aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorNikita Slyusarev <nslus@yandex-team.com>2022-02-10 16:46:53 +0300
committerDaniil Cherednik <dcherednik@yandex-team.ru>2022-02-10 16:46:53 +0300
commit469afdc4e2587bf62ecdd096b75a0baa444c4012 (patch)
tree49e222ea1c5804306084bb3ae065bb702625360f
parentcd77cecfc03a3eaf87816af28a33067c4f0cdb59 (diff)
downloadydb-469afdc4e2587bf62ecdd096b75a0baa444c4012.tar.gz
Restoring authorship annotation for Nikita Slyusarev <nslus@yandex-team.com>. Commit 2 of 2.
-rw-r--r--build/plugins/_common.py12
-rw-r--r--build/rules/autocheck.blacklist4
-rw-r--r--build/rules/local.blacklist2
-rw-r--r--build/rules/py2_deprecation/ya.make2
-rw-r--r--build/scripts/fix_msvc_output.py58
-rw-r--r--build/scripts/link_dyn_lib.py38
-rw-r--r--build/scripts/run_msvc_wine.py46
-rw-r--r--build/scripts/stdout2stderr.py12
-rw-r--r--build/ya.conf.json26
-rw-r--r--build/ya.make8
-rw-r--r--build/ymake.core.conf34
-rwxr-xr-xbuild/ymake_conf.py148
-rw-r--r--contrib/libs/curl/COPYING40
-rw-r--r--contrib/libs/curl/include/curl/curl.h3770
-rw-r--r--contrib/libs/curl/include/curl/curlver.h112
-rw-r--r--contrib/libs/curl/include/curl/easy.h194
-rw-r--r--contrib/libs/curl/include/curl/mprintf.h88
-rw-r--r--contrib/libs/curl/include/curl/multi.h722
-rw-r--r--contrib/libs/curl/include/curl/stdcheaders.h52
-rw-r--r--contrib/libs/curl/include/curl/typecheck-gcc.h504
-rw-r--r--contrib/libs/curl/lib/amigaos.c132
-rw-r--r--contrib/libs/curl/lib/amigaos.h70
-rw-r--r--contrib/libs/curl/lib/arpa_telnet.h204
-rw-r--r--contrib/libs/curl/lib/asyn-ares.c1102
-rw-r--r--contrib/libs/curl/lib/asyn-thread.c994
-rw-r--r--contrib/libs/curl/lib/asyn.h298
-rw-r--r--contrib/libs/curl/lib/base64.c306
-rw-r--r--contrib/libs/curl/lib/config-amigaos.h322
-rw-r--r--contrib/libs/curl/lib/config-dos.h344
-rw-r--r--contrib/libs/curl/lib/config-mac.h246
-rw-r--r--contrib/libs/curl/lib/config-os400.h1070
-rw-r--r--contrib/libs/curl/lib/config-riscos.h1004
-rw-r--r--contrib/libs/curl/lib/config-tpf.h1492
-rw-r--r--contrib/libs/curl/lib/config-vxworks.h1802
-rw-r--r--contrib/libs/curl/lib/config-win32.h1292
-rw-r--r--contrib/libs/curl/lib/config-win32ce.h880
-rw-r--r--contrib/libs/curl/lib/conncache.c368
-rw-r--r--contrib/libs/curl/lib/conncache.h80
-rw-r--r--contrib/libs/curl/lib/connect.c1736
-rw-r--r--contrib/libs/curl/lib/connect.h186
-rw-r--r--contrib/libs/curl/lib/content_encoding.c574
-rw-r--r--contrib/libs/curl/lib/content_encoding.h54
-rw-r--r--contrib/libs/curl/lib/cookie.c1978
-rw-r--r--contrib/libs/curl/lib/cookie.h174
-rw-r--r--contrib/libs/curl/lib/curl_addrinfo.c886
-rw-r--r--contrib/libs/curl/lib/curl_addrinfo.h160
-rw-r--r--contrib/libs/curl/lib/curl_base64.h58
-rw-r--r--contrib/libs/curl/lib/curl_config.h4
-rw-r--r--contrib/libs/curl/lib/curl_fnmatch.c430
-rw-r--r--contrib/libs/curl/lib/curl_fnmatch.h84
-rw-r--r--contrib/libs/curl/lib/curl_gethostname.c190
-rw-r--r--contrib/libs/curl/lib/curl_gethostname.h56
-rw-r--r--contrib/libs/curl/lib/curl_gssapi.c122
-rw-r--r--contrib/libs/curl/lib/curl_gssapi.h70
-rw-r--r--contrib/libs/curl/lib/curl_hmac.h88
-rw-r--r--contrib/libs/curl/lib/curl_ldap.h64
-rw-r--r--contrib/libs/curl/lib/curl_md4.h52
-rw-r--r--contrib/libs/curl/lib/curl_md5.h94
-rw-r--r--contrib/libs/curl/lib/curl_memory.h270
-rw-r--r--contrib/libs/curl/lib/curl_memrchr.c96
-rw-r--r--contrib/libs/curl/lib/curl_memrchr.h84
-rw-r--r--contrib/libs/curl/lib/curl_multibyte.c116
-rw-r--r--contrib/libs/curl/lib/curl_multibyte.h124
-rw-r--r--contrib/libs/curl/lib/curl_ntlm_core.c648
-rw-r--r--contrib/libs/curl/lib/curl_ntlm_core.h78
-rw-r--r--contrib/libs/curl/lib/curl_ntlm_wb.c554
-rw-r--r--contrib/libs/curl/lib/curl_ntlm_wb.h60
-rw-r--r--contrib/libs/curl/lib/curl_rtmp.c562
-rw-r--r--contrib/libs/curl/lib/curl_rtmp.h62
-rw-r--r--contrib/libs/curl/lib/curl_sasl.c246
-rw-r--r--contrib/libs/curl/lib/curl_sasl.h98
-rw-r--r--contrib/libs/curl/lib/curl_setup.h1090
-rw-r--r--contrib/libs/curl/lib/curl_setup_once.h980
-rw-r--r--contrib/libs/curl/lib/curl_sspi.c208
-rw-r--r--contrib/libs/curl/lib/curl_sspi.h422
-rw-r--r--contrib/libs/curl/lib/curl_threads.c208
-rw-r--r--contrib/libs/curl/lib/curl_threads.h102
-rw-r--r--contrib/libs/curl/lib/curlx.h184
-rw-r--r--contrib/libs/curl/lib/dict.c434
-rw-r--r--contrib/libs/curl/lib/dict.h54
-rw-r--r--contrib/libs/curl/lib/dotdot.c296
-rw-r--r--contrib/libs/curl/lib/dotdot.h42
-rw-r--r--contrib/libs/curl/lib/easy.c1502
-rw-r--r--contrib/libs/curl/lib/easyif.h58
-rw-r--r--contrib/libs/curl/lib/escape.c302
-rw-r--r--contrib/libs/curl/lib/escape.h56
-rw-r--r--contrib/libs/curl/lib/file.c818
-rw-r--r--contrib/libs/curl/lib/file.h76
-rw-r--r--contrib/libs/curl/lib/fileinfo.c72
-rw-r--r--contrib/libs/curl/lib/fileinfo.h54
-rw-r--r--contrib/libs/curl/lib/formdata.c1386
-rw-r--r--contrib/libs/curl/lib/formdata.h84
-rw-r--r--contrib/libs/curl/lib/ftp.c6570
-rw-r--r--contrib/libs/curl/lib/ftp.h282
-rw-r--r--contrib/libs/curl/lib/ftplistparser.c1690
-rw-r--r--contrib/libs/curl/lib/ftplistparser.h78
-rw-r--r--contrib/libs/curl/lib/getenv.c78
-rw-r--r--contrib/libs/curl/lib/getinfo.c548
-rw-r--r--contrib/libs/curl/lib/getinfo.h46
-rw-r--r--contrib/libs/curl/lib/gopher.c232
-rw-r--r--contrib/libs/curl/lib/gopher.h54
-rw-r--r--contrib/libs/curl/lib/hash.c482
-rw-r--r--contrib/libs/curl/lib/hash.h136
-rw-r--r--contrib/libs/curl/lib/hmac.c234
-rw-r--r--contrib/libs/curl/lib/hostasyn.c216
-rw-r--r--contrib/libs/curl/lib/hostcheck.c148
-rw-r--r--contrib/libs/curl/lib/hostcheck.h58
-rw-r--r--contrib/libs/curl/lib/hostip.c1088
-rw-r--r--contrib/libs/curl/lib/hostip.h362
-rw-r--r--contrib/libs/curl/lib/hostip4.c304
-rw-r--r--contrib/libs/curl/lib/hostip6.c292
-rw-r--r--contrib/libs/curl/lib/hostsyn.c192
-rw-r--r--contrib/libs/curl/lib/http.c4334
-rw-r--r--contrib/libs/curl/lib/http.h276
-rw-r--r--contrib/libs/curl/lib/http2.c202
-rw-r--r--contrib/libs/curl/lib/http2.h72
-rw-r--r--contrib/libs/curl/lib/http_chunks.c478
-rw-r--r--contrib/libs/curl/lib/http_chunks.h146
-rw-r--r--contrib/libs/curl/lib/http_digest.c214
-rw-r--r--contrib/libs/curl/lib/http_digest.h66
-rw-r--r--contrib/libs/curl/lib/http_negotiate.c134
-rw-r--r--contrib/libs/curl/lib/http_negotiate.h62
-rw-r--r--contrib/libs/curl/lib/http_proxy.c430
-rw-r--r--contrib/libs/curl/lib/http_proxy.h72
-rw-r--r--contrib/libs/curl/lib/idn_win32.c104
-rw-r--r--contrib/libs/curl/lib/if2ip.c294
-rw-r--r--contrib/libs/curl/lib/if2ip.h138
-rw-r--r--contrib/libs/curl/lib/imap.c3166
-rw-r--r--contrib/libs/curl/lib/imap.h152
-rw-r--r--contrib/libs/curl/lib/inet_ntop.c356
-rw-r--r--contrib/libs/curl/lib/inet_ntop.h68
-rw-r--r--contrib/libs/curl/lib/inet_pton.c442
-rw-r--r--contrib/libs/curl/lib/inet_pton.h68
-rw-r--r--contrib/libs/curl/lib/krb5.c562
-rw-r--r--contrib/libs/curl/lib/ldap.c988
-rw-r--r--contrib/libs/curl/lib/llist.c240
-rw-r--r--contrib/libs/curl/lib/llist.h66
-rw-r--r--contrib/libs/curl/lib/md4.c98
-rw-r--r--contrib/libs/curl/lib/md5.c464
-rw-r--r--contrib/libs/curl/lib/memdebug.c628
-rw-r--r--contrib/libs/curl/lib/memdebug.h218
-rw-r--r--contrib/libs/curl/lib/mprintf.c1794
-rw-r--r--contrib/libs/curl/lib/multi.c2958
-rw-r--r--contrib/libs/curl/lib/multihandle.h176
-rw-r--r--contrib/libs/curl/lib/multiif.h134
-rw-r--r--contrib/libs/curl/lib/netrc.c194
-rw-r--r--contrib/libs/curl/lib/netrc.h68
-rw-r--r--contrib/libs/curl/lib/non-ascii.c500
-rw-r--r--contrib/libs/curl/lib/non-ascii.h104
-rw-r--r--contrib/libs/curl/lib/nonblock.c170
-rw-r--r--contrib/libs/curl/lib/nonblock.h56
-rw-r--r--contrib/libs/curl/lib/openldap.c1088
-rw-r--r--contrib/libs/curl/lib/parsedate.c872
-rw-r--r--contrib/libs/curl/lib/parsedate.h56
-rw-r--r--contrib/libs/curl/lib/pingpong.c810
-rw-r--r--contrib/libs/curl/lib/pingpong.h274
-rw-r--r--contrib/libs/curl/lib/pop3.c2344
-rw-r--r--contrib/libs/curl/lib/pop3.h174
-rw-r--r--contrib/libs/curl/lib/progress.c500
-rw-r--r--contrib/libs/curl/lib/progress.h94
-rw-r--r--contrib/libs/curl/lib/rtsp.c1198
-rw-r--r--contrib/libs/curl/lib/rtsp.h128
-rw-r--r--contrib/libs/curl/lib/select.c516
-rw-r--r--contrib/libs/curl/lib/select.h178
-rw-r--r--contrib/libs/curl/lib/sendf.c702
-rw-r--r--contrib/libs/curl/lib/sendf.h158
-rw-r--r--contrib/libs/curl/lib/setup-os400.h372
-rw-r--r--contrib/libs/curl/lib/setup-vms.h670
-rw-r--r--contrib/libs/curl/lib/share.c442
-rw-r--r--contrib/libs/curl/lib/share.h106
-rw-r--r--contrib/libs/curl/lib/slist.c276
-rw-r--r--contrib/libs/curl/lib/slist.h74
-rw-r--r--contrib/libs/curl/lib/smtp.c2098
-rw-r--r--contrib/libs/curl/lib/smtp.h160
-rw-r--r--contrib/libs/curl/lib/sockaddr.h80
-rw-r--r--contrib/libs/curl/lib/socks.c482
-rw-r--r--contrib/libs/curl/lib/socks.h116
-rw-r--r--contrib/libs/curl/lib/socks_gssapi.c846
-rw-r--r--contrib/libs/curl/lib/socks_sspi.c1016
-rw-r--r--contrib/libs/curl/lib/speedcheck.c76
-rw-r--r--contrib/libs/curl/lib/speedcheck.h56
-rw-r--r--contrib/libs/curl/lib/splay.c422
-rw-r--r--contrib/libs/curl/lib/splay.h82
-rw-r--r--contrib/libs/curl/lib/strdup.c78
-rw-r--r--contrib/libs/curl/lib/strdup.h56
-rw-r--r--contrib/libs/curl/lib/strerror.c1334
-rw-r--r--contrib/libs/curl/lib/strerror.h58
-rw-r--r--contrib/libs/curl/lib/strtok.c126
-rw-r--r--contrib/libs/curl/lib/strtok.h64
-rw-r--r--contrib/libs/curl/lib/strtoofft.c358
-rw-r--r--contrib/libs/curl/lib/strtoofft.h86
-rw-r--r--contrib/libs/curl/lib/telnet.c2686
-rw-r--r--contrib/libs/curl/lib/telnet.h52
-rw-r--r--contrib/libs/curl/lib/tftp.c2274
-rw-r--r--contrib/libs/curl/lib/tftp.h52
-rw-r--r--contrib/libs/curl/lib/timeval.c176
-rw-r--r--contrib/libs/curl/lib/timeval.h74
-rw-r--r--contrib/libs/curl/lib/transfer.c2288
-rw-r--r--contrib/libs/curl/lib/transfer.h84
-rw-r--r--contrib/libs/curl/lib/url.c3328
-rw-r--r--contrib/libs/curl/lib/url.h80
-rw-r--r--contrib/libs/curl/lib/urldata.h1858
-rw-r--r--contrib/libs/curl/lib/version.c502
-rw-r--r--contrib/libs/curl/lib/warnless.c872
-rw-r--r--contrib/libs/curl/lib/warnless.h150
-rw-r--r--contrib/libs/curl/lib/wildcard.c92
-rw-r--r--contrib/libs/curl/lib/wildcard.h94
-rw-r--r--contrib/libs/curl/lib/x509asn1.c1524
-rw-r--r--contrib/libs/curl/lib/x509asn1.h172
-rw-r--r--contrib/libs/curl/ya.make64
-rw-r--r--contrib/libs/jemalloc/src/zone.c36
-rw-r--r--contrib/libs/jemalloc/ya.make2
-rw-r--r--contrib/libs/ya.make16
-rw-r--r--contrib/python/PyYAML/py2/ya.make2
-rw-r--r--contrib/python/PyYAML/py3/ya.make2
-rw-r--r--contrib/python/PyYAML/ya.make4
-rw-r--r--contrib/python/cryptography/.dist-info/METADATA202
-rw-r--r--contrib/python/cryptography/.dist-info/top_level.txt2
-rw-r--r--contrib/python/cryptography/ya.make12
-rw-r--r--contrib/python/ipython/py2/IPython/core/alias.py6
-rw-r--r--contrib/python/ipython/py2/IPython/core/application.py162
-rw-r--r--contrib/python/ipython/py2/IPython/core/builtin_trap.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/completer.py208
-rw-r--r--contrib/python/ipython/py2/IPython/core/completerlib.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/debugger.py120
-rw-r--r--contrib/python/ipython/py2/IPython/core/display.py118
-rw-r--r--contrib/python/ipython/py2/IPython/core/displayhook.py28
-rw-r--r--contrib/python/ipython/py2/IPython/core/displaypub.py16
-rw-r--r--contrib/python/ipython/py2/IPython/core/events.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/excolors.py60
-rw-r--r--contrib/python/ipython/py2/IPython/core/extensions.py18
-rw-r--r--contrib/python/ipython/py2/IPython/core/formatters.py68
-rw-r--r--contrib/python/ipython/py2/IPython/core/history.py132
-rw-r--r--contrib/python/ipython/py2/IPython/core/historyapp.py26
-rw-r--r--contrib/python/ipython/py2/IPython/core/hooks.py26
-rw-r--r--contrib/python/ipython/py2/IPython/core/interactiveshell.py636
-rw-r--r--contrib/python/ipython/py2/IPython/core/magic.py16
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/auto.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/basic.py28
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/code.py74
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/config.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/display.py32
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/execution.py122
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/history.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/logging.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/osm.py8
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/pylab.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/script.py16
-rw-r--r--contrib/python/ipython/py2/IPython/core/oinspect.py356
-rw-r--r--contrib/python/ipython/py2/IPython/core/page.py34
-rw-r--r--contrib/python/ipython/py2/IPython/core/prefilter.py44
-rw-r--r--contrib/python/ipython/py2/IPython/core/profileapp.py22
-rw-r--r--contrib/python/ipython/py2/IPython/core/profiledir.py34
-rw-r--r--contrib/python/ipython/py2/IPython/core/prompts.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/pylabtools.py8
-rw-r--r--contrib/python/ipython/py2/IPython/core/release.py6
-rw-r--r--contrib/python/ipython/py2/IPython/core/shellapp.py108
-rw-r--r--contrib/python/ipython/py2/IPython/core/ultratb.py108
-rw-r--r--contrib/python/ipython/py2/IPython/core/usage.py12
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/storemagic.py8
-rw-r--r--contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py6
-rw-r--r--contrib/python/ipython/py2/IPython/lib/backgroundjobs.py2
-rw-r--r--contrib/python/ipython/py2/IPython/lib/deepreload.py8
-rw-r--r--contrib/python/ipython/py2/IPython/lib/demo.py28
-rw-r--r--contrib/python/ipython/py2/IPython/lib/display.py2
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhook.py230
-rw-r--r--contrib/python/ipython/py2/IPython/lib/latextools.py34
-rw-r--r--contrib/python/ipython/py2/IPython/lib/lexers.py20
-rw-r--r--contrib/python/ipython/py2/IPython/lib/pretty.py38
-rw-r--r--contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py2
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/debugger.py148
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/embed.py66
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/interactiveshell.py706
-rwxr-xr-xcontrib/python/ipython/py2/IPython/terminal/ipapp.py54
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/magics.py410
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/prompts.py140
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py84
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py282
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py118
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py24
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py274
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py136
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py54
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py190
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py296
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/ptshell.py16
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/ptutils.py206
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/shortcuts.py374
-rw-r--r--contrib/python/ipython/py2/IPython/testing/decorators.py4
-rw-r--r--contrib/python/ipython/py2/IPython/testing/globalipapp.py18
-rw-r--r--contrib/python/ipython/py2/IPython/testing/iptest.py10
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py16
-rw-r--r--contrib/python/ipython/py2/IPython/testing/skipdoctest.py10
-rw-r--r--contrib/python/ipython/py2/IPython/testing/tools.py16
-rw-r--r--contrib/python/ipython/py2/IPython/utils/PyColorize.py86
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_common.py18
-rw-r--r--contrib/python/ipython/py2/IPython/utils/colorable.py52
-rw-r--r--contrib/python/ipython/py2/IPython/utils/contexts.py22
-rw-r--r--contrib/python/ipython/py2/IPython/utils/dir2.py72
-rw-r--r--contrib/python/ipython/py2/IPython/utils/io.py40
-rw-r--r--contrib/python/ipython/py2/IPython/utils/path.py18
-rw-r--r--contrib/python/ipython/py2/IPython/utils/py3compat.py4
-rw-r--r--contrib/python/ipython/py2/IPython/utils/terminal.py16
-rw-r--r--contrib/python/ipython/py2/IPython/utils/text.py14
-rw-r--r--contrib/python/ipython/py2/IPython/utils/tokenutil.py2
-rw-r--r--contrib/python/ipython/py2/IPython/utils/warn.py38
-rw-r--r--contrib/python/ipython/ya.make2
-rw-r--r--contrib/python/jedi/ya.make2
-rw-r--r--contrib/python/pexpect/ya.make4
-rw-r--r--contrib/python/pickleshare/ya.make2
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/__init__.py4
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/application.py88
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py532
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/cache.py222
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/clipboard/in_memory.py2
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/completion.py60
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/completers/filesystem.py10
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/compiler.py2
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/lexer.py50
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/validation.py2
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/telnet/server.py2
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/validators/base.py6
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py708
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/enums.py12
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_posix.py8
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_win32.py4
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/base.py10
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/inputhook.py30
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py84
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py82
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/select.py432
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/win32.py44
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/base.py82
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/cli.py420
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/types.py48
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/utils.py8
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/history.py4
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/input.py56
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py568
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py164
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py322
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/emacs.py198
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py788
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/scroll.py128
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/utils.py8
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py1580
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/digraphs.py2756
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/input_processor.py262
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/manager.py20
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/registry.py138
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/vi_state.py54
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/keys.py54
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/__init__.py2
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py1412
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py726
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py542
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/margins.py276
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/menus.py144
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py676
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/prompt.py14
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/screen.py18
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/toolbars.py44
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py118
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/mouse_events.py10
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py114
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/renderer.py100
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/selection.py6
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py576
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/__init__.py42
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/base.py172
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/defaults.py190
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_dict.py294
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_pygments.py142
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/utils.py90
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/conemu_output.py4
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_input.py236
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py674
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_input.py196
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_output.py182
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/token.py94
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/utils.py184
-rw-r--r--contrib/python/prompt-toolkit/py2/prompt_toolkit/validation.py2
-rw-r--r--contrib/python/prompt-toolkit/py2/ya.make28
-rw-r--r--contrib/python/prompt-toolkit/ya.make4
-rw-r--r--contrib/python/py/ya.make2
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/application.py256
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/configurable.py100
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/loader.py78
-rw-r--r--contrib/python/traitlets/py2/traitlets/config/manager.py2
-rw-r--r--contrib/python/traitlets/py2/traitlets/log.py12
-rw-r--r--contrib/python/traitlets/py2/traitlets/traitlets.py1026
-rw-r--r--contrib/python/traitlets/py2/traitlets/utils/bunch.py50
-rw-r--r--contrib/python/traitlets/py2/traitlets/utils/getargspec.py2
-rw-r--r--contrib/python/traitlets/py2/traitlets/utils/importstring.py4
-rw-r--r--contrib/python/traitlets/py2/ya.make4
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/application.py220
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/configurable.py88
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/loader.py62
-rw-r--r--contrib/python/traitlets/py3/traitlets/log.py12
-rw-r--r--contrib/python/traitlets/py3/traitlets/traitlets.py754
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/bunch.py50
-rw-r--r--contrib/python/traitlets/py3/ya.make4
-rw-r--r--contrib/python/ya.make64
-rw-r--r--contrib/tools/bison/bison/arcadia_root.cpp.in20
-rw-r--r--contrib/tools/bison/bison/arcadia_root.h28
-rw-r--r--contrib/tools/bison/bison/src/output.c6
-rw-r--r--contrib/tools/bison/bison/ya.make4
-rw-r--r--contrib/tools/bison/gnulib/platform/win64/config.h12
-rw-r--r--contrib/tools/bison/gnulib/platform/win64/fcntl.h20
-rw-r--r--contrib/tools/bison/gnulib/platform/win64/locale.h20
-rw-r--r--contrib/tools/bison/gnulib/platform/win64/math.h10
-rw-r--r--contrib/tools/bison/gnulib/platform/win64/signal.h20
-rw-r--r--contrib/tools/bison/gnulib/platform/win64/sys/stat.h20
-rw-r--r--contrib/tools/bison/gnulib/src/fpurge.c10
-rw-r--r--contrib/tools/bison/gnulib/src/freadahead.c8
-rw-r--r--contrib/tools/bison/gnulib/src/freading.c4
-rw-r--r--contrib/tools/bison/gnulib/src/fseeko.c6
-rw-r--r--contrib/tools/bison/gnulib/src/fseterr.c4
-rw-r--r--contrib/tools/bison/gnulib/src/snprintf.c4
-rw-r--r--contrib/tools/bison/gnulib/win_sdk10.h110
-rw-r--r--contrib/tools/python/ya.make4
-rw-r--r--library/cpp/accurate_accumulate/benchmark/metrics/ya.make4
-rw-r--r--library/cpp/accurate_accumulate/benchmark/ya.make2
-rw-r--r--library/cpp/actors/core/ut/ya.make10
-rw-r--r--library/cpp/actors/core/ya.make14
-rw-r--r--library/cpp/actors/helpers/ya.make2
-rw-r--r--library/cpp/actors/interconnect/ut/ya.make2
-rw-r--r--library/cpp/actors/memory_log/ya.make8
-rw-r--r--library/cpp/actors/prof/ut/ya.make8
-rw-r--r--library/cpp/actors/prof/ya.make10
-rw-r--r--library/cpp/actors/util/ut/ya.make8
-rw-r--r--library/cpp/actors/wilson/ya.make20
-rw-r--r--library/cpp/blockcodecs/fuzz/ya.make8
-rw-r--r--library/cpp/blockcodecs/ut/ya.make6
-rw-r--r--library/cpp/build_info/ya.make2
-rw-r--r--library/cpp/cgiparam/fuzz/ya.make8
-rw-r--r--library/cpp/codecs/static/example/ya.make8
-rw-r--r--library/cpp/codecs/static/tools/common/ya.make4
-rw-r--r--library/cpp/codecs/static/tools/static_codec_checker/ya.make2
-rw-r--r--library/cpp/codecs/static/tools/static_codec_generator/ya.make2
-rw-r--r--library/cpp/comptable/usage/ya.make10
-rw-r--r--library/cpp/comptable/ut/ya.make6
-rw-r--r--library/cpp/comptable/ya.make10
-rw-r--r--library/cpp/containers/comptrie/loader/ut/ya.make2
-rw-r--r--library/cpp/containers/intrusive_avl_tree/ut/ya.make8
-rw-r--r--library/cpp/containers/intrusive_avl_tree/ya.make8
-rw-r--r--library/cpp/containers/intrusive_rb_tree/fuzz/ya.make10
-rw-r--r--library/cpp/containers/intrusive_rb_tree/ut/ya.make8
-rw-r--r--library/cpp/containers/intrusive_rb_tree/ya.make8
-rw-r--r--library/cpp/containers/ring_buffer/ya.make2
-rw-r--r--library/cpp/coroutine/engine/ya.make2
-rw-r--r--library/cpp/deprecated/enum_codegen/ut/ya.make6
-rw-r--r--library/cpp/diff/ya.make4
-rw-r--r--library/cpp/digest/argonish/benchmark/ya.make10
-rw-r--r--library/cpp/digest/argonish/internal/blake2b/ya.make4
-rw-r--r--library/cpp/digest/argonish/internal/blamka/ya.make4
-rw-r--r--library/cpp/digest/argonish/ut/ya.make10
-rw-r--r--library/cpp/digest/argonish/ut_fat/ya.make16
-rw-r--r--library/cpp/digest/lower_case/ut/ya.make8
-rw-r--r--library/cpp/digest/md5/bench/ya.make8
-rw-r--r--library/cpp/digest/md5/medium_ut/ya.make10
-rw-r--r--library/cpp/digest/md5/ut/ya.make8
-rw-r--r--library/cpp/digest/md5/ya.make8
-rw-r--r--library/cpp/digest/old_crc/crc.cpp2
-rw-r--r--library/cpp/digest/old_crc/ut/ya.make8
-rw-r--r--library/cpp/digest/old_crc/ya.make14
-rw-r--r--library/cpp/digest/sfh/ut/ya.make8
-rw-r--r--library/cpp/digest/sfh/ya.make8
-rw-r--r--library/cpp/histogram/adaptive/protos/python/ya.make2
-rw-r--r--library/cpp/histogram/hdr/ut/ya.make8
-rw-r--r--library/cpp/histogram/hdr/ya.make8
-rw-r--r--library/cpp/html/escape/ut/ya.make2
-rw-r--r--library/cpp/html/escape/ya.make2
-rw-r--r--library/cpp/http/fetch/ya.make2
-rw-r--r--library/cpp/http/io/fuzz/ya.make8
-rw-r--r--library/cpp/int128/ya.make2
-rw-r--r--library/cpp/json/fast_sax/ya.make8
-rw-r--r--library/cpp/json/flex_buffers/ya.make2
-rw-r--r--library/cpp/json/ut/json_reader_ut.cpp34
-rw-r--r--library/cpp/json/writer/ya.make10
-rw-r--r--library/cpp/json/ya.make8
-rw-r--r--library/cpp/json/yson/ut/ya.make2
-rw-r--r--library/cpp/lfalloc/dbg/ya.make12
-rw-r--r--library/cpp/lfalloc/dbg_info/ya.make2
-rw-r--r--library/cpp/lfalloc/ya.make2
-rw-r--r--library/cpp/lfalloc/yt/ya.make4
-rw-r--r--library/cpp/linear_regression/benchmark/ya.make2
-rw-r--r--library/cpp/linear_regression/ut/ya.make2
-rw-r--r--library/cpp/linear_regression/ya.make2
-rw-r--r--library/cpp/malloc/ya.make2
-rw-r--r--library/cpp/messagebus/remote_connection_status.cpp2
-rw-r--r--library/cpp/messagebus/test/perftest/perftest.cpp2
-rw-r--r--library/cpp/messagebus/test/ut/ya.make12
-rw-r--r--library/cpp/monlib/deprecated/json/ut/ya.make8
-rw-r--r--library/cpp/monlib/deprecated/json/ya.make8
-rw-r--r--library/cpp/monlib/dynamic_counters/ya.make8
-rw-r--r--library/cpp/monlib/encode/buffered/ut/ya.make8
-rw-r--r--library/cpp/monlib/encode/buffered/ya.make10
-rw-r--r--library/cpp/monlib/encode/fake/ya.make8
-rw-r--r--library/cpp/monlib/encode/json/fuzz/ya.make14
-rw-r--r--library/cpp/monlib/encode/json/ut/ya.make8
-rw-r--r--library/cpp/monlib/encode/json/ya.make8
-rw-r--r--library/cpp/monlib/encode/legacy_protobuf/ut/ya.make12
-rw-r--r--library/cpp/monlib/encode/legacy_protobuf/ya.make8
-rw-r--r--library/cpp/monlib/encode/protobuf/protos/ya.make8
-rw-r--r--library/cpp/monlib/encode/protobuf/ya.make8
-rw-r--r--library/cpp/monlib/encode/spack/fuzz/ya.make16
-rw-r--r--library/cpp/monlib/encode/spack/ut/ya.make8
-rw-r--r--library/cpp/monlib/encode/spack/ya.make8
-rw-r--r--library/cpp/monlib/encode/text/ut/ya.make8
-rw-r--r--library/cpp/monlib/encode/text/ya.make8
-rw-r--r--library/cpp/monlib/encode/ut/ya.make8
-rw-r--r--library/cpp/monlib/encode/ya.make8
-rw-r--r--library/cpp/monlib/metrics/ut/ya.make8
-rw-r--r--library/cpp/monlib/metrics/ya.make8
-rw-r--r--library/cpp/monlib/ya.make8
-rw-r--r--library/cpp/openssl/io/ut/ya.make8
-rw-r--r--library/cpp/protobuf/json/ut/inline_ut.cpp2
-rw-r--r--library/cpp/protobuf/json/ut/json2proto_ut.cpp2
-rw-r--r--library/cpp/protobuf/json/ut/proto2json_ut.cpp2
-rw-r--r--library/cpp/protobuf/json/ut/ya.make4
-rw-r--r--library/cpp/random_provider/ya.make8
-rw-r--r--library/cpp/regex/hyperscan/ut/ya.make2
-rw-r--r--library/cpp/regex/hyperscan/ya.make2
-rw-r--r--library/cpp/regex/pire/inline/ya.make14
-rw-r--r--library/cpp/regex/pire/ut/ya.make8
-rw-r--r--library/cpp/regex/pire/ya.make14
-rw-r--r--library/cpp/retry/ut/ya.make10
-rw-r--r--library/cpp/retry/ya.make8
-rw-r--r--library/cpp/scheme/ya.make2
-rw-r--r--library/cpp/streams/brotli/ut/ya.make8
-rw-r--r--library/cpp/streams/brotli/ya.make8
-rw-r--r--library/cpp/streams/bzip2/ut/ya.make8
-rw-r--r--library/cpp/streams/bzip2/ya.make8
-rw-r--r--library/cpp/streams/lz/ut/ya.make8
-rw-r--r--library/cpp/streams/lz/ya.make8
-rw-r--r--library/cpp/streams/zc_memory_input/ya.make8
-rw-r--r--library/cpp/string_utils/base64/bench/metrics/ya.make2
-rw-r--r--library/cpp/string_utils/levenshtein_diff/ut/ya.make6
-rw-r--r--library/cpp/testing/benchmark/examples/metrics/ya.make2
-rw-r--r--library/cpp/testing/benchmark/main/ya.make8
-rw-r--r--library/cpp/testing/benchmark/ya.make8
-rw-r--r--library/cpp/testing/unittest/fat/ya.make10
-rw-r--r--library/cpp/threading/future/perf/ya.make8
-rw-r--r--library/cpp/threading/future/ut/ya.make8
-rw-r--r--library/cpp/threading/light_rw_lock/ut/ya.make2
-rw-r--r--library/cpp/threading/poor_man_openmp/ut/ya.make8
-rw-r--r--library/cpp/threading/queue/ut/ya.make2
-rw-r--r--library/cpp/time_provider/ya.make8
-rw-r--r--library/cpp/timezone_conversion/ya.make8
-rw-r--r--library/cpp/tld/ya.make8
-rw-r--r--library/cpp/tvmauth/src/rw/ut_large/ya.make10
-rw-r--r--library/cpp/unicode/normalization/generated/decomposition.cpp8
-rw-r--r--library/cpp/unicode/ya.make4
-rw-r--r--library/cpp/uri/ut/ya.make2
-rw-r--r--library/cpp/yson_pull/ya.make2
-rw-r--r--library/python/cores/ya.make2
-rw-r--r--library/python/filelock/__init__.py24
-rw-r--r--library/python/filelock/ut/lib/test_filelock.py18
-rw-r--r--library/python/filelock/ut/lib/ya.make2
-rw-r--r--library/python/filelock/ya.make6
-rw-r--r--library/python/find_root/ya.make2
-rw-r--r--library/python/fs/__init__.py492
-rw-r--r--library/python/fs/test/test_fs.py1584
-rw-r--r--library/python/pytest/allure/ya.make8
-rw-r--r--library/python/pytest/empty/ya.make14
-rw-r--r--library/python/pytest/ya.make8
-rw-r--r--library/python/pytest/yatest_tools.py8
-rw-r--r--library/python/reservoir_sampling/ya.make2
-rw-r--r--library/python/resource/ut/lib/ya.make2
-rw-r--r--library/python/resource/ya.make6
-rw-r--r--library/python/runtime_py3/main/ya.make8
-rw-r--r--library/python/runtime_py3/test/traceback/ya.make12
-rw-r--r--library/python/runtime_py3/test/ya.make10
-rw-r--r--library/python/runtime_py3/ya.make12
-rw-r--r--library/python/strings/strings.py100
-rw-r--r--library/python/strings/ut/test_strings.py258
-rw-r--r--library/python/strings/ut/ya.make2
-rw-r--r--library/python/strings/ya.make6
-rw-r--r--library/python/symbols/python/ut/ya.make4
-rw-r--r--library/python/symbols/python/ya.make4
-rw-r--r--library/python/testing/import_test/ya.make6
-rw-r--r--library/python/testing/recipe/ya.make6
-rw-r--r--library/python/testing/yatest_common/yatest/common/canonical.py20
-rw-r--r--library/python/testing/yatest_common/yatest/common/network.py2
-rw-r--r--library/python/testing/yatest_common/yatest/common/path.py2
-rw-r--r--library/python/testing/yatest_lib/ya.make4
-rw-r--r--library/python/windows/__init__.py538
-rw-r--r--library/python/windows/ut/test_windows.py162
-rw-r--r--library/python/windows/ut/ya.make2
-rw-r--r--library/python/ya.make8
-rw-r--r--library/ya.make2
-rw-r--r--tools/enum_parser/enum_parser/main.cpp20
-rw-r--r--tools/ya.make8
-rw-r--r--util/charset/benchmark/to_lower/metrics/ya.make4
-rw-r--r--util/charset/benchmark/to_lower/ya.make2
-rw-r--r--util/charset/benchmark/utf8_to_wide/metrics/ya.make4
-rw-r--r--util/charset/unidata.h6
-rw-r--r--util/charset/ya.make8
-rw-r--r--util/draft/ut/ya.make8
-rw-r--r--util/folder/dirut.cpp12
-rw-r--r--util/folder/dirut.h2
-rw-r--r--util/folder/dirut_ut.cpp34
-rw-r--r--util/folder/path.h8
-rw-r--r--util/folder/path_ut.cpp64
-rw-r--r--util/folder/pathsplit.cpp6
-rw-r--r--util/folder/pathsplit.h6
-rw-r--r--util/folder/pathsplit_ut.cpp556
-rw-r--r--util/generic/benchmark/fastclp2/metrics/ya.make4
-rw-r--r--util/generic/benchmark/log2/metrics/ya.make4
-rw-r--r--util/generic/benchmark/rotate_bits/metrics/ya.make4
-rw-r--r--util/generic/benchmark/vector_count_ctor/metrics/ya.make4
-rw-r--r--util/generic/bitmap.h44
-rw-r--r--util/generic/bitmap_ut.cpp140
-rw-r--r--util/generic/fuzz/vector/ya.make8
-rw-r--r--util/generic/is_in.h6
-rw-r--r--util/generic/is_in_ut.cpp14
-rw-r--r--util/memory/benchmark/pool/metrics/ya.make6
-rw-r--r--util/memory/benchmark/pool/ya.make2
-rw-r--r--util/memory/benchmark/ya.make2
-rw-r--r--util/random/benchmark/prng/metrics/ya.make4
-rw-r--r--util/string/benchmark/float_to_string/metrics/ya.make4
-rw-r--r--util/string/benchmark/float_to_string/ya.make6
-rw-r--r--util/string/benchmark/join/metrics/ya.make4
-rw-r--r--util/string/benchmark/subst_global/metrics/ya.make4
-rw-r--r--util/string/benchmark/subst_global/ya.make6
-rw-r--r--util/string/fuzzing/collapse/ya.make8
-rw-r--r--util/string/fuzzing/strtod/ya.make8
-rw-r--r--util/system/benchmark/cpu_id/metrics/ya.make4
-rw-r--r--util/system/benchmark/create_destroy_thread/metrics/ya.make4
-rw-r--r--util/system/benchmark/create_destroy_thread/ya.make2
-rw-r--r--util/system/getpid.cpp2
-rw-r--r--util/system/getpid.h18
-rw-r--r--util/system/getpid_ut.cpp2
-rw-r--r--util/system/shellcommand.cpp24
-rw-r--r--util/system/shellcommand_ut.cpp6
-rw-r--r--util/system/ut/ya.make6
-rw-r--r--util/tests/cython/ya.make4
-rw-r--r--util/tests/sym_versions/ya.make44
-rw-r--r--util/tests/ya.make6
-rw-r--r--util/ya.make16
-rwxr-xr-xya.bat162
-rw-r--r--ydb/core/blobstorage/vdisk/handoff/handoff_delegate.h2
-rw-r--r--ydb/library/yql/public/udf/udfs_exports.exports4
644 files changed, 69330 insertions, 69330 deletions
diff --git a/build/plugins/_common.py b/build/plugins/_common.py
index d74e2387de..2f831a94db 100644
--- a/build/plugins/_common.py
+++ b/build/plugins/_common.py
@@ -52,8 +52,8 @@ def stripext(fname):
def tobuilddir(fname):
- if not fname:
- return '$B'
+ if not fname:
+ return '$B'
if fname.startswith('$S'):
return fname.replace('$S', '$B', 1)
else:
@@ -113,14 +113,14 @@ def resolve_to_abs_path(path, source_root, build_root):
if path.startswith('$B') and build_root is not None:
return path.replace('$B', build_root, 1)
return path
-
-
+
+
def resolve_to_ymake_path(path):
return resolve_to_abs_path(path, '${ARCADIA_ROOT}', '${ARCADIA_BUILD_ROOT}')
-def join_intl_paths(*args):
- return '/'.join(args)
+def join_intl_paths(*args):
+ return '/'.join(args)
def get(fun, num):
diff --git a/build/rules/autocheck.blacklist b/build/rules/autocheck.blacklist
index 07282ba68d..8711560ed3 100644
--- a/build/rules/autocheck.blacklist
+++ b/build/rules/autocheck.blacklist
@@ -9,7 +9,7 @@ data-ui/unity
direct/frontend/services
direct/frontend/packages
drive/pyback
-fintech/frontend
+fintech/frontend
frontend
games/frontend
junk
@@ -19,7 +19,7 @@ maps/front
mobile
music/frontend
serp/hermione
-zen/frontend
+zen/frontend
taxi/lavka/frontend
velocity/error-booster/error-booster-queue
velocity/error-booster/market
diff --git a/build/rules/local.blacklist b/build/rules/local.blacklist
index 0612cdeb60..46d8cff894 100644
--- a/build/rules/local.blacklist
+++ b/build/rules/local.blacklist
@@ -1,3 +1,3 @@
# Local blacklist
# The list of top level directories excluded from local build
-mobile
+mobile
diff --git a/build/rules/py2_deprecation/ya.make b/build/rules/py2_deprecation/ya.make
index 14295798da..f488d5e97b 100644
--- a/build/rules/py2_deprecation/ya.make
+++ b/build/rules/py2_deprecation/ya.make
@@ -1,6 +1,6 @@
OWNER(g:ymake)
RESOURCES_LIBRARY()
-MESSAGE(WARNING You are using deprecated Python2-only code. Please consider rewriting to Python 3. To list all such errors use `ya make -DFAIL_PY2`.)
+MESSAGE(WARNING You are using deprecated Python2-only code. Please consider rewriting to Python 3. To list all such errors use `ya make -DFAIL_PY2`.)
END()
diff --git a/build/scripts/fix_msvc_output.py b/build/scripts/fix_msvc_output.py
index 4fda5b6321..b2e7d38307 100644
--- a/build/scripts/fix_msvc_output.py
+++ b/build/scripts/fix_msvc_output.py
@@ -1,13 +1,13 @@
-import subprocess
-import sys
-
+import subprocess
+import sys
+
import process_command_files as pcf
import process_whole_archive_option as pwa
-
-def out2err(cmd):
- return subprocess.Popen(cmd, stdout=sys.stderr).wait()
-
-
+
+def out2err(cmd):
+ return subprocess.Popen(cmd, stdout=sys.stderr).wait()
+
+
def decoding_needed(strval):
if sys.version_info >= (3, 0, 0):
return isinstance(strval, bytes)
@@ -15,28 +15,28 @@ def decoding_needed(strval):
return False
-def out2err_cut_first_line(cmd):
- p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
- first_line = True
- while True:
- line = p.stdout.readline()
+def out2err_cut_first_line(cmd):
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ first_line = True
+ while True:
+ line = p.stdout.readline()
line = line.decode('utf-8') if decoding_needed(line) else line
- if not line:
- break
- if first_line:
- sys.stdout.write(line)
- first_line = False
- else:
- sys.stderr.write(line)
- return p.wait()
-
-
-if __name__ == '__main__':
+ if not line:
+ break
+ if first_line:
+ sys.stdout.write(line)
+ first_line = False
+ else:
+ sys.stderr.write(line)
+ return p.wait()
+
+
+if __name__ == '__main__':
mode = sys.argv[1]
args, wa_peers, wa_libs = pwa.get_whole_archive_peers_and_libs(pcf.skip_markers(sys.argv[2:]))
cmd = pwa.ProcessWholeArchiveOption('WINDOWS', wa_peers, wa_libs).construct_cmd(args)
- run = out2err
- if mode in ('cl', 'ml'):
- # First line of cl.exe and ml64.exe stdout is useless: it prints input file
- run = out2err_cut_first_line
- sys.exit(run(cmd))
+ run = out2err
+ if mode in ('cl', 'ml'):
+ # First line of cl.exe and ml64.exe stdout is useless: it prints input file
+ run = out2err_cut_first_line
+ sys.exit(run(cmd))
diff --git a/build/scripts/link_dyn_lib.py b/build/scripts/link_dyn_lib.py
index 1b48e6a204..23487f5c1e 100644
--- a/build/scripts/link_dyn_lib.py
+++ b/build/scripts/link_dyn_lib.py
@@ -112,31 +112,31 @@ def fix_gnu_param(arch, ex):
return ret
-def fix_windows_param(ex):
- with tempfile.NamedTemporaryFile(delete=False) as def_file:
- exports = []
- for item in ex:
- if item.get('lang') == 'C':
- exports.append(item.get('sym'))
- def_file.write('EXPORTS\n')
- for export in exports:
- def_file.write(' {}\n'.format(export))
- return ['/DEF:{}'.format(def_file.name)]
-
-
+def fix_windows_param(ex):
+ with tempfile.NamedTemporaryFile(delete=False) as def_file:
+ exports = []
+ for item in ex:
+ if item.get('lang') == 'C':
+ exports.append(item.get('sym'))
+ def_file.write('EXPORTS\n')
+ for export in exports:
+ def_file.write(' {}\n'.format(export))
+ return ['/DEF:{}'.format(def_file.name)]
+
+
musl_libs = '-lc', '-lcrypt', '-ldl', '-lm', '-lpthread', '-lrt', '-lutil'
def fix_cmd(arch, musl, c):
- if arch == 'WINDOWS':
- prefix = '/DEF:'
- f = fix_windows_param
+ if arch == 'WINDOWS':
+ prefix = '/DEF:'
+ f = fix_windows_param
else:
- prefix = '-Wl,--version-script='
+ prefix = '-Wl,--version-script='
if arch in ('DARWIN', 'IOS'):
- f = fix_darwin_param
- else:
- f = lambda x: fix_gnu_param(arch, x)
+ f = fix_darwin_param
+ else:
+ f = lambda x: fix_gnu_param(arch, x)
def do_fix(p):
if musl and p in musl_libs:
diff --git a/build/scripts/run_msvc_wine.py b/build/scripts/run_msvc_wine.py
index 0d41fde8b2..439d1f8831 100644
--- a/build/scripts/run_msvc_wine.py
+++ b/build/scripts/run_msvc_wine.py
@@ -16,14 +16,14 @@ procs = []
build_kekeke = 45
-def stringize(s):
- return s.encode('utf-8') if isinstance(s, unicode) else s
-
-
+def stringize(s):
+ return s.encode('utf-8') if isinstance(s, unicode) else s
+
+
def run_subprocess(*args, **kwargs):
- if 'env' in kwargs:
- kwargs['env'] = {stringize(k): stringize(v) for k, v in kwargs['env'].iteritems()}
-
+ if 'env' in kwargs:
+ kwargs['env'] = {stringize(k): stringize(v) for k, v in kwargs['env'].iteritems()}
+
p = subprocess.Popen(*args, **kwargs)
procs.append(p)
@@ -310,7 +310,7 @@ def colorize_line(l):
parts.extend(colorize_strings(l))
return ''.join(parts)
- except Exception:
+ except Exception:
return lll
@@ -361,11 +361,11 @@ def make_full_path_arg(arg, bld_root, short_root):
def fix_path(p):
topdirs = ['/%s/' % d for d in os.listdir('/')]
- def abs_path_start(path, pos):
- if pos < 0:
- return False
- return pos == 0 or path[pos - 1] == ':'
-
+ def abs_path_start(path, pos):
+ if pos < 0:
+ return False
+ return pos == 0 or path[pos - 1] == ':'
+
pp = None
for pr in topdirs:
pp2 = p.find(pr)
@@ -443,7 +443,7 @@ def run_main():
env['WINEDLLOVERRIDES'] = 'msvcr{}=n'.format(version)
env['WINEDEBUG'] = 'fixme-all'
- env['INCLUDE'] = ';'.join(fix_path(p) for p in incl_paths)
+ env['INCLUDE'] = ';'.join(fix_path(p) for p in incl_paths)
env['VSINSTALLDIR'] = fix_path(tc_dir)
env['VCINSTALLDIR'] = fix_path(tc_dir + '/VC')
env['WindowsSdkDir'] = fix_path(tc_dir)
@@ -475,20 +475,20 @@ def run_main():
out, _ = p.communicate()
return p.wait(), out
- def print_err_log(log):
- if not log:
- return
- if mode == 'cxx':
- log = colorize(log)
- print >>sys.stderr, log
-
+ def print_err_log(log):
+ if not log:
+ return
+ if mode == 'cxx':
+ log = colorize(log)
+ print >>sys.stderr, log
+
tout = 200
while True:
rc, out = run_process(0, tout)
if rc in (-signal.SIGALRM, signal.SIGALRM):
- print_err_log(out)
+ print_err_log(out)
print >>sys.stderr, '##append_tag##time out'
elif out and ' stack overflow ' in out:
print >>sys.stderr, '##append_tag##stack overflow'
@@ -503,7 +503,7 @@ def run_main():
print >>sys.stderr, e
else:
- print_err_log(out)
+ print_err_log(out)
# non-zero return code - bad, return it immediately
if rc:
diff --git a/build/scripts/stdout2stderr.py b/build/scripts/stdout2stderr.py
index 5220b36002..d7861fdda3 100644
--- a/build/scripts/stdout2stderr.py
+++ b/build/scripts/stdout2stderr.py
@@ -1,6 +1,6 @@
-import subprocess
-import sys
-
-if __name__ == '__main__':
- assert len(sys.argv) > 1
- sys.exit(subprocess.Popen(sys.argv[1:], stdout=sys.stderr).wait())
+import subprocess
+import sys
+
+if __name__ == '__main__':
+ assert len(sys.argv) > 1
+ sys.exit(subprocess.Popen(sys.argv[1:], stdout=sys.stderr).wait())
diff --git a/build/ya.conf.json b/build/ya.conf.json
index a54f90ca40..5f7cc875d6 100644
--- a/build/ya.conf.json
+++ b/build/ya.conf.json
@@ -1137,14 +1137,14 @@
}
]
},
- "yo": {
- "tools": {
+ "yo": {
+ "tools": {
"yo": {
"bottle": "yo",
"executable": "yo"
}
- },
- "platforms": [
+ },
+ "platforms": [
{
"host": {
"os": "LINUX"
@@ -1157,8 +1157,8 @@
},
"default": true
}
- ]
- },
+ ]
+ },
"mockgen": {
"tools": {
"mockgen": {
@@ -5819,17 +5819,17 @@
]
}
},
- "yo": {
- "formula": {
+ "yo": {
+ "formula": {
"sandbox_id": 1183539336,
- "match": "yo"
- },
- "executable": {
+ "match": "yo"
+ },
+ "executable": {
"yo": [
"yo"
]
- }
- },
+ }
+ },
"mockgen": {
"formula": {
"sandbox_id": [
diff --git a/build/ya.make b/build/ya.make
index f7ea6697c4..407b8f13e0 100644
--- a/build/ya.make
+++ b/build/ya.make
@@ -2,9 +2,9 @@ OWNER(
g:ymake
somov
)
-
-NEED_CHECK()
-
+
+NEED_CHECK()
+
PY2_LIBRARY()
PY_SRCS(
@@ -33,6 +33,6 @@ RECURSE(
prebuilt
scripts
tests
- tests_slow
+ tests_slow
yandex_specific/config
)
diff --git a/build/ymake.core.conf b/build/ymake.core.conf
index 2ac32fa79d..081833998b 100644
--- a/build/ymake.core.conf
+++ b/build/ymake.core.conf
@@ -599,10 +599,10 @@ macro OPTIMIZE_PY_PROTOS() {
### Disable Python proto optimization using embedding corresponding C++ code into binary.
### Python protobuf runtime will use C++ implementation instead of Python one if former is available.
### This is default mode only for some system libraries.
-macro NO_OPTIMIZE_PY_PROTOS() {
- SET(OPTIMIZE_PY_PROTOS_FLAG no)
-}
-
+macro NO_OPTIMIZE_PY_PROTOS() {
+ SET(OPTIMIZE_PY_PROTOS_FLAG no)
+}
+
# tag:proto tag:python-specific
macro _PROTO_PLUGIN_ARGS_BASE(Name, Tool, OutParm...) {
.CMD=--plugin=protoc-gen-${Name}=\${tool:"$Tool"} --${Name}_out=$OutParm$ARCADIA_BUILD_ROOT/\$PROTO_NAMESPACE
@@ -985,19 +985,19 @@ macro _JAVA_EVLOG_CMD(File) {
}
# tag:sanitize
-RUN_NO_SANITIZE=$YMAKE_PYTHON ${input:"build/scripts/run_tool.py"} --
+RUN_NO_SANITIZE=$YMAKE_PYTHON ${input:"build/scripts/run_tool.py"} --
# tag:sanitize
when ($IS_CROSS_SANITIZE) {
RUN_NO_SANITIZE=
}
-YIELD=$YMAKE_PYTHON ${input:"build/scripts/yield_line.py"} -- ${BINDIR}/__args
-XARGS=$YMAKE_PYTHON ${input:"build/scripts/xargs.py"} -- ${BINDIR}/__args
+YIELD=$YMAKE_PYTHON ${input:"build/scripts/yield_line.py"} -- ${BINDIR}/__args
+XARGS=$YMAKE_PYTHON ${input:"build/scripts/xargs.py"} -- ${BINDIR}/__args
-RESPFILE_CMD=$YMAKE_PYTHON ${input:"build/scripts/writer.py"}
+RESPFILE_CMD=$YMAKE_PYTHON ${input:"build/scripts/writer.py"}
-FS_TOOLS=$YMAKE_PYTHON ${input:"build/scripts/fs_tools.py"}
+FS_TOOLS=$YMAKE_PYTHON ${input:"build/scripts/fs_tools.py"}
COPY_CMD=$FS_TOOLS copy
LINK_OR_COPY_CMD=$FS_TOOLS link_or_copy
@@ -1005,11 +1005,11 @@ REMOVE_FILE=$FS_TOOLS remove
MOVE_FILE=$FS_TOOLS rename
# tag:allocator tag:windows-specific
-MSVC_DYNAMICBASE=/DYNAMICBASE
+MSVC_DYNAMICBASE=/DYNAMICBASE
when ($ALLOCATOR == "LF") {
MSVC_DYNAMICBASE=/DYNAMICBASE:NO
}
-
+
# tag:sanitize
SANITIZER_CFLAGS=
@@ -6903,11 +6903,11 @@ macro NEED_CHECK(Flags...) {
### @usage: NO_NEED_CHECK()
###
-### Commits to the project marked with this macro will not be affected by higher-level NEED_CHECK macro.
-macro NO_NEED_CHECK(Flags...) {
- ENABLE(UNUSED_MACRO)
-}
-
+### Commits to the project marked with this macro will not be affected by higher-level NEED_CHECK macro.
+macro NO_NEED_CHECK(Flags...) {
+ ENABLE(UNUSED_MACRO)
+}
+
# tag:deprecated
### @usage: NEED_REVIEW() # deprecated
###
@@ -7261,7 +7261,7 @@ TOUCH_UNIT=$YMAKE_PYTHON ${input:"build/scripts/touch.py"} ${kv;hide:"p UN"} ${k
TOUCH_PACKAGE=$YMAKE_PYTHON ${input:"build/scripts/touch.py"} ${kv;hide:"pc light-red"} $TARGET && $YMAKE_PYTHON ${input:"build/scripts/copy_to_dir.py"} --dest-dir $BINDIR --build-root $ARCADIA_BUILD_ROOT $PACKED_PACKAGE_ARGS $SRCS_GLOBAL $PEERS
_P_PK=${kv;hide:"p PK"}
TOUCH_PACKAGE_MF=$GENERATE_MF && $TOUCH_PACKAGE $_P_PK
-TOUCH_JAVA_UNIT=$YMAKE_PYTHON ${input:"build/scripts/touch.py"} ${kv;hide:"java $CURDIR"} $TARGET
+TOUCH_JAVA_UNIT=$YMAKE_PYTHON ${input:"build/scripts/touch.py"} ${kv;hide:"java $CURDIR"} $TARGET
NO_CHECK_IMPORTS_FOR_VALUE=None
### @usage: NO_CHECK_IMPORTS([patterns])
diff --git a/build/ymake_conf.py b/build/ymake_conf.py
index 1cd05c8a7d..30219eb85e 100755
--- a/build/ymake_conf.py
+++ b/build/ymake_conf.py
@@ -232,8 +232,8 @@ def which(prog):
return p
return None
-
-
+
+
def get_stdout(command):
stdout, code = get_stdout_and_code(command)
return stdout if code == 0 else None
@@ -719,10 +719,10 @@ class YMake(object):
def print_core_conf(self):
emit('YMAKE_YNDEXER_IGNORE_BUILD_ROOT', 'yes')
print('@import "${CONF_ROOT}/ymake.core.conf"')
-
+
def print_settings(self):
emit_with_ignore_comment('ARCADIA_ROOT', self.arcadia.root)
-
+
@staticmethod
def _find_conf(conf_file):
script_dir = os.path.dirname(__file__)
@@ -2297,7 +2297,7 @@ class MSVC(object):
self.build = build
self.tc = tc
-
+
class MSVCToolchain(MSVC, Toolchain):
def __init__(self, tc, build):
@@ -2333,46 +2333,46 @@ class MSVCCompiler(MSVC, Compiler):
def __init__(self, tc, build):
Compiler.__init__(self, tc, 'MSVC')
MSVC.__init__(self, tc, build)
-
+
def print_compiler(self):
super(MSVCCompiler, self).print_compiler()
-
+
target = self.build.target
win32_winnt = self.WIN32_WINNT.Windows7
- warns_enabled = [
+ warns_enabled = [
4018, # 'expression' : signed/unsigned mismatch
4265, # 'class' : class has virtual functions, but destructor is not virtual
4296, # 'operator' : expression is always false
4431, # missing type specifier - int assumed
- ]
+ ]
warns_as_error = [
4013, # 'function' undefined; assuming extern returning int
]
- warns_disabled = [
- 4127, # conditional expression is constant
- 4200, # nonstandard extension used : zero-sized array in struct/union
- 4201, # nonstandard extension used : nameless struct/union
- 4351, # elements of array will be default initialized
- 4355, # 'this' : used in base member initializer list
+ warns_disabled = [
+ 4127, # conditional expression is constant
+ 4200, # nonstandard extension used : zero-sized array in struct/union
+ 4201, # nonstandard extension used : nameless struct/union
+ 4351, # elements of array will be default initialized
+ 4355, # 'this' : used in base member initializer list
4503, # decorated name length exceeded, name was truncated
- 4510, # default constructor could not be generated
- 4511, # copy constructor could not be generated
- 4512, # assignment operator could not be generated
- 4554, # check operator precedence for possible error; use parentheses to clarify precedence
- 4610, # 'object' can never be instantiated - user defined constructor required
- 4706, # assignment within conditional expression
- 4800, # forcing value to bool 'true' or 'false' (performance warning)
- 4996, # The POSIX name for this item is deprecated
- 4714, # function marked as __forceinline not inlined
- 4197, # 'TAtomic' : top-level volatile in cast is ignored
- 4245, # 'initializing' : conversion from 'int' to 'ui32', signed/unsigned mismatch
+ 4510, # default constructor could not be generated
+ 4511, # copy constructor could not be generated
+ 4512, # assignment operator could not be generated
+ 4554, # check operator precedence for possible error; use parentheses to clarify precedence
+ 4610, # 'object' can never be instantiated - user defined constructor required
+ 4706, # assignment within conditional expression
+ 4800, # forcing value to bool 'true' or 'false' (performance warning)
+ 4996, # The POSIX name for this item is deprecated
+ 4714, # function marked as __forceinline not inlined
+ 4197, # 'TAtomic' : top-level volatile in cast is ignored
+ 4245, # 'initializing' : conversion from 'int' to 'ui32', signed/unsigned mismatch
4324, # 'ystd::function<void (uint8_t *)>': structure was padded due to alignment specifier
5033, # 'register' is no longer a supported storage class
- ]
-
- defines = [
+ ]
+
+ defines = [
'/DARCADIA_ROOT=${ARCADIA_ROOT}',
'/DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
'/DFAKEID=$CPP_FAKEID',
@@ -2388,8 +2388,8 @@ class MSVCCompiler(MSVC, Compiler):
'/D_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES',
'/DNOMINMAX',
'/DWIN32_LEAN_AND_MEAN',
- ]
-
+ ]
+
cxx_defines = [
# Use builtin offsetof implementation
# instead of a crutcy macro defined in ucrt/stddef.h.
@@ -2420,12 +2420,12 @@ class MSVCCompiler(MSVC, Compiler):
'/permissive-'
]
flags += self.tc.arch_opt
-
+
c_warnings = ['/we{}'.format(code) for code in warns_as_error]
c_warnings += ['/w1{}'.format(code) for code in warns_enabled]
c_warnings += ['/wd{}'.format(code) for code in warns_disabled]
cxx_warnings = []
-
+
flags_debug = ['/Ob0', '/Od', '/D_DEBUG']
flags_release = ['/Ox', '/Ob2', '/Oi', '/DNDEBUG']
@@ -2435,7 +2435,7 @@ class MSVCCompiler(MSVC, Compiler):
# https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
"/Zc:__cplusplus"
]
-
+
if self.tc.use_clang:
flags += [
# Allow <windows.h> to be included via <Windows.h> in case-sensitive file-systems.
@@ -2511,7 +2511,7 @@ class MSVCCompiler(MSVC, Compiler):
masm_io = '-o ${output;suf=${OBJECT_SUF}:SRC} ${input;msvs_source:SRC}'
else:
masm_io = '/nologo /c /Fo${output;suf=${OBJECT_SUF}:SRC} ${input;msvs_source:SRC}'
-
+
emit('OBJ_CROSS_SUF', '$OBJ_SUF')
emit('OBJECT_SUF', '$OBJ_SUF.obj')
emit('WIN32_WINNT', '{value}'.format(value=win32_winnt))
@@ -2546,9 +2546,9 @@ class MSVCCompiler(MSVC, Compiler):
if not self.tc.use_clang:
flags_msvs_only += ['/FD', '/MP']
debug_info_flags = '/Zi /FS'
- else:
+ else:
debug_info_flags = '/Z7'
-
+
if self.tc.use_clang:
emit('CLANG_CL', 'yes')
if self.tc.ide_msvs:
@@ -2573,11 +2573,11 @@ class MSVCCompiler(MSVC, Compiler):
emit('CFLAGS_PER_TYPE', '$CFLAGS_DEBUG')
if self.build.is_ide:
emit('CFLAGS_PER_TYPE', '@[debug|$CFLAGS_DEBUG]@[release|$CFLAGS_RELEASE]')
-
+
append('CFLAGS', flags, flags_msvs_only, '$CFLAGS_PER_TYPE', '$DEBUG_INFO_FLAGS', '$C_WARNING_OPTS', '$C_DEFINES', '$USER_CFLAGS', '$USER_CFLAGS_GLOBAL')
append('CXXFLAGS', '$CFLAGS', '/std:' + self.tc.cxx_std, cxx_flags, cxx_defines, '$CXX_WARNING_OPTS', '$USER_CXXFLAGS', '$USER_CXXFLAGS_GLOBAL')
append('CONLYFLAGS', flags_c_only, '$USER_CONLYFLAGS', '$USER_CONLYFLAGS_GLOBAL')
-
+
append('BC_CFLAGS', '$CFLAGS')
append('BC_CXXFLAGS', '$BC_CFLAGS', '$CXXFLAGS')
@@ -2603,14 +2603,14 @@ class MSVCCompiler(MSVC, Compiler):
emit('SFDL_FLAG', ['/E', '/C', '/P', '/TP', '/Fi$SFDL_TMP_OUT'])
emit('WERROR_FLAG', '/WX')
emit('WERROR_MODE', self.tc.werror_mode)
-
+
if not self.tc.under_wine:
emit('CL_WRAPPER', '${YMAKE_PYTHON}', '${input:"build/scripts/fix_msvc_output.py"}', 'cl')
emit('ML_WRAPPER', '${YMAKE_PYTHON}', '${input:"build/scripts/fix_msvc_output.py"}', 'ml')
- else:
+ else:
emit('CL_WRAPPER')
emit('ML_WRAPPER')
-
+
emit('_SRC_C_NODEPS_CMD',
'${TOOLCHAIN_ENV} ${CL_WRAPPER} ${C_COMPILER} /c /Fo${OUTFILE} ${SRC} ${EXTRA_C_FLAGS} ${pre=/I :INC} '
'${CFLAGS} ${requirements;hide:CC_REQUIREMENTS} ${hide;kv:"soe"} ${hide;kv:"p CC"} ${hide;kv:"pc yellow"}'
@@ -2651,32 +2651,32 @@ class MSVCLinker(MSVC, Linker):
(target.is_armv7, 'arm'),
))
- libpaths = []
+ libpaths = []
if not self.tc.ide_msvs:
if self.tc.kit_libs:
libpaths.extend([os.path.join(self.tc.kit_libs, name, arch) for name in ('um', 'ucrt')])
libpaths.append(os.path.join(self.tc.vc_root, 'lib', arch))
- ignored_errors = [
- 4221
- ]
+ ignored_errors = [
+ 4221
+ ]
flag_machine = '/MACHINE:{}'.format(arch.upper())
- flags_ignore = ['/IGNORE:{}'.format(code) for code in ignored_errors]
-
- flags_common = ['/NOLOGO', '/ERRORREPORT:PROMPT', '/SUBSYSTEM:CONSOLE', '/TLBID:1', '$MSVC_DYNAMICBASE', '/NXCOMPAT']
- flags_common += flags_ignore
+ flags_ignore = ['/IGNORE:{}'.format(code) for code in ignored_errors]
+
+ flags_common = ['/NOLOGO', '/ERRORREPORT:PROMPT', '/SUBSYSTEM:CONSOLE', '/TLBID:1', '$MSVC_DYNAMICBASE', '/NXCOMPAT']
+ flags_common += flags_ignore
flags_common += [flag_machine]
-
- flags_debug_only = []
- flags_release_only = []
-
+
+ flags_debug_only = []
+ flags_release_only = []
+
if self.tc.ide_msvs:
- flags_common += ['/INCREMENTAL']
- else:
- flags_common += ['/INCREMENTAL:NO']
-
+ flags_common += ['/INCREMENTAL']
+ else:
+ flags_common += ['/INCREMENTAL:NO']
+
if self.tc.use_clang:
flags_debug_only.append('/STACK:4194304')
@@ -2687,14 +2687,14 @@ class MSVCLinker(MSVC, Linker):
else:
# No FASTLINK for ya make, because resulting PDB would require .obj files (build_root's) to persist
flags_common.append('/DEBUG')
-
+
if not self.tc.ide_msvs:
- flags_common += ['/LIBPATH:"{}"'.format(path) for path in libpaths]
-
+ flags_common += ['/LIBPATH:"{}"'.format(path) for path in libpaths]
+
link_flags_debug = flags_common + flags_debug_only
link_flags_release = flags_common + flags_release_only
link_flags_lib = flags_ignore + [flag_machine]
-
+
stdlibs = [
'advapi32.lib',
'comdlg32.lib',
@@ -2702,10 +2702,10 @@ class MSVCLinker(MSVC, Linker):
'dnsapi.lib',
'gdi32.lib',
'iphlpapi.lib',
- 'kernel32.lib',
+ 'kernel32.lib',
'mswsock.lib',
- 'ole32.lib',
- 'oleaut32.lib',
+ 'ole32.lib',
+ 'oleaut32.lib',
'psapi.lib',
'rpcrt4.lib',
'secur32.lib',
@@ -2713,13 +2713,13 @@ class MSVCLinker(MSVC, Linker):
'shlwapi.lib',
'user32.lib',
'userenv.lib',
- 'uuid.lib',
+ 'uuid.lib',
'version.lib',
'winmm.lib',
'winspool.lib',
'ws2_32.lib',
- ]
-
+ ]
+
emit('LINK_LIB_CMD', linker_lib)
emit('LINK_EXE_CMD', linker)
emit('LINK_LIB_FLAGS', link_flags_lib)
@@ -2729,16 +2729,16 @@ class MSVCLinker(MSVC, Linker):
emit('LDFLAGS_GLOBAL', '')
emit('LDFLAGS', '')
emit('OBJADDE', '')
-
+
if self.build.is_release:
emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_RELEASE')
if self.build.is_debug:
emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_DEBUG')
if self.build.is_ide and self.tc.ide_msvs:
emit('LINK_EXE_FLAGS_PER_TYPE', '@[debug|$LINK_EXE_FLAGS_DEBUG]@[release|$LINK_EXE_FLAGS_RELEASE]')
-
+
emit('LINK_EXE_FLAGS', '$LINK_EXE_FLAGS_PER_TYPE')
-
+
emit('LINK_IMPLIB_VALUE')
emit('LINK_IMPLIB', '/IMPLIB:${output;noext;rootrel;pre=$MODULE_PREFIX:REALPRJNAME.lib}')
if is_negative_str(preset('NO_DEBUGINFO', 'no')):
@@ -2749,10 +2749,10 @@ class MSVCLinker(MSVC, Linker):
if not self.tc.under_wine:
emit('LIB_WRAPPER', '${YMAKE_PYTHON}', '${input:"build/scripts/fix_msvc_output.py"}', 'lib')
emit('LINK_WRAPPER', '${YMAKE_PYTHON}', '${input:"build/scripts/fix_msvc_output.py"}', 'link')
- else:
+ else:
emit('LIB_WRAPPER')
emit('LINK_WRAPPER')
-
+
emit('LINK_WRAPPER_DYNLIB', '${YMAKE_PYTHON}', '${input:"build/scripts/link_dyn_lib.py"}', '--arch', 'WINDOWS', '--target', '$TARGET')
emit_big('''
EXPORTS_VALUE=
@@ -2760,7 +2760,7 @@ class MSVCLinker(MSVC, Linker):
LINK_IMPLIB_VALUE=$LINK_IMPLIB
EXPORTS_VALUE=/DEF:${input:EXPORTS_FILE}
}''')
-
+
emit("GENERATE_MF_CMD", '$YMAKE_PYTHON ${input:"build/scripts/generate_mf.py"}',
'--build-root $ARCADIA_BUILD_ROOT --module-name $REALPRJNAME -o ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.mf:REALPRJNAME}',
'-t $MODULE_TYPE --ya-start-command-file -Ya,lics $LICENSE_NAMES -Ya,peers ${rootrel:PEERS} -Ya,credits ${input:CREDITS_TEXTS_FILE} $CREDITS_FLAGS --ya-end-command-file',
diff --git a/contrib/libs/curl/COPYING b/contrib/libs/curl/COPYING
index 2367825f36..9d9e4af8d8 100644
--- a/contrib/libs/curl/COPYING
+++ b/contrib/libs/curl/COPYING
@@ -1,22 +1,22 @@
-COPYRIGHT AND PERMISSION NOTICE
-
+COPYRIGHT AND PERMISSION NOTICE
+
Copyright (c) 1996 - 2020, Daniel Stenberg, <daniel@haxx.se>, and many
contributors, see the THANKS file.
-
-All rights reserved.
-
-Permission to use, copy, modify, and distribute this software for any purpose
-with or without fee is hereby granted, provided that the above copyright
-notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
-NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
-OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of a copyright holder shall not
-be used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization of the copyright holder.
+
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright
+notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
+OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall not
+be used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization of the copyright holder.
diff --git a/contrib/libs/curl/include/curl/curl.h b/contrib/libs/curl/include/curl/curl.h
index a20ca8f1cd..8efbe22885 100644
--- a/contrib/libs/curl/include/curl/curl.h
+++ b/contrib/libs/curl/include/curl/curl.h
@@ -1,145 +1,145 @@
#ifndef CURLINC_CURL_H
#define CURLINC_CURL_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * If you have libcurl problems, all docs and details are found here:
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * If you have libcurl problems, all docs and details are found here:
* https://curl.se/libcurl/
- *
- * curl-library mailing list subscription and unsubscription web interface:
+ *
+ * curl-library mailing list subscription and unsubscription web interface:
* https://cool.haxx.se/mailman/listinfo/curl-library/
- */
-
+ */
+
#ifdef CURL_NO_OLDIES
#define CURL_STRICTER
#endif
-#include "curlver.h" /* libcurl version defines */
+#include "curlver.h" /* libcurl version defines */
#include "system.h" /* determine things run-time */
-
-/*
+
+/*
* Define CURL_WIN32 when build target is Win32 API
- */
-
+ */
+
#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \
!defined(__SYMBIAN32__)
#define CURL_WIN32
-#endif
-
-#include <stdio.h>
-#include <limits.h>
-
-#if defined(__FreeBSD__) && (__FreeBSD__ >= 2)
-/* Needed for __FreeBSD_version symbol definition */
-#include <osreldate.h>
-#endif
-
-/* The include stuff here below is mainly for time_t! */
-#include <sys/types.h>
-#include <time.h>
-
+#endif
+
+#include <stdio.h>
+#include <limits.h>
+
+#if defined(__FreeBSD__) && (__FreeBSD__ >= 2)
+/* Needed for __FreeBSD_version symbol definition */
+#include <osreldate.h>
+#endif
+
+/* The include stuff here below is mainly for time_t! */
+#include <sys/types.h>
+#include <time.h>
+
#if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__)
#if !(defined(_WINSOCK_H) || \
defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H))
-/* The check above prevents the winsock2 inclusion if winsock.h already was
- included, since they can't co-exist without problems */
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#endif
-#endif
-
-/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish
- libc5-based Linux systems. Only include it on systems that are known to
- require it! */
-#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
- defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
+/* The check above prevents the winsock2 inclusion if winsock.h already was
+ included, since they can't co-exist without problems */
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#endif
+
+/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish
+ libc5-based Linux systems. Only include it on systems that are known to
+ require it! */
+#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
+ defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \
defined(__CYGWIN__) || defined(AMIGA) || \
- (defined(__FreeBSD_version) && (__FreeBSD_version < 800000))
-#include <sys/select.h>
-#endif
-
+ (defined(__FreeBSD_version) && (__FreeBSD_version < 800000))
+#include <sys/select.h>
+#endif
+
#if !defined(CURL_WIN32) && !defined(_WIN32_WCE)
-#include <sys/socket.h>
-#endif
-
+#include <sys/socket.h>
+#endif
+
#if !defined(CURL_WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__)
-#include <sys/time.h>
-#endif
-
-#ifdef __BEOS__
-#include <support/SupportDefs.h>
-#endif
-
+#include <sys/time.h>
+#endif
+
+#ifdef __BEOS__
+#include <support/SupportDefs.h>
+#endif
+
/* Compatibility for non-Clang compilers */
#ifndef __has_declspec_attribute
# define __has_declspec_attribute(x) 0
#endif
-#ifdef __cplusplus
-extern "C" {
-#endif
-
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER)
typedef struct Curl_easy CURL;
typedef struct Curl_share CURLSH;
#else
-typedef void CURL;
+typedef void CURL;
typedef void CURLSH;
#endif
-
-/*
- * libcurl external API function linkage decorations.
- */
-
-#ifdef CURL_STATICLIB
-# define CURL_EXTERN
+
+/*
+ * libcurl external API function linkage decorations.
+ */
+
+#ifdef CURL_STATICLIB
+# define CURL_EXTERN
#elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \
(__has_declspec_attribute(dllexport) && \
__has_declspec_attribute(dllimport))
-# if defined(BUILDING_LIBCURL)
-# define CURL_EXTERN __declspec(dllexport)
-# else
-# define CURL_EXTERN __declspec(dllimport)
-# endif
-#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS)
-# define CURL_EXTERN CURL_EXTERN_SYMBOL
-#else
-# define CURL_EXTERN
-#endif
-
-#ifndef curl_socket_typedef
-/* socket typedef */
+# if defined(BUILDING_LIBCURL)
+# define CURL_EXTERN __declspec(dllexport)
+# else
+# define CURL_EXTERN __declspec(dllimport)
+# endif
+#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS)
+# define CURL_EXTERN CURL_EXTERN_SYMBOL
+#else
+# define CURL_EXTERN
+#endif
+
+#ifndef curl_socket_typedef
+/* socket typedef */
#if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H)
-typedef SOCKET curl_socket_t;
-#define CURL_SOCKET_BAD INVALID_SOCKET
-#else
-typedef int curl_socket_t;
-#define CURL_SOCKET_BAD -1
-#endif
-#define curl_socket_typedef
-#endif /* curl_socket_typedef */
-
+typedef SOCKET curl_socket_t;
+#define CURL_SOCKET_BAD INVALID_SOCKET
+#else
+typedef int curl_socket_t;
+#define CURL_SOCKET_BAD -1
+#endif
+#define curl_socket_typedef
+#endif /* curl_socket_typedef */
+
/* enum for the different supported SSL backends */
typedef enum {
CURLSSLBACKEND_NONE = 0,
@@ -166,22 +166,22 @@ typedef enum {
#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL
#define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT
-struct curl_httppost {
- struct curl_httppost *next; /* next entry in the list */
- char *name; /* pointer to allocated name */
- long namelength; /* length of name length */
- char *contents; /* pointer to allocated data contents */
+struct curl_httppost {
+ struct curl_httppost *next; /* next entry in the list */
+ char *name; /* pointer to allocated name */
+ long namelength; /* length of name length */
+ char *contents; /* pointer to allocated data contents */
long contentslength; /* length of contents field, see also
CURL_HTTPPOST_LARGE */
- char *buffer; /* pointer to allocated buffer contents */
- long bufferlength; /* length of buffer field */
- char *contenttype; /* Content-Type */
+ char *buffer; /* pointer to allocated buffer contents */
+ long bufferlength; /* length of buffer field */
+ char *contenttype; /* Content-Type */
struct curl_slist *contentheader; /* list of extra headers for this form */
- struct curl_httppost *more; /* if one field name has more than one
- file, this link should link to following
- files */
- long flags; /* as defined below */
-
+ struct curl_httppost *more; /* if one field name has more than one
+ file, this link should link to following
+ files */
+ long flags; /* as defined below */
+
/* specified content is a file name */
#define CURL_HTTPPOST_FILENAME (1<<0)
/* specified content is a file name */
@@ -200,16 +200,16 @@ struct curl_httppost {
/* use size in 'contentlen', added in 7.46.0 */
#define CURL_HTTPPOST_LARGE (1<<7)
- char *showfilename; /* The file name to show. If not set, the
- actual file name will be used (if this
- is a file part) */
- void *userp; /* custom pointer used for
- HTTPPOST_CALLBACK posts */
+ char *showfilename; /* The file name to show. If not set, the
+ actual file name will be used (if this
+ is a file part) */
+ void *userp; /* custom pointer used for
+ HTTPPOST_CALLBACK posts */
curl_off_t contentlen; /* alternative length of contents
field. Used if CURL_HTTPPOST_LARGE is
set. Added in 7.46.0 */
-};
-
+};
+
/* This is a return code for the progress callback that, when returned, will
signal libcurl to continue executing the default progress function */
@@ -217,158 +217,158 @@ struct curl_httppost {
/* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now
considered deprecated but was the only choice up until 7.31.0 */
-typedef int (*curl_progress_callback)(void *clientp,
- double dltotal,
- double dlnow,
- double ultotal,
- double ulnow);
-
+typedef int (*curl_progress_callback)(void *clientp,
+ double dltotal,
+ double dlnow,
+ double ultotal,
+ double ulnow);
+
/* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced
in 7.32.0, avoids the use of floating point numbers and provides more
detailed information. */
-typedef int (*curl_xferinfo_callback)(void *clientp,
- curl_off_t dltotal,
- curl_off_t dlnow,
- curl_off_t ultotal,
- curl_off_t ulnow);
-
+typedef int (*curl_xferinfo_callback)(void *clientp,
+ curl_off_t dltotal,
+ curl_off_t dlnow,
+ curl_off_t ultotal,
+ curl_off_t ulnow);
+
#ifndef CURL_MAX_READ_SIZE
/* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */
#define CURL_MAX_READ_SIZE 524288
#endif
-#ifndef CURL_MAX_WRITE_SIZE
- /* Tests have proven that 20K is a very bad buffer size for uploads on
- Windows, while 16K for some odd reason performed a lot better.
- We do the ifndef check to allow this value to easier be changed at build
- time for those who feel adventurous. The practical minimum is about
- 400 bytes since libcurl uses a buffer of this size as a scratch area
- (unrelated to network send operations). */
-#define CURL_MAX_WRITE_SIZE 16384
-#endif
-
-#ifndef CURL_MAX_HTTP_HEADER
-/* The only reason to have a max limit for this is to avoid the risk of a bad
- server feeding libcurl with a never-ending header that will cause reallocs
- infinitely */
-#define CURL_MAX_HTTP_HEADER (100*1024)
-#endif
-
-/* This is a magic return code for the write callback that, when returned,
- will signal libcurl to pause receiving on the current transfer. */
-#define CURL_WRITEFUNC_PAUSE 0x10000001
-
-typedef size_t (*curl_write_callback)(char *buffer,
- size_t size,
- size_t nitems,
- void *outstream);
-
+#ifndef CURL_MAX_WRITE_SIZE
+ /* Tests have proven that 20K is a very bad buffer size for uploads on
+ Windows, while 16K for some odd reason performed a lot better.
+ We do the ifndef check to allow this value to easier be changed at build
+ time for those who feel adventurous. The practical minimum is about
+ 400 bytes since libcurl uses a buffer of this size as a scratch area
+ (unrelated to network send operations). */
+#define CURL_MAX_WRITE_SIZE 16384
+#endif
+
+#ifndef CURL_MAX_HTTP_HEADER
+/* The only reason to have a max limit for this is to avoid the risk of a bad
+ server feeding libcurl with a never-ending header that will cause reallocs
+ infinitely */
+#define CURL_MAX_HTTP_HEADER (100*1024)
+#endif
+
+/* This is a magic return code for the write callback that, when returned,
+ will signal libcurl to pause receiving on the current transfer. */
+#define CURL_WRITEFUNC_PAUSE 0x10000001
+
+typedef size_t (*curl_write_callback)(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *outstream);
+
/* This callback will be called when a new resolver request is made */
typedef int (*curl_resolver_start_callback)(void *resolver_state,
void *reserved, void *userdata);
-
-/* enumeration of file types */
-typedef enum {
- CURLFILETYPE_FILE = 0,
- CURLFILETYPE_DIRECTORY,
- CURLFILETYPE_SYMLINK,
- CURLFILETYPE_DEVICE_BLOCK,
- CURLFILETYPE_DEVICE_CHAR,
- CURLFILETYPE_NAMEDPIPE,
- CURLFILETYPE_SOCKET,
- CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */
-
- CURLFILETYPE_UNKNOWN /* should never occur */
-} curlfiletype;
-
-#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0)
-#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1)
-#define CURLFINFOFLAG_KNOWN_TIME (1<<2)
-#define CURLFINFOFLAG_KNOWN_PERM (1<<3)
-#define CURLFINFOFLAG_KNOWN_UID (1<<4)
-#define CURLFINFOFLAG_KNOWN_GID (1<<5)
-#define CURLFINFOFLAG_KNOWN_SIZE (1<<6)
-#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7)
-
+
+/* enumeration of file types */
+typedef enum {
+ CURLFILETYPE_FILE = 0,
+ CURLFILETYPE_DIRECTORY,
+ CURLFILETYPE_SYMLINK,
+ CURLFILETYPE_DEVICE_BLOCK,
+ CURLFILETYPE_DEVICE_CHAR,
+ CURLFILETYPE_NAMEDPIPE,
+ CURLFILETYPE_SOCKET,
+ CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */
+
+ CURLFILETYPE_UNKNOWN /* should never occur */
+} curlfiletype;
+
+#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0)
+#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1)
+#define CURLFINFOFLAG_KNOWN_TIME (1<<2)
+#define CURLFINFOFLAG_KNOWN_PERM (1<<3)
+#define CURLFINFOFLAG_KNOWN_UID (1<<4)
+#define CURLFINFOFLAG_KNOWN_GID (1<<5)
+#define CURLFINFOFLAG_KNOWN_SIZE (1<<6)
+#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7)
+
/* Information about a single file, used when doing FTP wildcard matching */
-struct curl_fileinfo {
- char *filename;
- curlfiletype filetype;
+struct curl_fileinfo {
+ char *filename;
+ curlfiletype filetype;
time_t time; /* always zero! */
- unsigned int perm;
- int uid;
- int gid;
- curl_off_t size;
- long int hardlinks;
-
- struct {
- /* If some of these fields is not NULL, it is a pointer to b_data. */
- char *time;
- char *perm;
- char *user;
- char *group;
- char *target; /* pointer to the target filename of a symlink */
- } strings;
-
- unsigned int flags;
-
- /* used internally */
+ unsigned int perm;
+ int uid;
+ int gid;
+ curl_off_t size;
+ long int hardlinks;
+
+ struct {
+ /* If some of these fields is not NULL, it is a pointer to b_data. */
+ char *time;
+ char *perm;
+ char *user;
+ char *group;
+ char *target; /* pointer to the target filename of a symlink */
+ } strings;
+
+ unsigned int flags;
+
+ /* used internally */
char *b_data;
- size_t b_size;
- size_t b_used;
-};
-
-/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */
-#define CURL_CHUNK_BGN_FUNC_OK 0
-#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */
-#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */
-
-/* if splitting of data transfer is enabled, this callback is called before
- download of an individual chunk started. Note that parameter "remains" works
- only for FTP wildcard downloading (for now), otherwise is not used */
-typedef long (*curl_chunk_bgn_callback)(const void *transfer_info,
- void *ptr,
- int remains);
-
-/* return codes for CURLOPT_CHUNK_END_FUNCTION */
-#define CURL_CHUNK_END_FUNC_OK 0
-#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */
-
-/* If splitting of data transfer is enabled this callback is called after
- download of an individual chunk finished.
- Note! After this callback was set then it have to be called FOR ALL chunks.
- Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC.
- This is the reason why we don't need "transfer_info" parameter in this
- callback and we are not interested in "remains" parameter too. */
-typedef long (*curl_chunk_end_callback)(void *ptr);
-
-/* return codes for FNMATCHFUNCTION */
-#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */
-#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */
-#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */
-
-/* callback type for wildcard downloading pattern matching. If the
- string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */
-typedef int (*curl_fnmatch_callback)(void *ptr,
- const char *pattern,
- const char *string);
-
-/* These are the return codes for the seek callbacks */
-#define CURL_SEEKFUNC_OK 0
-#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */
-#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so
- libcurl might try other means instead */
-typedef int (*curl_seek_callback)(void *instream,
- curl_off_t offset,
- int origin); /* 'whence' */
-
-/* This is a return code for the read callback that, when returned, will
- signal libcurl to immediately abort the current transfer. */
-#define CURL_READFUNC_ABORT 0x10000000
-/* This is a return code for the read callback that, when returned, will
- signal libcurl to pause sending data on the current transfer. */
-#define CURL_READFUNC_PAUSE 0x10000001
-
+ size_t b_size;
+ size_t b_used;
+};
+
+/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */
+#define CURL_CHUNK_BGN_FUNC_OK 0
+#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */
+#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */
+
+/* if splitting of data transfer is enabled, this callback is called before
+ download of an individual chunk started. Note that parameter "remains" works
+ only for FTP wildcard downloading (for now), otherwise is not used */
+typedef long (*curl_chunk_bgn_callback)(const void *transfer_info,
+ void *ptr,
+ int remains);
+
+/* return codes for CURLOPT_CHUNK_END_FUNCTION */
+#define CURL_CHUNK_END_FUNC_OK 0
+#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */
+
+/* If splitting of data transfer is enabled this callback is called after
+ download of an individual chunk finished.
+ Note! After this callback was set then it have to be called FOR ALL chunks.
+ Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC.
+ This is the reason why we don't need "transfer_info" parameter in this
+ callback and we are not interested in "remains" parameter too. */
+typedef long (*curl_chunk_end_callback)(void *ptr);
+
+/* return codes for FNMATCHFUNCTION */
+#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */
+#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */
+#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */
+
+/* callback type for wildcard downloading pattern matching. If the
+ string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */
+typedef int (*curl_fnmatch_callback)(void *ptr,
+ const char *pattern,
+ const char *string);
+
+/* These are the return codes for the seek callbacks */
+#define CURL_SEEKFUNC_OK 0
+#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */
+#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so
+ libcurl might try other means instead */
+typedef int (*curl_seek_callback)(void *instream,
+ curl_off_t offset,
+ int origin); /* 'whence' */
+
+/* This is a return code for the read callback that, when returned, will
+ signal libcurl to immediately abort the current transfer. */
+#define CURL_READFUNC_ABORT 0x10000000
+/* This is a return code for the read callback that, when returned, will
+ signal libcurl to pause sending data on the current transfer. */
+#define CURL_READFUNC_PAUSE 0x10000001
+
/* Return code for when the trailing headers' callback has terminated
without any errors*/
#define CURL_TRAILERFUNC_OK 0
@@ -376,229 +376,229 @@ typedef int (*curl_seek_callback)(void *instream,
want to abort the request */
#define CURL_TRAILERFUNC_ABORT 1
-typedef size_t (*curl_read_callback)(char *buffer,
- size_t size,
- size_t nitems,
- void *instream);
-
+typedef size_t (*curl_read_callback)(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *instream);
+
typedef int (*curl_trailer_callback)(struct curl_slist **list,
void *userdata);
typedef enum {
- CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */
- CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */
- CURLSOCKTYPE_LAST /* never use */
-} curlsocktype;
-
-/* The return code from the sockopt_callback can signal information back
- to libcurl: */
-#define CURL_SOCKOPT_OK 0
-#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return
- CURLE_ABORTED_BY_CALLBACK */
-#define CURL_SOCKOPT_ALREADY_CONNECTED 2
-
-typedef int (*curl_sockopt_callback)(void *clientp,
- curl_socket_t curlfd,
- curlsocktype purpose);
-
-struct curl_sockaddr {
- int family;
- int socktype;
- int protocol;
- unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it
- turned really ugly and painful on the systems that
- lack this type */
- struct sockaddr addr;
-};
-
-typedef curl_socket_t
-(*curl_opensocket_callback)(void *clientp,
- curlsocktype purpose,
- struct curl_sockaddr *address);
-
-typedef int
-(*curl_closesocket_callback)(void *clientp, curl_socket_t item);
-
-typedef enum {
- CURLIOE_OK, /* I/O operation successful */
- CURLIOE_UNKNOWNCMD, /* command was unknown to callback */
- CURLIOE_FAILRESTART, /* failed to restart the read */
- CURLIOE_LAST /* never use */
-} curlioerr;
-
+ CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */
+ CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */
+ CURLSOCKTYPE_LAST /* never use */
+} curlsocktype;
+
+/* The return code from the sockopt_callback can signal information back
+ to libcurl: */
+#define CURL_SOCKOPT_OK 0
+#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return
+ CURLE_ABORTED_BY_CALLBACK */
+#define CURL_SOCKOPT_ALREADY_CONNECTED 2
+
+typedef int (*curl_sockopt_callback)(void *clientp,
+ curl_socket_t curlfd,
+ curlsocktype purpose);
+
+struct curl_sockaddr {
+ int family;
+ int socktype;
+ int protocol;
+ unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it
+ turned really ugly and painful on the systems that
+ lack this type */
+ struct sockaddr addr;
+};
+
+typedef curl_socket_t
+(*curl_opensocket_callback)(void *clientp,
+ curlsocktype purpose,
+ struct curl_sockaddr *address);
+
+typedef int
+(*curl_closesocket_callback)(void *clientp, curl_socket_t item);
+
+typedef enum {
+ CURLIOE_OK, /* I/O operation successful */
+ CURLIOE_UNKNOWNCMD, /* command was unknown to callback */
+ CURLIOE_FAILRESTART, /* failed to restart the read */
+ CURLIOE_LAST /* never use */
+} curlioerr;
+
typedef enum {
- CURLIOCMD_NOP, /* no operation */
- CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
- CURLIOCMD_LAST /* never use */
-} curliocmd;
-
-typedef curlioerr (*curl_ioctl_callback)(CURL *handle,
- int cmd,
- void *clientp);
-
+ CURLIOCMD_NOP, /* no operation */
+ CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
+ CURLIOCMD_LAST /* never use */
+} curliocmd;
+
+typedef curlioerr (*curl_ioctl_callback)(CURL *handle,
+ int cmd,
+ void *clientp);
+
#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS
-/*
- * The following typedef's are signatures of malloc, free, realloc, strdup and
- * calloc respectively. Function pointers of these types can be passed to the
- * curl_global_init_mem() function to set user defined memory management
- * callback routines.
- */
-typedef void *(*curl_malloc_callback)(size_t size);
-typedef void (*curl_free_callback)(void *ptr);
-typedef void *(*curl_realloc_callback)(void *ptr, size_t size);
-typedef char *(*curl_strdup_callback)(const char *str);
-typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size);
-
+/*
+ * The following typedef's are signatures of malloc, free, realloc, strdup and
+ * calloc respectively. Function pointers of these types can be passed to the
+ * curl_global_init_mem() function to set user defined memory management
+ * callback routines.
+ */
+typedef void *(*curl_malloc_callback)(size_t size);
+typedef void (*curl_free_callback)(void *ptr);
+typedef void *(*curl_realloc_callback)(void *ptr, size_t size);
+typedef char *(*curl_strdup_callback)(const char *str);
+typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size);
+
#define CURL_DID_MEMORY_FUNC_TYPEDEFS
#endif
-/* the kind of data that is passed to information_callback*/
-typedef enum {
- CURLINFO_TEXT = 0,
- CURLINFO_HEADER_IN, /* 1 */
- CURLINFO_HEADER_OUT, /* 2 */
- CURLINFO_DATA_IN, /* 3 */
- CURLINFO_DATA_OUT, /* 4 */
- CURLINFO_SSL_DATA_IN, /* 5 */
- CURLINFO_SSL_DATA_OUT, /* 6 */
- CURLINFO_END
-} curl_infotype;
-
-typedef int (*curl_debug_callback)
- (CURL *handle, /* the handle/transfer this concerns */
- curl_infotype type, /* what kind of data */
- char *data, /* points to the data */
- size_t size, /* size of the data pointed to */
- void *userptr); /* whatever the user please */
-
-/* All possible error codes from all sorts of curl functions. Future versions
- may return other values, stay prepared.
-
- Always add new return codes last. Never *EVER* remove any. The return
- codes must remain the same!
- */
-
-typedef enum {
- CURLE_OK = 0,
- CURLE_UNSUPPORTED_PROTOCOL, /* 1 */
- CURLE_FAILED_INIT, /* 2 */
- CURLE_URL_MALFORMAT, /* 3 */
- CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for
- 7.17.0, reused in April 2011 for 7.21.5] */
- CURLE_COULDNT_RESOLVE_PROXY, /* 5 */
- CURLE_COULDNT_RESOLVE_HOST, /* 6 */
- CURLE_COULDNT_CONNECT, /* 7 */
+/* the kind of data that is passed to information_callback*/
+typedef enum {
+ CURLINFO_TEXT = 0,
+ CURLINFO_HEADER_IN, /* 1 */
+ CURLINFO_HEADER_OUT, /* 2 */
+ CURLINFO_DATA_IN, /* 3 */
+ CURLINFO_DATA_OUT, /* 4 */
+ CURLINFO_SSL_DATA_IN, /* 5 */
+ CURLINFO_SSL_DATA_OUT, /* 6 */
+ CURLINFO_END
+} curl_infotype;
+
+typedef int (*curl_debug_callback)
+ (CURL *handle, /* the handle/transfer this concerns */
+ curl_infotype type, /* what kind of data */
+ char *data, /* points to the data */
+ size_t size, /* size of the data pointed to */
+ void *userptr); /* whatever the user please */
+
+/* All possible error codes from all sorts of curl functions. Future versions
+ may return other values, stay prepared.
+
+ Always add new return codes last. Never *EVER* remove any. The return
+ codes must remain the same!
+ */
+
+typedef enum {
+ CURLE_OK = 0,
+ CURLE_UNSUPPORTED_PROTOCOL, /* 1 */
+ CURLE_FAILED_INIT, /* 2 */
+ CURLE_URL_MALFORMAT, /* 3 */
+ CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for
+ 7.17.0, reused in April 2011 for 7.21.5] */
+ CURLE_COULDNT_RESOLVE_PROXY, /* 5 */
+ CURLE_COULDNT_RESOLVE_HOST, /* 6 */
+ CURLE_COULDNT_CONNECT, /* 7 */
CURLE_WEIRD_SERVER_REPLY, /* 8 */
- CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server
- due to lack of access - when login fails
- this is not returned. */
- CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for
- 7.15.4, reused in Dec 2011 for 7.24.0]*/
- CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */
- CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server
- [was obsoleted in August 2007 for 7.17.0,
- reused in Dec 2011 for 7.24.0]*/
- CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */
- CURLE_FTP_WEIRD_227_FORMAT, /* 14 */
- CURLE_FTP_CANT_GET_HOST, /* 15 */
+ CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server
+ due to lack of access - when login fails
+ this is not returned. */
+ CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for
+ 7.15.4, reused in Dec 2011 for 7.24.0]*/
+ CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */
+ CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server
+ [was obsoleted in August 2007 for 7.17.0,
+ reused in Dec 2011 for 7.24.0]*/
+ CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */
+ CURLE_FTP_WEIRD_227_FORMAT, /* 14 */
+ CURLE_FTP_CANT_GET_HOST, /* 15 */
CURLE_HTTP2, /* 16 - A problem in the http2 framing layer.
[was obsoleted in August 2007 for 7.17.0,
reused in July 2014 for 7.38.0] */
- CURLE_FTP_COULDNT_SET_TYPE, /* 17 */
- CURLE_PARTIAL_FILE, /* 18 */
- CURLE_FTP_COULDNT_RETR_FILE, /* 19 */
- CURLE_OBSOLETE20, /* 20 - NOT USED */
- CURLE_QUOTE_ERROR, /* 21 - quote command failure */
- CURLE_HTTP_RETURNED_ERROR, /* 22 */
- CURLE_WRITE_ERROR, /* 23 */
- CURLE_OBSOLETE24, /* 24 - NOT USED */
- CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */
- CURLE_READ_ERROR, /* 26 - couldn't open/read from file */
- CURLE_OUT_OF_MEMORY, /* 27 */
- /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error
- instead of a memory allocation error if CURL_DOES_CONVERSIONS
- is defined
- */
- CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */
- CURLE_OBSOLETE29, /* 29 - NOT USED */
- CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */
- CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */
- CURLE_OBSOLETE32, /* 32 - NOT USED */
- CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */
- CURLE_HTTP_POST_ERROR, /* 34 */
- CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */
- CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */
- CURLE_FILE_COULDNT_READ_FILE, /* 37 */
- CURLE_LDAP_CANNOT_BIND, /* 38 */
- CURLE_LDAP_SEARCH_FAILED, /* 39 */
- CURLE_OBSOLETE40, /* 40 - NOT USED */
+ CURLE_FTP_COULDNT_SET_TYPE, /* 17 */
+ CURLE_PARTIAL_FILE, /* 18 */
+ CURLE_FTP_COULDNT_RETR_FILE, /* 19 */
+ CURLE_OBSOLETE20, /* 20 - NOT USED */
+ CURLE_QUOTE_ERROR, /* 21 - quote command failure */
+ CURLE_HTTP_RETURNED_ERROR, /* 22 */
+ CURLE_WRITE_ERROR, /* 23 */
+ CURLE_OBSOLETE24, /* 24 - NOT USED */
+ CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */
+ CURLE_READ_ERROR, /* 26 - couldn't open/read from file */
+ CURLE_OUT_OF_MEMORY, /* 27 */
+ /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error
+ instead of a memory allocation error if CURL_DOES_CONVERSIONS
+ is defined
+ */
+ CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */
+ CURLE_OBSOLETE29, /* 29 - NOT USED */
+ CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */
+ CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */
+ CURLE_OBSOLETE32, /* 32 - NOT USED */
+ CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */
+ CURLE_HTTP_POST_ERROR, /* 34 */
+ CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */
+ CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */
+ CURLE_FILE_COULDNT_READ_FILE, /* 37 */
+ CURLE_LDAP_CANNOT_BIND, /* 38 */
+ CURLE_LDAP_SEARCH_FAILED, /* 39 */
+ CURLE_OBSOLETE40, /* 40 - NOT USED */
CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */
- CURLE_ABORTED_BY_CALLBACK, /* 42 */
- CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */
- CURLE_OBSOLETE44, /* 44 - NOT USED */
- CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */
- CURLE_OBSOLETE46, /* 46 - NOT USED */
+ CURLE_ABORTED_BY_CALLBACK, /* 42 */
+ CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */
+ CURLE_OBSOLETE44, /* 44 - NOT USED */
+ CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */
+ CURLE_OBSOLETE46, /* 46 - NOT USED */
CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */
- CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */
+ CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */
CURLE_TELNET_OPTION_SYNTAX, /* 49 - Malformed telnet option */
- CURLE_OBSOLETE50, /* 50 - NOT USED */
+ CURLE_OBSOLETE50, /* 50 - NOT USED */
CURLE_OBSOLETE51, /* 51 - NOT USED */
- CURLE_GOT_NOTHING, /* 52 - when this is a specific error */
- CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */
- CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as
- default */
- CURLE_SEND_ERROR, /* 55 - failed sending network data */
- CURLE_RECV_ERROR, /* 56 - failure in receiving network data */
- CURLE_OBSOLETE57, /* 57 - NOT IN USE */
- CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */
- CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */
+ CURLE_GOT_NOTHING, /* 52 - when this is a specific error */
+ CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */
+ CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as
+ default */
+ CURLE_SEND_ERROR, /* 55 - failed sending network data */
+ CURLE_RECV_ERROR, /* 56 - failure in receiving network data */
+ CURLE_OBSOLETE57, /* 57 - NOT IN USE */
+ CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */
+ CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */
CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint
wasn't verified fine */
- CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */
- CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */
- CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */
- CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
- CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
- that failed */
- CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
- CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
- accepted and we failed to login */
- CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
- CURLE_TFTP_PERM, /* 69 - permission problem on server */
- CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */
- CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */
- CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */
- CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */
- CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */
- CURLE_CONV_FAILED, /* 75 - conversion failed */
- CURLE_CONV_REQD, /* 76 - caller must register conversion
- callbacks using curl_easy_setopt options
- CURLOPT_CONV_FROM_NETWORK_FUNCTION,
- CURLOPT_CONV_TO_NETWORK_FUNCTION, and
- CURLOPT_CONV_FROM_UTF8_FUNCTION */
- CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing
- or wrong format */
- CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */
- CURLE_SSH, /* 79 - error from the SSH layer, somewhat
- generic so the error message will be of
- interest when this has happened */
-
- CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL
- connection */
- CURLE_AGAIN, /* 81 - socket is not ready for send/recv,
- wait till it's ready and try again (Added
- in 7.18.2) */
- CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or
- wrong format (Added in 7.19.0) */
- CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in
- 7.19.0) */
- CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */
- CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */
- CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */
- CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */
- CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */
- CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the
- session will be queued */
+ CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */
+ CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */
+ CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */
+ CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
+ CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
+ that failed */
+ CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
+ CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
+ accepted and we failed to login */
+ CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
+ CURLE_TFTP_PERM, /* 69 - permission problem on server */
+ CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */
+ CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */
+ CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */
+ CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */
+ CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */
+ CURLE_CONV_FAILED, /* 75 - conversion failed */
+ CURLE_CONV_REQD, /* 76 - caller must register conversion
+ callbacks using curl_easy_setopt options
+ CURLOPT_CONV_FROM_NETWORK_FUNCTION,
+ CURLOPT_CONV_TO_NETWORK_FUNCTION, and
+ CURLOPT_CONV_FROM_UTF8_FUNCTION */
+ CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing
+ or wrong format */
+ CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */
+ CURLE_SSH, /* 79 - error from the SSH layer, somewhat
+ generic so the error message will be of
+ interest when this has happened */
+
+ CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL
+ connection */
+ CURLE_AGAIN, /* 81 - socket is not ready for send/recv,
+ wait till it's ready and try again (Added
+ in 7.18.2) */
+ CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or
+ wrong format (Added in 7.19.0) */
+ CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in
+ 7.19.0) */
+ CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */
+ CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */
+ CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */
+ CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */
+ CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */
+ CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the
+ session will be queued */
CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not
match */
CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */
@@ -611,73 +611,73 @@ typedef enum {
CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */
CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */
CURLE_PROXY, /* 97 - proxy handshake error */
- CURL_LAST /* never use! */
-} CURLcode;
-
-#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
- the obsolete stuff removed! */
-
+ CURL_LAST /* never use! */
+} CURLcode;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
/* Previously obsolete error code re-used in 7.38.0 */
#define CURLE_OBSOLETE16 CURLE_HTTP2
/* Previously obsolete error codes re-used in 7.24.0 */
-#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED
-#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT
-
-/* compatibility with older names */
-#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING
+#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED
+#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT
+
+/* compatibility with older names */
+#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING
#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY
-
+
/* The following were added in 7.62.0 */
#define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION
-/* The following were added in 7.21.5, April 2011 */
-#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION
-
-/* The following were added in 7.17.1 */
-/* These are scheduled to disappear by 2009 */
-#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION
-
-/* The following were added in 7.17.0 */
-/* These are scheduled to disappear by 2009 */
-#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */
-#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46
-#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44
-#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10
-#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16
-#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32
-#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29
-#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12
-#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20
-#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40
-#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24
-#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57
-#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN
-
-#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED
-#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE
-#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR
-#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL
-#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS
-#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR
-#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED
-
-/* The following were added earlier */
-
-#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT
-
-#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR
-#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED
-#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED
-
-#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE
-#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME
-
-/* This was the error code 50 in 7.7.3 and a few earlier versions, this
- is no longer used by libcurl but is instead #defined here only to not
- make programs break */
-#define CURLE_ALREADY_COMPLETE 99999
-
+/* The following were added in 7.21.5, April 2011 */
+#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION
+
+/* The following were added in 7.17.1 */
+/* These are scheduled to disappear by 2009 */
+#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION
+
+/* The following were added in 7.17.0 */
+/* These are scheduled to disappear by 2009 */
+#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */
+#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46
+#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44
+#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10
+#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16
+#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32
+#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29
+#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12
+#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20
+#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40
+#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24
+#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57
+#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN
+
+#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED
+#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE
+#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR
+#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL
+#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS
+#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR
+#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED
+
+/* The following were added earlier */
+
+#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT
+
+#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR
+#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED
+#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED
+
+#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE
+#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME
+
+/* This was the error code 50 in 7.7.3 and a few earlier versions, this
+ is no longer used by libcurl but is instead #defined here only to not
+ make programs break */
+#define CURLE_ALREADY_COMPLETE 99999
+
/* Provide defines for really old option names */
#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */
#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */
@@ -688,8 +688,8 @@ typedef enum {
#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40
#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72
-#endif /*!CURL_NO_OLDIES*/
-
+#endif /*!CURL_NO_OLDIES*/
+
/*
* Proxy error codes. Returned in CURLINFO_PROXY_ERROR if CURLE_PROXY was
* return for the transfers.
@@ -732,143 +732,143 @@ typedef enum {
CURLPX_LAST /* never use */
} CURLproxycode;
-/* This prototype applies to all conversion callbacks */
-typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length);
-
-typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */
+/* This prototype applies to all conversion callbacks */
+typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length);
+
+typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */
void *ssl_ctx, /* actually an OpenSSL
or WolfSSL SSL_CTX,
or an mbedTLS
mbedtls_ssl_config */
- void *userptr);
-
-typedef enum {
- CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use
- CONNECT HTTP/1.1 */
- CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT
- HTTP/1.0 */
+ void *userptr);
+
+typedef enum {
+ CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use
+ CONNECT HTTP/1.1 */
+ CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT
+ HTTP/1.0 */
CURLPROXY_HTTPS = 2, /* added in 7.52.0 */
- CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already
- in 7.10 */
- CURLPROXY_SOCKS5 = 5, /* added in 7.10 */
- CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */
- CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the
- host name rather than the IP address. added
- in 7.18.0 */
-} curl_proxytype; /* this enum was added in 7.10 */
-
-/*
- * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options:
- *
- * CURLAUTH_NONE - No HTTP authentication
- * CURLAUTH_BASIC - HTTP Basic authentication (default)
- * CURLAUTH_DIGEST - HTTP Digest authentication
+ CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already
+ in 7.10 */
+ CURLPROXY_SOCKS5 = 5, /* added in 7.10 */
+ CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */
+ CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the
+ host name rather than the IP address. added
+ in 7.18.0 */
+} curl_proxytype; /* this enum was added in 7.10 */
+
+/*
+ * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options:
+ *
+ * CURLAUTH_NONE - No HTTP authentication
+ * CURLAUTH_BASIC - HTTP Basic authentication (default)
+ * CURLAUTH_DIGEST - HTTP Digest authentication
* CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication
* CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated)
- * CURLAUTH_NTLM - HTTP NTLM authentication
- * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour
- * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper
+ * CURLAUTH_NTLM - HTTP NTLM authentication
+ * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour
+ * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper
* CURLAUTH_BEARER - HTTP Bearer token authentication
- * CURLAUTH_ONLY - Use together with a single other type to force no
- * authentication or just that single type
- * CURLAUTH_ANY - All fine types set
- * CURLAUTH_ANYSAFE - All fine types except Basic
- */
-
-#define CURLAUTH_NONE ((unsigned long)0)
-#define CURLAUTH_BASIC (((unsigned long)1)<<0)
-#define CURLAUTH_DIGEST (((unsigned long)1)<<1)
+ * CURLAUTH_ONLY - Use together with a single other type to force no
+ * authentication or just that single type
+ * CURLAUTH_ANY - All fine types set
+ * CURLAUTH_ANYSAFE - All fine types except Basic
+ */
+
+#define CURLAUTH_NONE ((unsigned long)0)
+#define CURLAUTH_BASIC (((unsigned long)1)<<0)
+#define CURLAUTH_DIGEST (((unsigned long)1)<<1)
#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2)
/* Deprecated since the advent of CURLAUTH_NEGOTIATE */
#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE
/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */
#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE
-#define CURLAUTH_NTLM (((unsigned long)1)<<3)
-#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4)
-#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5)
+#define CURLAUTH_NTLM (((unsigned long)1)<<3)
+#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4)
+#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5)
#define CURLAUTH_BEARER (((unsigned long)1)<<6)
-#define CURLAUTH_ONLY (((unsigned long)1)<<31)
-#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE)
-#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE))
-
-#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */
-#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */
-#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */
-#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */
-#define CURLSSH_AUTH_HOST (1<<2) /* host key files */
-#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */
-#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */
+#define CURLAUTH_ONLY (((unsigned long)1)<<31)
+#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE)
+#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE))
+
+#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */
+#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */
+#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */
+#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */
+#define CURLSSH_AUTH_HOST (1<<2) /* host key files */
+#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */
+#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */
#define CURLSSH_AUTH_GSSAPI (1<<5) /* gssapi (kerberos, ...) */
-#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY
-
-#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */
-#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */
-#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */
-
-#define CURL_ERROR_SIZE 256
-
-enum curl_khtype {
- CURLKHTYPE_UNKNOWN,
- CURLKHTYPE_RSA1,
- CURLKHTYPE_RSA,
+#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY
+
+#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */
+#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */
+#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */
+
+#define CURL_ERROR_SIZE 256
+
+enum curl_khtype {
+ CURLKHTYPE_UNKNOWN,
+ CURLKHTYPE_RSA1,
+ CURLKHTYPE_RSA,
CURLKHTYPE_DSS,
CURLKHTYPE_ECDSA,
CURLKHTYPE_ED25519
-};
-
-struct curl_khkey {
+};
+
+struct curl_khkey {
const char *key; /* points to a null-terminated string encoded with base64
- if len is zero, otherwise to the "raw" data */
- size_t len;
- enum curl_khtype keytype;
-};
-
-/* this is the set of return values expected from the curl_sshkeycallback
- callback */
-enum curl_khstat {
- CURLKHSTAT_FINE_ADD_TO_FILE,
- CURLKHSTAT_FINE,
- CURLKHSTAT_REJECT, /* reject the connection, return an error */
- CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so
- this causes a CURLE_DEFER error but otherwise the
- connection will be left intact etc */
+ if len is zero, otherwise to the "raw" data */
+ size_t len;
+ enum curl_khtype keytype;
+};
+
+/* this is the set of return values expected from the curl_sshkeycallback
+ callback */
+enum curl_khstat {
+ CURLKHSTAT_FINE_ADD_TO_FILE,
+ CURLKHSTAT_FINE,
+ CURLKHSTAT_REJECT, /* reject the connection, return an error */
+ CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so
+ this causes a CURLE_DEFER error but otherwise the
+ connection will be left intact etc */
CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key*/
- CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */
-};
-
-/* this is the set of status codes pass in to the callback */
-enum curl_khmatch {
- CURLKHMATCH_OK, /* match */
- CURLKHMATCH_MISMATCH, /* host found, key mismatch! */
- CURLKHMATCH_MISSING, /* no matching host/key found */
- CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */
-};
-
-typedef int
- (*curl_sshkeycallback) (CURL *easy, /* easy handle */
- const struct curl_khkey *knownkey, /* known */
- const struct curl_khkey *foundkey, /* found */
- enum curl_khmatch, /* libcurl's view on the keys */
- void *clientp); /* custom pointer passed from app */
-
-/* parameter for the CURLOPT_USE_SSL option */
-typedef enum {
- CURLUSESSL_NONE, /* do not attempt to use SSL */
- CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */
- CURLUSESSL_CONTROL, /* SSL for the control connection or fail */
- CURLUSESSL_ALL, /* SSL for all communication or fail */
- CURLUSESSL_LAST /* not an option, never use */
-} curl_usessl;
-
-/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */
-
-/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the
- name of improving interoperability with older servers. Some SSL libraries
- have introduced work-arounds for this flaw but those work-arounds sometimes
- make the SSL communication fail. To regain functionality with those broken
- servers, a user can this way allow the vulnerability back. */
-#define CURLSSLOPT_ALLOW_BEAST (1<<0)
-
+ CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */
+};
+
+/* this is the set of status codes pass in to the callback */
+enum curl_khmatch {
+ CURLKHMATCH_OK, /* match */
+ CURLKHMATCH_MISMATCH, /* host found, key mismatch! */
+ CURLKHMATCH_MISSING, /* no matching host/key found */
+ CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */
+};
+
+typedef int
+ (*curl_sshkeycallback) (CURL *easy, /* easy handle */
+ const struct curl_khkey *knownkey, /* known */
+ const struct curl_khkey *foundkey, /* found */
+ enum curl_khmatch, /* libcurl's view on the keys */
+ void *clientp); /* custom pointer passed from app */
+
+/* parameter for the CURLOPT_USE_SSL option */
+typedef enum {
+ CURLUSESSL_NONE, /* do not attempt to use SSL */
+ CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */
+ CURLUSESSL_CONTROL, /* SSL for the control connection or fail */
+ CURLUSESSL_ALL, /* SSL for all communication or fail */
+ CURLUSESSL_LAST /* not an option, never use */
+} curl_usessl;
+
+/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */
+
+/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the
+ name of improving interoperability with older servers. Some SSL libraries
+ have introduced work-arounds for this flaw but those work-arounds sometimes
+ make the SSL communication fail. To regain functionality with those broken
+ servers, a user can this way allow the vulnerability back. */
+#define CURLSSLOPT_ALLOW_BEAST (1<<0)
+
/* - NO_REVOKE tells libcurl to disable certificate revocation checks for those
SSL backends where such behavior is present. */
#define CURLSSLOPT_NO_REVOKE (1<<1)
@@ -894,56 +894,56 @@ typedef enum {
/* The default connection upkeep interval in milliseconds. */
#define CURL_UPKEEP_INTERVAL_DEFAULT 60000L
-#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
- the obsolete stuff removed! */
-
-/* Backwards compatibility with older names */
-/* These are scheduled to disappear by 2009 */
-
-#define CURLFTPSSL_NONE CURLUSESSL_NONE
-#define CURLFTPSSL_TRY CURLUSESSL_TRY
-#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL
-#define CURLFTPSSL_ALL CURLUSESSL_ALL
-#define CURLFTPSSL_LAST CURLUSESSL_LAST
-#define curl_ftpssl curl_usessl
-#endif /*!CURL_NO_OLDIES*/
-
-/* parameter for the CURLOPT_FTP_SSL_CCC option */
-typedef enum {
- CURLFTPSSL_CCC_NONE, /* do not send CCC */
- CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */
- CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */
- CURLFTPSSL_CCC_LAST /* not an option, never use */
-} curl_ftpccc;
-
-/* parameter for the CURLOPT_FTPSSLAUTH option */
-typedef enum {
- CURLFTPAUTH_DEFAULT, /* let libcurl decide */
- CURLFTPAUTH_SSL, /* use "AUTH SSL" */
- CURLFTPAUTH_TLS, /* use "AUTH TLS" */
- CURLFTPAUTH_LAST /* not an option, never use */
-} curl_ftpauth;
-
-/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */
-typedef enum {
- CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */
- CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD
- again if MKD succeeded, for SFTP this does
- similar magic */
- CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD
- again even if MKD failed! */
- CURLFTP_CREATE_DIR_LAST /* not an option, never use */
-} curl_ftpcreatedir;
-
-/* parameter for the CURLOPT_FTP_FILEMETHOD option */
-typedef enum {
- CURLFTPMETHOD_DEFAULT, /* let libcurl pick */
- CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */
- CURLFTPMETHOD_NOCWD, /* no CWD at all */
- CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */
- CURLFTPMETHOD_LAST /* not an option, never use */
-} curl_ftpmethod;
-
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+/* These are scheduled to disappear by 2009 */
+
+#define CURLFTPSSL_NONE CURLUSESSL_NONE
+#define CURLFTPSSL_TRY CURLUSESSL_TRY
+#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL
+#define CURLFTPSSL_ALL CURLUSESSL_ALL
+#define CURLFTPSSL_LAST CURLUSESSL_LAST
+#define curl_ftpssl curl_usessl
+#endif /*!CURL_NO_OLDIES*/
+
+/* parameter for the CURLOPT_FTP_SSL_CCC option */
+typedef enum {
+ CURLFTPSSL_CCC_NONE, /* do not send CCC */
+ CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */
+ CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */
+ CURLFTPSSL_CCC_LAST /* not an option, never use */
+} curl_ftpccc;
+
+/* parameter for the CURLOPT_FTPSSLAUTH option */
+typedef enum {
+ CURLFTPAUTH_DEFAULT, /* let libcurl decide */
+ CURLFTPAUTH_SSL, /* use "AUTH SSL" */
+ CURLFTPAUTH_TLS, /* use "AUTH TLS" */
+ CURLFTPAUTH_LAST /* not an option, never use */
+} curl_ftpauth;
+
+/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */
+typedef enum {
+ CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */
+ CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD
+ again if MKD succeeded, for SFTP this does
+ similar magic */
+ CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD
+ again even if MKD failed! */
+ CURLFTP_CREATE_DIR_LAST /* not an option, never use */
+} curl_ftpcreatedir;
+
+/* parameter for the CURLOPT_FTP_FILEMETHOD option */
+typedef enum {
+ CURLFTPMETHOD_DEFAULT, /* let libcurl pick */
+ CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */
+ CURLFTPMETHOD_NOCWD, /* no CWD at all */
+ CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */
+ CURLFTPMETHOD_LAST /* not an option, never use */
+} curl_ftpmethod;
+
/* bitmask defines for CURLOPT_HEADEROPT */
#define CURLHEADER_UNIFIED 0
#define CURLHEADER_SEPARATE (1<<0)
@@ -985,52 +985,52 @@ typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy,
#define CURLHSTS_ENABLE (long)(1<<0)
#define CURLHSTS_READONLYFILE (long)(1<<1)
-/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */
-#define CURLPROTO_HTTP (1<<0)
-#define CURLPROTO_HTTPS (1<<1)
-#define CURLPROTO_FTP (1<<2)
-#define CURLPROTO_FTPS (1<<3)
-#define CURLPROTO_SCP (1<<4)
-#define CURLPROTO_SFTP (1<<5)
-#define CURLPROTO_TELNET (1<<6)
-#define CURLPROTO_LDAP (1<<7)
-#define CURLPROTO_LDAPS (1<<8)
-#define CURLPROTO_DICT (1<<9)
-#define CURLPROTO_FILE (1<<10)
-#define CURLPROTO_TFTP (1<<11)
-#define CURLPROTO_IMAP (1<<12)
-#define CURLPROTO_IMAPS (1<<13)
-#define CURLPROTO_POP3 (1<<14)
-#define CURLPROTO_POP3S (1<<15)
-#define CURLPROTO_SMTP (1<<16)
-#define CURLPROTO_SMTPS (1<<17)
-#define CURLPROTO_RTSP (1<<18)
-#define CURLPROTO_RTMP (1<<19)
-#define CURLPROTO_RTMPT (1<<20)
-#define CURLPROTO_RTMPE (1<<21)
-#define CURLPROTO_RTMPTE (1<<22)
-#define CURLPROTO_RTMPS (1<<23)
-#define CURLPROTO_RTMPTS (1<<24)
-#define CURLPROTO_GOPHER (1<<25)
+/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */
+#define CURLPROTO_HTTP (1<<0)
+#define CURLPROTO_HTTPS (1<<1)
+#define CURLPROTO_FTP (1<<2)
+#define CURLPROTO_FTPS (1<<3)
+#define CURLPROTO_SCP (1<<4)
+#define CURLPROTO_SFTP (1<<5)
+#define CURLPROTO_TELNET (1<<6)
+#define CURLPROTO_LDAP (1<<7)
+#define CURLPROTO_LDAPS (1<<8)
+#define CURLPROTO_DICT (1<<9)
+#define CURLPROTO_FILE (1<<10)
+#define CURLPROTO_TFTP (1<<11)
+#define CURLPROTO_IMAP (1<<12)
+#define CURLPROTO_IMAPS (1<<13)
+#define CURLPROTO_POP3 (1<<14)
+#define CURLPROTO_POP3S (1<<15)
+#define CURLPROTO_SMTP (1<<16)
+#define CURLPROTO_SMTPS (1<<17)
+#define CURLPROTO_RTSP (1<<18)
+#define CURLPROTO_RTMP (1<<19)
+#define CURLPROTO_RTMPT (1<<20)
+#define CURLPROTO_RTMPE (1<<21)
+#define CURLPROTO_RTMPTE (1<<22)
+#define CURLPROTO_RTMPS (1<<23)
+#define CURLPROTO_RTMPTS (1<<24)
+#define CURLPROTO_GOPHER (1<<25)
#define CURLPROTO_SMB (1<<26)
#define CURLPROTO_SMBS (1<<27)
#define CURLPROTO_MQTT (1<<28)
-#define CURLPROTO_ALL (~0) /* enable everything */
-
-/* long may be 32 or 64 bits, but we should never depend on anything else
- but 32 */
-#define CURLOPTTYPE_LONG 0
-#define CURLOPTTYPE_OBJECTPOINT 10000
-#define CURLOPTTYPE_FUNCTIONPOINT 20000
-#define CURLOPTTYPE_OFF_T 30000
+#define CURLPROTO_ALL (~0) /* enable everything */
+
+/* long may be 32 or 64 bits, but we should never depend on anything else
+ but 32 */
+#define CURLOPTTYPE_LONG 0
+#define CURLOPTTYPE_OBJECTPOINT 10000
+#define CURLOPTTYPE_FUNCTIONPOINT 20000
+#define CURLOPTTYPE_OFF_T 30000
#define CURLOPTTYPE_BLOB 40000
-
+
/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the
string options from the header file */
-
+
#define CURLOPT(na,t,nu) na = t + nu
-
+
/* CURLOPT aliases that make no run-time difference */
/* 'char *' argument to a string with a trailing zero */
@@ -1045,162 +1045,162 @@ typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy,
/* 'long' argument with a set of values/bitmask */
#define CURLOPTTYPE_VALUES CURLOPTTYPE_LONG
-/*
+/*
* All CURLOPT_* values.
- */
-
-typedef enum {
- /* This is the FILE * or void * the regular output should be written to. */
+ */
+
+typedef enum {
+ /* This is the FILE * or void * the regular output should be written to. */
CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_CBPOINT, 1),
-
- /* The full URL to get/put */
+
+ /* The full URL to get/put */
CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2),
-
- /* Port number to connect to, if other than default. */
+
+ /* Port number to connect to, if other than default. */
CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3),
-
- /* Name of proxy to use. */
+
+ /* Name of proxy to use. */
CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4),
-
+
/* "user:password;options" to use when fetching. */
CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5),
-
+
/* "user:password" to use with proxy. */
CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6),
-
- /* Range to get, specified as an ASCII string. */
+
+ /* Range to get, specified as an ASCII string. */
CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7),
-
- /* not used */
-
- /* Specified file stream to upload from (use as input): */
+
+ /* not used */
+
+ /* Specified file stream to upload from (use as input): */
CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_CBPOINT, 9),
-
- /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE
+
+ /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE
* bytes big. */
CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10),
-
- /* Function that will be called to store the output (instead of fwrite). The
- * parameters will use fwrite() syntax, make sure to follow them. */
+
+ /* Function that will be called to store the output (instead of fwrite). The
+ * parameters will use fwrite() syntax, make sure to follow them. */
CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11),
-
- /* Function that will be called to read the input (instead of fread). The
- * parameters will use fread() syntax, make sure to follow them. */
+
+ /* Function that will be called to read the input (instead of fread). The
+ * parameters will use fread() syntax, make sure to follow them. */
CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12),
-
- /* Time-out the read operation after this amount of seconds */
+
+ /* Time-out the read operation after this amount of seconds */
CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13),
-
- /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about
- * how large the file being sent really is. That allows better error
- * checking and better verifies that the upload was successful. -1 means
- * unknown size.
- *
- * For large file support, there is also a _LARGE version of the key
- * which takes an off_t type, allowing platforms with larger off_t
- * sizes to handle larger files. See below for INFILESIZE_LARGE.
- */
+
+ /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about
+ * how large the file being sent really is. That allows better error
+ * checking and better verifies that the upload was successful. -1 means
+ * unknown size.
+ *
+ * For large file support, there is also a _LARGE version of the key
+ * which takes an off_t type, allowing platforms with larger off_t
+ * sizes to handle larger files. See below for INFILESIZE_LARGE.
+ */
CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14),
-
- /* POST static input fields. */
+
+ /* POST static input fields. */
CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15),
-
- /* Set the referrer page (needed by some CGIs) */
+
+ /* Set the referrer page (needed by some CGIs) */
CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16),
-
- /* Set the FTP PORT string (interface name, named or numerical IP address)
- Use i.e '-' to use default address. */
+
+ /* Set the FTP PORT string (interface name, named or numerical IP address)
+ Use i.e '-' to use default address. */
CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17),
-
- /* Set the User-Agent string (examined by some CGIs) */
+
+ /* Set the User-Agent string (examined by some CGIs) */
CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18),
-
- /* If the download receives less than "low speed limit" bytes/second
- * during "low speed time" seconds, the operations is aborted.
- * You could i.e if you have a pretty high speed connection, abort if
- * it is less than 2000 bytes/sec during 20 seconds.
- */
-
- /* Set the "low speed limit" */
+
+ /* If the download receives less than "low speed limit" bytes/second
+ * during "low speed time" seconds, the operations is aborted.
+ * You could i.e if you have a pretty high speed connection, abort if
+ * it is less than 2000 bytes/sec during 20 seconds.
+ */
+
+ /* Set the "low speed limit" */
CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19),
-
- /* Set the "low speed time" */
+
+ /* Set the "low speed time" */
CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20),
-
- /* Set the continuation offset.
- *
- * Note there is also a _LARGE version of this key which uses
- * off_t types, allowing for large file offsets on platforms which
- * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE.
- */
+
+ /* Set the continuation offset.
+ *
+ * Note there is also a _LARGE version of this key which uses
+ * off_t types, allowing for large file offsets on platforms which
+ * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE.
+ */
CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21),
-
- /* Set cookie in request: */
+
+ /* Set cookie in request: */
CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22),
-
+
/* This points to a linked list of headers, struct curl_slist kind. This
list is also used for RTSP (in spite of its name) */
CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23),
-
- /* This points to a linked list of post entries, struct curl_httppost */
+
+ /* This points to a linked list of post entries, struct curl_httppost */
CURLOPT(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24),
-
- /* name of the file keeping your private SSL-certificate */
+
+ /* name of the file keeping your private SSL-certificate */
CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25),
-
- /* password for the SSL or SSH private key */
+
+ /* password for the SSL or SSH private key */
CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26),
-
- /* send TYPE parameter? */
+
+ /* send TYPE parameter? */
CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27),
-
- /* send linked-list of QUOTE commands */
+
+ /* send linked-list of QUOTE commands */
CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28),
-
- /* send FILE * or void * to store headers to, if you use a callback it
- is simply passed to the callback unmodified */
+
+ /* send FILE * or void * to store headers to, if you use a callback it
+ is simply passed to the callback unmodified */
CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_CBPOINT, 29),
-
- /* point to a file to read the initial cookies from, also enables
- "cookie awareness" */
+
+ /* point to a file to read the initial cookies from, also enables
+ "cookie awareness" */
CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31),
-
- /* What version to specifically try to use.
- See CURL_SSLVERSION defines below. */
+
+ /* What version to specifically try to use.
+ See CURL_SSLVERSION defines below. */
CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_VALUES, 32),
-
- /* What kind of HTTP time condition to use, see defines */
+
+ /* What kind of HTTP time condition to use, see defines */
CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_VALUES, 33),
-
- /* Time to use with the above condition. Specified in number of seconds
- since 1 Jan 1970 */
+
+ /* Time to use with the above condition. Specified in number of seconds
+ since 1 Jan 1970 */
CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34),
-
- /* 35 = OBSOLETE */
-
- /* Custom request, for customizing the get command like
- HTTP: DELETE, TRACE and others
- FTP: to use a different list command
- */
+
+ /* 35 = OBSOLETE */
+
+ /* Custom request, for customizing the get command like
+ HTTP: DELETE, TRACE and others
+ FTP: to use a different list command
+ */
CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36),
-
+
/* FILE handle to use instead of stderr */
CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37),
-
- /* 38 is not used */
-
- /* send linked-list of post-transfer QUOTE commands */
+
+ /* 38 is not used */
+
+ /* send linked-list of post-transfer QUOTE commands */
CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39),
-
+
/* OBSOLETE, do not use! */
CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40),
-
+
/* talk a lot */
CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41),
-
+
/* throw the header out too */
CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42),
-
+
/* shut off the progress meter */
CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43),
@@ -1222,612 +1222,612 @@ typedef enum {
/* Append instead of overwrite on upload! */
CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50),
- /* Specify whether to read the user+password from the .netrc or the URL.
- * This must be one of the CURL_NETRC_* enums below. */
+ /* Specify whether to read the user+password from the .netrc or the URL.
+ * This must be one of the CURL_NETRC_* enums below. */
CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_VALUES, 51),
-
+
/* use Location: Luke! */
CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52),
-
+
/* transfer data in text/ASCII format */
CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53),
-
+
/* HTTP PUT */
CURLOPT(CURLOPT_PUT, CURLOPTTYPE_LONG, 54),
- /* 55 = OBSOLETE */
-
- /* DEPRECATED
- * Function that will be called instead of the internal progress display
- * function. This function should be defined as the curl_progress_callback
- * prototype defines. */
+ /* 55 = OBSOLETE */
+
+ /* DEPRECATED
+ * Function that will be called instead of the internal progress display
+ * function. This function should be defined as the curl_progress_callback
+ * prototype defines. */
CURLOPT(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56),
-
- /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION
- callbacks */
+
+ /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION
+ callbacks */
CURLOPT(CURLOPT_XFERINFODATA, CURLOPTTYPE_CBPOINT, 57),
#define CURLOPT_PROGRESSDATA CURLOPT_XFERINFODATA
-
- /* We want the referrer field set automatically when following locations */
+
+ /* We want the referrer field set automatically when following locations */
CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58),
-
- /* Port of the proxy, can be set in the proxy string as well with:
- "[host]:[port]" */
+
+ /* Port of the proxy, can be set in the proxy string as well with:
+ "[host]:[port]" */
CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59),
-
- /* size of the POST input data, if strlen() is not good to use */
+
+ /* size of the POST input data, if strlen() is not good to use */
CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60),
-
- /* tunnel non-http operations through a HTTP proxy */
+
+ /* tunnel non-http operations through a HTTP proxy */
CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61),
-
- /* Set the interface string to use as outgoing network interface */
+
+ /* Set the interface string to use as outgoing network interface */
CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62),
-
- /* Set the krb4/5 security level, this also enables krb4/5 awareness. This
- * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string
- * is set but doesn't match one of these, 'private' will be used. */
+
+ /* Set the krb4/5 security level, this also enables krb4/5 awareness. This
+ * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string
+ * is set but doesn't match one of these, 'private' will be used. */
CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63),
-
- /* Set if we should verify the peer in ssl handshake, set 1 to verify. */
+
+ /* Set if we should verify the peer in ssl handshake, set 1 to verify. */
CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64),
-
- /* The CApath or CAfile used to validate the peer certificate
- this option is used only if SSL_VERIFYPEER is true */
+
+ /* The CApath or CAfile used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65),
-
- /* 66 = OBSOLETE */
- /* 67 = OBSOLETE */
-
- /* Maximum number of http redirects to follow */
+
+ /* 66 = OBSOLETE */
+ /* 67 = OBSOLETE */
+
+ /* Maximum number of http redirects to follow */
CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68),
-
- /* Pass a long set to 1 to get the date of the requested document (if
- possible)! Pass a zero to shut it off. */
+
+ /* Pass a long set to 1 to get the date of the requested document (if
+ possible)! Pass a zero to shut it off. */
CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69),
-
- /* This points to a linked list of telnet options */
+
+ /* This points to a linked list of telnet options */
CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70),
-
- /* Max amount of cached alive connections */
+
+ /* Max amount of cached alive connections */
CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71),
-
+
/* OBSOLETE, do not use! */
CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72),
-
- /* 73 = OBSOLETE */
-
- /* Set to explicitly use a new connection for the upcoming transfer.
- Do not use this unless you're absolutely sure of this, as it makes the
- operation slower and is less friendly for the network. */
+
+ /* 73 = OBSOLETE */
+
+ /* Set to explicitly use a new connection for the upcoming transfer.
+ Do not use this unless you're absolutely sure of this, as it makes the
+ operation slower and is less friendly for the network. */
CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74),
-
- /* Set to explicitly forbid the upcoming transfer's connection to be re-used
- when done. Do not use this unless you're absolutely sure of this, as it
- makes the operation slower and is less friendly for the network. */
+
+ /* Set to explicitly forbid the upcoming transfer's connection to be re-used
+ when done. Do not use this unless you're absolutely sure of this, as it
+ makes the operation slower and is less friendly for the network. */
CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75),
-
- /* Set to a file name that contains random data for libcurl to use to
- seed the random engine when doing SSL connects. */
+
+ /* Set to a file name that contains random data for libcurl to use to
+ seed the random engine when doing SSL connects. */
CURLOPT(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76),
-
- /* Set to the Entropy Gathering Daemon socket pathname */
+
+ /* Set to the Entropy Gathering Daemon socket pathname */
CURLOPT(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77),
-
- /* Time-out connect operations after this amount of seconds, if connects are
- OK within this time, then fine... This only aborts the connect phase. */
+
+ /* Time-out connect operations after this amount of seconds, if connects are
+ OK within this time, then fine... This only aborts the connect phase. */
CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78),
-
- /* Function that will be called to store headers (instead of fwrite). The
- * parameters will use fwrite() syntax, make sure to follow them. */
+
+ /* Function that will be called to store headers (instead of fwrite). The
+ * parameters will use fwrite() syntax, make sure to follow them. */
CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79),
-
- /* Set this to force the HTTP request to get back to GET. Only really usable
- if POST, PUT or a custom request have been used first.
- */
+
+ /* Set this to force the HTTP request to get back to GET. Only really usable
+ if POST, PUT or a custom request have been used first.
+ */
CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80),
-
- /* Set if we should verify the Common name from the peer certificate in ssl
- * handshake, set 1 to check existence, 2 to ensure that it matches the
- * provided hostname. */
+
+ /* Set if we should verify the Common name from the peer certificate in ssl
+ * handshake, set 1 to check existence, 2 to ensure that it matches the
+ * provided hostname. */
CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81),
-
- /* Specify which file name to write all known cookies in after completed
- operation. Set file name to "-" (dash) to make it go to stdout. */
+
+ /* Specify which file name to write all known cookies in after completed
+ operation. Set file name to "-" (dash) to make it go to stdout. */
CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82),
-
- /* Specify which SSL ciphers to use */
+
+ /* Specify which SSL ciphers to use */
CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83),
-
- /* Specify which HTTP version to use! This must be set to one of the
- CURL_HTTP_VERSION* enums set below. */
+
+ /* Specify which HTTP version to use! This must be set to one of the
+ CURL_HTTP_VERSION* enums set below. */
CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_VALUES, 84),
-
- /* Specifically switch on or off the FTP engine's use of the EPSV command. By
- default, that one will always be attempted before the more traditional
- PASV command. */
+
+ /* Specifically switch on or off the FTP engine's use of the EPSV command. By
+ default, that one will always be attempted before the more traditional
+ PASV command. */
CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85),
-
- /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */
+
+ /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */
CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86),
-
- /* name of the file keeping your private SSL-key */
+
+ /* name of the file keeping your private SSL-key */
CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87),
-
- /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */
+
+ /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */
CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88),
-
- /* crypto engine for the SSL-sub system */
+
+ /* crypto engine for the SSL-sub system */
CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89),
-
- /* set the crypto engine for the SSL-sub system as default
- the param has no meaning...
- */
+
+ /* set the crypto engine for the SSL-sub system as default
+ the param has no meaning...
+ */
CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90),
-
- /* Non-zero value means to use the global dns cache */
+
+ /* Non-zero value means to use the global dns cache */
/* DEPRECATED, do not use! */
CURLOPT(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91),
-
- /* DNS cache timeout */
+
+ /* DNS cache timeout */
CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92),
-
- /* send linked-list of pre-transfer QUOTE commands */
+
+ /* send linked-list of pre-transfer QUOTE commands */
CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93),
-
- /* set the debug function */
+
+ /* set the debug function */
CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94),
-
- /* set the data for the debug function */
+
+ /* set the data for the debug function */
CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_CBPOINT, 95),
-
- /* mark this as start of a cookie session */
+
+ /* mark this as start of a cookie session */
CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96),
-
- /* The CApath directory used to validate the peer certificate
- this option is used only if SSL_VERIFYPEER is true */
+
+ /* The CApath directory used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97),
-
- /* Instruct libcurl to use a smaller receive buffer */
+
+ /* Instruct libcurl to use a smaller receive buffer */
CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98),
-
- /* Instruct libcurl to not use any signal/alarm handlers, even when using
- timeouts. This option is useful for multi-threaded applications.
- See libcurl-the-guide for more background information. */
+
+ /* Instruct libcurl to not use any signal/alarm handlers, even when using
+ timeouts. This option is useful for multi-threaded applications.
+ See libcurl-the-guide for more background information. */
CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99),
-
- /* Provide a CURLShare for mutexing non-ts data */
+
+ /* Provide a CURLShare for mutexing non-ts data */
CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100),
-
- /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default),
+
+ /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default),
CURLPROXY_HTTPS, CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and
CURLPROXY_SOCKS5. */
CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_VALUES, 101),
-
- /* Set the Accept-Encoding string. Use this to tell a server you would like
- the response to be compressed. Before 7.21.6, this was known as
- CURLOPT_ENCODING */
+
+ /* Set the Accept-Encoding string. Use this to tell a server you would like
+ the response to be compressed. Before 7.21.6, this was known as
+ CURLOPT_ENCODING */
CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102),
-
- /* Set pointer to private data */
+
+ /* Set pointer to private data */
CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103),
-
- /* Set aliases for HTTP 200 in the HTTP Response header */
+
+ /* Set aliases for HTTP 200 in the HTTP Response header */
CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104),
-
- /* Continue to send authentication (user+password) when following locations,
- even when hostname changed. This can potentially send off the name
- and password to whatever host the server decides. */
+
+ /* Continue to send authentication (user+password) when following locations,
+ even when hostname changed. This can potentially send off the name
+ and password to whatever host the server decides. */
CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105),
-
- /* Specifically switch on or off the FTP engine's use of the EPRT command (
- it also disables the LPRT attempt). By default, those ones will always be
- attempted before the good old traditional PORT command. */
+
+ /* Specifically switch on or off the FTP engine's use of the EPRT command (
+ it also disables the LPRT attempt). By default, those ones will always be
+ attempted before the good old traditional PORT command. */
CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106),
-
- /* Set this to a bitmask value to enable the particular authentications
- methods you like. Use this in combination with CURLOPT_USERPWD.
- Note that setting multiple bits may cause extra network round-trips. */
+
+ /* Set this to a bitmask value to enable the particular authentications
+ methods you like. Use this in combination with CURLOPT_USERPWD.
+ Note that setting multiple bits may cause extra network round-trips. */
CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107),
-
+
/* Set the ssl context callback function, currently only for OpenSSL or
WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument.
The function must match the curl_ssl_ctx_callback prototype. */
CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108),
-
- /* Set the userdata for the ssl context callback function's third
- argument */
+
+ /* Set the userdata for the ssl context callback function's third
+ argument */
CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_CBPOINT, 109),
-
- /* FTP Option that causes missing dirs to be created on the remote server.
- In 7.19.4 we introduced the convenience enums for this option using the
- CURLFTP_CREATE_DIR prefix.
- */
+
+ /* FTP Option that causes missing dirs to be created on the remote server.
+ In 7.19.4 we introduced the convenience enums for this option using the
+ CURLFTP_CREATE_DIR prefix.
+ */
CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110),
-
- /* Set this to a bitmask value to enable the particular authentications
- methods you like. Use this in combination with CURLOPT_PROXYUSERPWD.
- Note that setting multiple bits may cause extra network round-trips. */
+
+ /* Set this to a bitmask value to enable the particular authentications
+ methods you like. Use this in combination with CURLOPT_PROXYUSERPWD.
+ Note that setting multiple bits may cause extra network round-trips. */
CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111),
-
- /* FTP option that changes the timeout, in seconds, associated with
- getting a response. This is different from transfer timeout time and
- essentially places a demand on the FTP server to acknowledge commands
- in a timely manner. */
+
+ /* FTP option that changes the timeout, in seconds, associated with
+ getting a response. This is different from transfer timeout time and
+ essentially places a demand on the FTP server to acknowledge commands
+ in a timely manner. */
CURLOPT(CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112),
-#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT
-
- /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to
- tell libcurl to resolve names to those IP versions only. This only has
- affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */
+#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT
+
+ /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to
+ tell libcurl to resolve names to those IP versions only. This only has
+ affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */
CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_VALUES, 113),
-
- /* Set this option to limit the size of a file that will be downloaded from
- an HTTP or FTP server.
-
- Note there is also _LARGE version which adds large file support for
- platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */
+
+ /* Set this option to limit the size of a file that will be downloaded from
+ an HTTP or FTP server.
+
+ Note there is also _LARGE version which adds large file support for
+ platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */
CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114),
-
- /* See the comment for INFILESIZE above, but in short, specifies
- * the size of the file being uploaded. -1 means unknown.
- */
+
+ /* See the comment for INFILESIZE above, but in short, specifies
+ * the size of the file being uploaded. -1 means unknown.
+ */
CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115),
-
+
/* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version
* of this; look above for RESUME_FROM.
- */
+ */
CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116),
-
- /* Sets the maximum size of data that will be downloaded from
- * an HTTP or FTP server. See MAXFILESIZE above for the LONG version.
- */
+
+ /* Sets the maximum size of data that will be downloaded from
+ * an HTTP or FTP server. See MAXFILESIZE above for the LONG version.
+ */
CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117),
-
- /* Set this option to the file name of your .netrc file you want libcurl
- to parse (using the CURLOPT_NETRC option). If not set, libcurl will do
- a poor attempt to find the user's home directory and check for a .netrc
- file in there. */
+
+ /* Set this option to the file name of your .netrc file you want libcurl
+ to parse (using the CURLOPT_NETRC option). If not set, libcurl will do
+ a poor attempt to find the user's home directory and check for a .netrc
+ file in there. */
CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118),
-
- /* Enable SSL/TLS for FTP, pick one of:
- CURLUSESSL_TRY - try using SSL, proceed anyway otherwise
- CURLUSESSL_CONTROL - SSL for the control connection or fail
- CURLUSESSL_ALL - SSL for all communication or fail
- */
+
+ /* Enable SSL/TLS for FTP, pick one of:
+ CURLUSESSL_TRY - try using SSL, proceed anyway otherwise
+ CURLUSESSL_CONTROL - SSL for the control connection or fail
+ CURLUSESSL_ALL - SSL for all communication or fail
+ */
CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_VALUES, 119),
-
- /* The _LARGE version of the standard POSTFIELDSIZE option */
+
+ /* The _LARGE version of the standard POSTFIELDSIZE option */
CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120),
-
- /* Enable/disable the TCP Nagle algorithm */
+
+ /* Enable/disable the TCP Nagle algorithm */
CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121),
-
- /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
- /* 123 OBSOLETE. Gone in 7.16.0 */
- /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
- /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
- /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
- /* 127 OBSOLETE. Gone in 7.16.0 */
- /* 128 OBSOLETE. Gone in 7.16.0 */
-
- /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option
- can be used to change libcurl's default action which is to first try
- "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK
- response has been received.
-
- Available parameters are:
- CURLFTPAUTH_DEFAULT - let libcurl decide
- CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS
- CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL
- */
+
+ /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 123 OBSOLETE. Gone in 7.16.0 */
+ /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 127 OBSOLETE. Gone in 7.16.0 */
+ /* 128 OBSOLETE. Gone in 7.16.0 */
+
+ /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option
+ can be used to change libcurl's default action which is to first try
+ "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK
+ response has been received.
+
+ Available parameters are:
+ CURLFTPAUTH_DEFAULT - let libcurl decide
+ CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS
+ CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL
+ */
CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_VALUES, 129),
-
+
CURLOPT(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130),
CURLOPT(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131),
-
- /* 132 OBSOLETE. Gone in 7.16.0 */
- /* 133 OBSOLETE. Gone in 7.16.0 */
-
+
+ /* 132 OBSOLETE. Gone in 7.16.0 */
+ /* 133 OBSOLETE. Gone in 7.16.0 */
+
/* null-terminated string for pass on to the FTP server when asked for
- "account" info */
+ "account" info */
CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134),
-
+
/* feed cookie into cookie engine */
CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135),
-
- /* ignore Content-Length */
+
+ /* ignore Content-Length */
CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136),
-
- /* Set to non-zero to skip the IP address received in a 227 PASV FTP server
- response. Typically used for FTP-SSL purposes but is not restricted to
- that. libcurl will then instead use the same IP address it used for the
- control connection. */
+
+ /* Set to non-zero to skip the IP address received in a 227 PASV FTP server
+ response. Typically used for FTP-SSL purposes but is not restricted to
+ that. libcurl will then instead use the same IP address it used for the
+ control connection. */
CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137),
-
- /* Select "file method" to use when doing FTP, see the curl_ftpmethod
- above. */
+
+ /* Select "file method" to use when doing FTP, see the curl_ftpmethod
+ above. */
CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_VALUES, 138),
-
- /* Local port number to bind the socket to */
+
+ /* Local port number to bind the socket to */
CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139),
-
- /* Number of ports to try, including the first one set with LOCALPORT.
- Thus, setting it to 1 will make no additional attempts but the first.
- */
+
+ /* Number of ports to try, including the first one set with LOCALPORT.
+ Thus, setting it to 1 will make no additional attempts but the first.
+ */
CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140),
-
- /* no transfer, set up connection and let application use the socket by
- extracting it with CURLINFO_LASTSOCKET */
+
+ /* no transfer, set up connection and let application use the socket by
+ extracting it with CURLINFO_LASTSOCKET */
CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141),
-
- /* Function that will be called to convert from the
- network encoding (instead of using the iconv calls in libcurl) */
+
+ /* Function that will be called to convert from the
+ network encoding (instead of using the iconv calls in libcurl) */
CURLOPT(CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 142),
-
- /* Function that will be called to convert to the
- network encoding (instead of using the iconv calls in libcurl) */
+
+ /* Function that will be called to convert to the
+ network encoding (instead of using the iconv calls in libcurl) */
CURLOPT(CURLOPT_CONV_TO_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 143),
-
- /* Function that will be called to convert from UTF8
- (instead of using the iconv calls in libcurl)
- Note that this is used only for SSL certificate processing */
+
+ /* Function that will be called to convert from UTF8
+ (instead of using the iconv calls in libcurl)
+ Note that this is used only for SSL certificate processing */
CURLOPT(CURLOPT_CONV_FROM_UTF8_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 144),
-
- /* if the connection proceeds too quickly then need to slow it down */
- /* limit-rate: maximum number of bytes per second to send or receive */
+
+ /* if the connection proceeds too quickly then need to slow it down */
+ /* limit-rate: maximum number of bytes per second to send or receive */
CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145),
CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146),
-
- /* Pointer to command string to send if USER/PASS fails. */
+
+ /* Pointer to command string to send if USER/PASS fails. */
CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147),
-
- /* callback function for setting socket options */
+
+ /* callback function for setting socket options */
CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148),
CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149),
-
- /* set to 0 to disable session ID re-use for this transfer, default is
- enabled (== 1) */
+
+ /* set to 0 to disable session ID re-use for this transfer, default is
+ enabled (== 1) */
CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150),
-
- /* allowed SSH authentication methods */
+
+ /* allowed SSH authentication methods */
CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_VALUES, 151),
-
- /* Used by scp/sftp to do public/private key authentication */
+
+ /* Used by scp/sftp to do public/private key authentication */
CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152),
CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153),
-
- /* Send CCC (Clear Command Channel) after authentication */
+
+ /* Send CCC (Clear Command Channel) after authentication */
CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154),
-
- /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */
+
+ /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */
CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155),
CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156),
-
- /* set to zero to disable the libcurl's decoding and thus pass the raw body
- data to the application even when it is encoded/compressed */
+
+ /* set to zero to disable the libcurl's decoding and thus pass the raw body
+ data to the application even when it is encoded/compressed */
CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157),
CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158),
-
- /* Permission used when creating new files and directories on the remote
- server for protocols that support it, SFTP/SCP/FILE */
+
+ /* Permission used when creating new files and directories on the remote
+ server for protocols that support it, SFTP/SCP/FILE */
CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159),
CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160),
-
- /* Set the behaviour of POST when redirecting. Values must be set to one
- of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */
+
+ /* Set the behaviour of POST when redirecting. Values must be set to one
+ of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */
CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_VALUES, 161),
-
- /* used by scp/sftp to verify the host's public key */
+
+ /* used by scp/sftp to verify the host's public key */
CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162),
-
- /* Callback function for opening socket (instead of socket(2)). Optionally,
- callback is able change the address or refuse to connect returning
- CURL_SOCKET_BAD. The callback should have type
- curl_opensocket_callback */
+
+ /* Callback function for opening socket (instead of socket(2)). Optionally,
+ callback is able change the address or refuse to connect returning
+ CURL_SOCKET_BAD. The callback should have type
+ curl_opensocket_callback */
CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163),
CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164),
-
- /* POST volatile input fields. */
+
+ /* POST volatile input fields. */
CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165),
-
- /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */
+
+ /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */
CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166),
-
- /* Callback function for seeking in the input stream */
+
+ /* Callback function for seeking in the input stream */
CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167),
CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_CBPOINT, 168),
-
- /* CRL file */
+
+ /* CRL file */
CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169),
-
- /* Issuer certificate */
+
+ /* Issuer certificate */
CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170),
-
- /* (IPv6) Address scope */
+
+ /* (IPv6) Address scope */
CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171),
-
- /* Collect certificate chain info and allow it to get retrievable with
+
+ /* Collect certificate chain info and allow it to get retrievable with
CURLINFO_CERTINFO after the transfer is complete. */
CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172),
-
- /* "name" and "pwd" to use when fetching. */
+
+ /* "name" and "pwd" to use when fetching. */
CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173),
CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174),
-
- /* "name" and "pwd" to use with Proxy when fetching. */
+
+ /* "name" and "pwd" to use with Proxy when fetching. */
CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175),
CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176),
-
- /* Comma separated list of hostnames defining no-proxy zones. These should
- match both hostnames directly, and hostnames within a domain. For
- example, local.com will match local.com and www.local.com, but NOT
- notlocal.com or www.notlocal.com. For compatibility with other
- implementations of this, .local.com will be considered to be the same as
- local.com. A single * is the only valid wildcard, and effectively
- disables the use of proxy. */
+
+ /* Comma separated list of hostnames defining no-proxy zones. These should
+ match both hostnames directly, and hostnames within a domain. For
+ example, local.com will match local.com and www.local.com, but NOT
+ notlocal.com or www.notlocal.com. For compatibility with other
+ implementations of this, .local.com will be considered to be the same as
+ local.com. A single * is the only valid wildcard, and effectively
+ disables the use of proxy. */
CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177),
-
- /* block size for TFTP transfers */
+
+ /* block size for TFTP transfers */
CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178),
-
- /* Socks Service */
+
+ /* Socks Service */
/* DEPRECATED, do not use! */
CURLOPT(CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOPTTYPE_STRINGPOINT, 179),
-
- /* Socks Service */
+
+ /* Socks Service */
CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180),
-
- /* set the bitmask for the protocols that are allowed to be used for the
- transfer, which thus helps the app which takes URLs from users or other
- external inputs and want to restrict what protocol(s) to deal
- with. Defaults to CURLPROTO_ALL. */
+
+ /* set the bitmask for the protocols that are allowed to be used for the
+ transfer, which thus helps the app which takes URLs from users or other
+ external inputs and want to restrict what protocol(s) to deal
+ with. Defaults to CURLPROTO_ALL. */
CURLOPT(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181),
-
- /* set the bitmask for the protocols that libcurl is allowed to follow to,
- as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
+
+ /* set the bitmask for the protocols that libcurl is allowed to follow to,
+ as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
to be set in both bitmasks to be allowed to get redirected to. */
CURLOPT(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182),
-
- /* set the SSH knownhost file name to use */
+
+ /* set the SSH knownhost file name to use */
CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183),
-
- /* set the SSH host key callback, must point to a curl_sshkeycallback
- function */
+
+ /* set the SSH host key callback, must point to a curl_sshkeycallback
+ function */
CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184),
-
- /* set the SSH host key callback custom pointer */
+
+ /* set the SSH host key callback custom pointer */
CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_CBPOINT, 185),
-
- /* set the SMTP mail originator */
+
+ /* set the SMTP mail originator */
CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186),
-
+
/* set the list of SMTP mail receiver(s) */
CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187),
-
- /* FTP: send PRET before PASV */
+
+ /* FTP: send PRET before PASV */
CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188),
-
- /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */
+
+ /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */
CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_VALUES, 189),
-
- /* The RTSP session identifier */
+
+ /* The RTSP session identifier */
CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190),
-
- /* The RTSP stream URI */
+
+ /* The RTSP stream URI */
CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191),
-
- /* The Transport: header to use in RTSP requests */
+
+ /* The Transport: header to use in RTSP requests */
CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192),
-
- /* Manually initialize the client RTSP CSeq for this handle */
+
+ /* Manually initialize the client RTSP CSeq for this handle */
CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193),
-
- /* Manually initialize the server RTSP CSeq for this handle */
+
+ /* Manually initialize the server RTSP CSeq for this handle */
CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194),
-
- /* The stream to pass to INTERLEAVEFUNCTION. */
+
+ /* The stream to pass to INTERLEAVEFUNCTION. */
CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_CBPOINT, 195),
-
- /* Let the application define a custom write method for RTP data */
+
+ /* Let the application define a custom write method for RTP data */
CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196),
-
- /* Turn on wildcard matching */
+
+ /* Turn on wildcard matching */
CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197),
-
- /* Directory matching callback called before downloading of an
- individual file (chunk) started */
+
+ /* Directory matching callback called before downloading of an
+ individual file (chunk) started */
CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198),
-
- /* Directory matching callback called after the file (chunk)
- was downloaded, or skipped */
+
+ /* Directory matching callback called after the file (chunk)
+ was downloaded, or skipped */
CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199),
-
- /* Change match (fnmatch-like) callback for wildcard matching */
+
+ /* Change match (fnmatch-like) callback for wildcard matching */
CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200),
-
- /* Let the application define custom chunk data pointer */
+
+ /* Let the application define custom chunk data pointer */
CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_CBPOINT, 201),
-
- /* FNMATCH_FUNCTION user pointer */
+
+ /* FNMATCH_FUNCTION user pointer */
CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_CBPOINT, 202),
-
- /* send linked-list of name:port:address sets */
+
+ /* send linked-list of name:port:address sets */
CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203),
-
- /* Set a username for authenticated TLS */
+
+ /* Set a username for authenticated TLS */
CURLOPT(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204),
-
- /* Set a password for authenticated TLS */
+
+ /* Set a password for authenticated TLS */
CURLOPT(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205),
-
- /* Set authentication type for authenticated TLS */
+
+ /* Set authentication type for authenticated TLS */
CURLOPT(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206),
-
- /* Set to 1 to enable the "TE:" header in HTTP requests to ask for
- compressed transfer-encoded responses. Set to 0 to disable the use of TE:
- in outgoing requests. The current default is 0, but it might change in a
- future libcurl release.
-
- libcurl will ask for the compressed methods it knows of, and if that
- isn't any, it will not ask for transfer-encoding at all even if this
- option is set to 1.
-
- */
+
+ /* Set to 1 to enable the "TE:" header in HTTP requests to ask for
+ compressed transfer-encoded responses. Set to 0 to disable the use of TE:
+ in outgoing requests. The current default is 0, but it might change in a
+ future libcurl release.
+
+ libcurl will ask for the compressed methods it knows of, and if that
+ isn't any, it will not ask for transfer-encoding at all even if this
+ option is set to 1.
+
+ */
CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207),
-
- /* Callback function for closing socket (instead of close(2)). The callback
- should have type curl_closesocket_callback */
+
+ /* Callback function for closing socket (instead of close(2)). The callback
+ should have type curl_closesocket_callback */
CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208),
CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_CBPOINT, 209),
-
- /* allow GSSAPI credential delegation */
+
+ /* allow GSSAPI credential delegation */
CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210),
-
- /* Set the name servers to use for DNS resolution */
+
+ /* Set the name servers to use for DNS resolution */
CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211),
-
- /* Time-out accept operations (currently for FTP only) after this amount
+
+ /* Time-out accept operations (currently for FTP only) after this amount
of milliseconds. */
CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212),
-
- /* Set TCP keepalive */
+
+ /* Set TCP keepalive */
CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213),
-
- /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */
+
+ /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */
CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214),
CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215),
-
- /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */
+
+ /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */
CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_VALUES, 216),
-
- /* Set the SMTP auth originator */
+
+ /* Set the SMTP auth originator */
CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217),
-
- /* Enable/disable SASL initial response */
+
+ /* Enable/disable SASL initial response */
CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218),
-
- /* Function that will be called instead of the internal progress display
- * function. This function should be defined as the curl_xferinfo_callback
- * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */
+
+ /* Function that will be called instead of the internal progress display
+ * function. This function should be defined as the curl_xferinfo_callback
+ * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */
CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219),
-
- /* The XOAUTH2 bearer token */
+
+ /* The XOAUTH2 bearer token */
CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220),
-
- /* Set the interface string to use as outgoing network
- * interface for DNS requests.
- * Only supported by the c-ares DNS backend */
+
+ /* Set the interface string to use as outgoing network
+ * interface for DNS requests.
+ * Only supported by the c-ares DNS backend */
CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221),
-
- /* Set the local IPv4 address to use for outgoing DNS requests.
- * Only supported by the c-ares DNS backend */
+
+ /* Set the local IPv4 address to use for outgoing DNS requests.
+ * Only supported by the c-ares DNS backend */
CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222),
-
+
/* Set the local IPv6 address to use for outgoing DNS requests.
- * Only supported by the c-ares DNS backend */
+ * Only supported by the c-ares DNS backend */
CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223),
-
+
/* Set authentication options directly */
CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224),
@@ -2073,113 +2073,113 @@ typedef enum {
CURLOPT(CURLOPT_HSTSWRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 303),
CURLOPT(CURLOPT_HSTSWRITEDATA, CURLOPTTYPE_CBPOINT, 304),
- CURLOPT_LASTENTRY /* the last unused */
-} CURLoption;
-
-#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
- the obsolete stuff removed! */
-
-/* Backwards compatibility with older names */
-/* These are scheduled to disappear by 2011 */
-
-/* This was added in version 7.19.1 */
-#define CURLOPT_POST301 CURLOPT_POSTREDIR
-
-/* These are scheduled to disappear by 2009 */
-
-/* The following were added in 7.17.0 */
-#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD
-#define CURLOPT_FTPAPPEND CURLOPT_APPEND
-#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY
-#define CURLOPT_FTP_SSL CURLOPT_USE_SSL
-
-/* The following were added earlier */
-
-#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD
-#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL
-
-#else
-/* This is set if CURL_NO_OLDIES is defined at compile-time */
-#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */
-#endif
-
-
- /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host
- name resolves addresses using more than one IP protocol version, this
- option might be handy to force libcurl to use a specific IP version. */
-#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP
- versions that your system allows */
+ CURLOPT_LASTENTRY /* the last unused */
+} CURLoption;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+/* These are scheduled to disappear by 2011 */
+
+/* This was added in version 7.19.1 */
+#define CURLOPT_POST301 CURLOPT_POSTREDIR
+
+/* These are scheduled to disappear by 2009 */
+
+/* The following were added in 7.17.0 */
+#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD
+#define CURLOPT_FTPAPPEND CURLOPT_APPEND
+#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY
+#define CURLOPT_FTP_SSL CURLOPT_USE_SSL
+
+/* The following were added earlier */
+
+#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD
+#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL
+
+#else
+/* This is set if CURL_NO_OLDIES is defined at compile-time */
+#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */
+#endif
+
+
+ /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host
+ name resolves addresses using more than one IP protocol version, this
+ option might be handy to force libcurl to use a specific IP version. */
+#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP
+ versions that your system allows */
#define CURL_IPRESOLVE_V4 1 /* resolve to IPv4 addresses */
#define CURL_IPRESOLVE_V6 2 /* resolve to IPv6 addresses */
-
- /* three convenient "aliases" that follow the name scheme better */
-#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER
-
- /* These enums are for use with the CURLOPT_HTTP_VERSION option. */
-enum {
- CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd
- like the library to choose the best possible
- for us! */
- CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */
- CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */
+
+ /* three convenient "aliases" that follow the name scheme better */
+#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER
+
+ /* These enums are for use with the CURLOPT_HTTP_VERSION option. */
+enum {
+ CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd
+ like the library to choose the best possible
+ for us! */
+ CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */
+ CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */
CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */
CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1
Upgrade */
CURL_HTTP_VERSION_3 = 30, /* Makes use of explicit HTTP/3 without fallback.
Use CURLOPT_ALTSVC to enable HTTP/3 upgrade */
- CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */
-};
-
+ CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */
+};
+
/* Convenience definition simple because the name of the version is HTTP/2 and
not 2.0. The 2_0 version of the enum name was set while the version was
still planned to be 2.0 and we stick to it for compatibility. */
#define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0
-/*
- * Public API enums for RTSP requests
- */
-enum {
- CURL_RTSPREQ_NONE, /* first in list */
- CURL_RTSPREQ_OPTIONS,
- CURL_RTSPREQ_DESCRIBE,
- CURL_RTSPREQ_ANNOUNCE,
- CURL_RTSPREQ_SETUP,
- CURL_RTSPREQ_PLAY,
- CURL_RTSPREQ_PAUSE,
- CURL_RTSPREQ_TEARDOWN,
- CURL_RTSPREQ_GET_PARAMETER,
- CURL_RTSPREQ_SET_PARAMETER,
- CURL_RTSPREQ_RECORD,
- CURL_RTSPREQ_RECEIVE,
- CURL_RTSPREQ_LAST /* last in list */
-};
-
- /* These enums are for use with the CURLOPT_NETRC option. */
-enum CURL_NETRC_OPTION {
- CURL_NETRC_IGNORED, /* The .netrc will never be read.
- * This is the default. */
- CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred
- * to one in the .netrc. */
- CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored.
- * Unless one is set programmatically, the .netrc
- * will be queried. */
- CURL_NETRC_LAST
-};
-
-enum {
- CURL_SSLVERSION_DEFAULT,
+/*
+ * Public API enums for RTSP requests
+ */
+enum {
+ CURL_RTSPREQ_NONE, /* first in list */
+ CURL_RTSPREQ_OPTIONS,
+ CURL_RTSPREQ_DESCRIBE,
+ CURL_RTSPREQ_ANNOUNCE,
+ CURL_RTSPREQ_SETUP,
+ CURL_RTSPREQ_PLAY,
+ CURL_RTSPREQ_PAUSE,
+ CURL_RTSPREQ_TEARDOWN,
+ CURL_RTSPREQ_GET_PARAMETER,
+ CURL_RTSPREQ_SET_PARAMETER,
+ CURL_RTSPREQ_RECORD,
+ CURL_RTSPREQ_RECEIVE,
+ CURL_RTSPREQ_LAST /* last in list */
+};
+
+ /* These enums are for use with the CURLOPT_NETRC option. */
+enum CURL_NETRC_OPTION {
+ CURL_NETRC_IGNORED, /* The .netrc will never be read.
+ * This is the default. */
+ CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred
+ * to one in the .netrc. */
+ CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored.
+ * Unless one is set programmatically, the .netrc
+ * will be queried. */
+ CURL_NETRC_LAST
+};
+
+enum {
+ CURL_SSLVERSION_DEFAULT,
CURL_SSLVERSION_TLSv1, /* TLS 1.x */
- CURL_SSLVERSION_SSLv2,
- CURL_SSLVERSION_SSLv3,
+ CURL_SSLVERSION_SSLv2,
+ CURL_SSLVERSION_SSLv3,
CURL_SSLVERSION_TLSv1_0,
CURL_SSLVERSION_TLSv1_1,
CURL_SSLVERSION_TLSv1_2,
CURL_SSLVERSION_TLSv1_3,
-
- CURL_SSLVERSION_LAST /* never use, keep last */
-};
-
+
+ CURL_SSLVERSION_LAST /* never use, keep last */
+};
+
enum {
CURL_SSLVERSION_MAX_NONE = 0,
CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16),
@@ -2192,42 +2192,42 @@ enum {
CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16)
};
-enum CURL_TLSAUTH {
- CURL_TLSAUTH_NONE,
- CURL_TLSAUTH_SRP,
- CURL_TLSAUTH_LAST /* never use, keep last */
-};
-
-/* symbols to use with CURLOPT_POSTREDIR.
- CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303
- can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302
- | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */
-
-#define CURL_REDIR_GET_ALL 0
-#define CURL_REDIR_POST_301 1
-#define CURL_REDIR_POST_302 2
-#define CURL_REDIR_POST_303 4
-#define CURL_REDIR_POST_ALL \
- (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303)
-
-typedef enum {
- CURL_TIMECOND_NONE,
-
- CURL_TIMECOND_IFMODSINCE,
- CURL_TIMECOND_IFUNMODSINCE,
- CURL_TIMECOND_LASTMOD,
-
- CURL_TIMECOND_LAST
-} curl_TimeCond;
-
+enum CURL_TLSAUTH {
+ CURL_TLSAUTH_NONE,
+ CURL_TLSAUTH_SRP,
+ CURL_TLSAUTH_LAST /* never use, keep last */
+};
+
+/* symbols to use with CURLOPT_POSTREDIR.
+ CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303
+ can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302
+ | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */
+
+#define CURL_REDIR_GET_ALL 0
+#define CURL_REDIR_POST_301 1
+#define CURL_REDIR_POST_302 2
+#define CURL_REDIR_POST_303 4
+#define CURL_REDIR_POST_ALL \
+ (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303)
+
+typedef enum {
+ CURL_TIMECOND_NONE,
+
+ CURL_TIMECOND_IFMODSINCE,
+ CURL_TIMECOND_IFUNMODSINCE,
+ CURL_TIMECOND_LASTMOD,
+
+ CURL_TIMECOND_LAST
+} curl_TimeCond;
+
/* Special size_t value signaling a null-terminated string. */
#define CURL_ZERO_TERMINATED ((size_t) -1)
-
-/* curl_strequal() and curl_strnequal() are subject for removal in a future
+
+/* curl_strequal() and curl_strnequal() are subject for removal in a future
release */
CURL_EXTERN int curl_strequal(const char *s1, const char *s2);
CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n);
-
+
/* Mime/form handling support. */
typedef struct curl_mime curl_mime; /* Mime context. */
typedef struct curl_mimepart curl_mimepart; /* Mime part context. */
@@ -2353,7 +2353,7 @@ CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part,
struct curl_slist *headers,
int take_ownership);
-typedef enum {
+typedef enum {
CURLFORM_NOTHING, /********* the first one is unused ************/
CURLFORM_COPYNAME,
CURLFORM_PTRNAME,
@@ -2365,220 +2365,220 @@ typedef enum {
CURLFORM_ARRAY,
CURLFORM_OBSOLETE,
CURLFORM_FILE,
-
+
CURLFORM_BUFFER,
CURLFORM_BUFFERPTR,
CURLFORM_BUFFERLENGTH,
-
+
CURLFORM_CONTENTTYPE,
CURLFORM_CONTENTHEADER,
CURLFORM_FILENAME,
CURLFORM_END,
CURLFORM_OBSOLETE2,
-
+
CURLFORM_STREAM,
CURLFORM_CONTENTLEN, /* added in 7.46.0, provide a curl_off_t length */
-
- CURLFORM_LASTENTRY /* the last unused */
-} CURLformoption;
-
-/* structure to be used as parameter for CURLFORM_ARRAY */
-struct curl_forms {
- CURLformoption option;
- const char *value;
-};
-
-/* use this for multipart formpost building */
-/* Returns code for curl_formadd()
- *
- * Returns:
- * CURL_FORMADD_OK on success
- * CURL_FORMADD_MEMORY if the FormInfo allocation fails
- * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
- * CURL_FORMADD_NULL if a null pointer was given for a char
- * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
- * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
- * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
- * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated
- * CURL_FORMADD_MEMORY if some allocation for string copying failed.
- * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
- *
- ***************************************************************************/
-typedef enum {
- CURL_FORMADD_OK, /* first, no error */
-
- CURL_FORMADD_MEMORY,
- CURL_FORMADD_OPTION_TWICE,
- CURL_FORMADD_NULL,
- CURL_FORMADD_UNKNOWN_OPTION,
- CURL_FORMADD_INCOMPLETE,
- CURL_FORMADD_ILLEGAL_ARRAY,
- CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */
-
- CURL_FORMADD_LAST /* last */
-} CURLFORMcode;
-
-/*
- * NAME curl_formadd()
- *
- * DESCRIPTION
- *
- * Pretty advanced function for building multi-part formposts. Each invoke
- * adds one part that together construct a full post. Then use
- * CURLOPT_HTTPPOST to send it off to libcurl.
- */
-CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost,
- struct curl_httppost **last_post,
- ...);
-
-/*
- * callback function for curl_formget()
- * The void *arg pointer will be the one passed as second argument to
- * curl_formget().
- * The character buffer passed to it must not be freed.
- * Should return the buffer length passed to it as the argument "len" on
- * success.
- */
-typedef size_t (*curl_formget_callback)(void *arg, const char *buf,
- size_t len);
-
-/*
- * NAME curl_formget()
- *
- * DESCRIPTION
- *
- * Serialize a curl_httppost struct built with curl_formadd().
- * Accepts a void pointer as second argument which will be passed to
- * the curl_formget_callback function.
- * Returns 0 on success.
- */
-CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg,
- curl_formget_callback append);
-/*
- * NAME curl_formfree()
- *
- * DESCRIPTION
- *
- * Free a multipart formpost previously built with curl_formadd().
- */
-CURL_EXTERN void curl_formfree(struct curl_httppost *form);
-
-/*
- * NAME curl_getenv()
- *
- * DESCRIPTION
- *
- * Returns a malloc()'ed string that MUST be curl_free()ed after usage is
- * complete. DEPRECATED - see lib/README.curlx
- */
-CURL_EXTERN char *curl_getenv(const char *variable);
-
-/*
- * NAME curl_version()
- *
- * DESCRIPTION
- *
- * Returns a static ascii string of the libcurl version.
- */
-CURL_EXTERN char *curl_version(void);
-
-/*
- * NAME curl_easy_escape()
- *
- * DESCRIPTION
- *
- * Escapes URL strings (converts all letters consider illegal in URLs to their
- * %XX versions). This function returns a new allocated string or NULL if an
- * error occurred.
- */
-CURL_EXTERN char *curl_easy_escape(CURL *handle,
- const char *string,
- int length);
-
-/* the previous version: */
-CURL_EXTERN char *curl_escape(const char *string,
- int length);
-
-
-/*
- * NAME curl_easy_unescape()
- *
- * DESCRIPTION
- *
- * Unescapes URL encoding in strings (converts all %XX codes to their 8bit
- * versions). This function returns a new allocated string or NULL if an error
- * occurred.
- * Conversion Note: On non-ASCII platforms the ASCII %XX codes are
- * converted into the host encoding.
- */
-CURL_EXTERN char *curl_easy_unescape(CURL *handle,
- const char *string,
- int length,
- int *outlength);
-
-/* the previous version */
-CURL_EXTERN char *curl_unescape(const char *string,
- int length);
-
-/*
- * NAME curl_free()
- *
- * DESCRIPTION
- *
- * Provided for de-allocation in the same translation unit that did the
- * allocation. Added in libcurl 7.10
- */
-CURL_EXTERN void curl_free(void *p);
-
-/*
- * NAME curl_global_init()
- *
- * DESCRIPTION
- *
- * curl_global_init() should be invoked exactly once for each application that
- * uses libcurl and before any call of other libcurl functions.
- *
- * This function is not thread-safe!
- */
-CURL_EXTERN CURLcode curl_global_init(long flags);
-
-/*
- * NAME curl_global_init_mem()
- *
- * DESCRIPTION
- *
- * curl_global_init() or curl_global_init_mem() should be invoked exactly once
- * for each application that uses libcurl. This function can be used to
- * initialize libcurl and set user defined memory management callback
- * functions. Users can implement memory management routines to check for
- * memory leaks, check for mis-use of the curl library etc. User registered
+
+ CURLFORM_LASTENTRY /* the last unused */
+} CURLformoption;
+
+/* structure to be used as parameter for CURLFORM_ARRAY */
+struct curl_forms {
+ CURLformoption option;
+ const char *value;
+};
+
+/* use this for multipart formpost building */
+/* Returns code for curl_formadd()
+ *
+ * Returns:
+ * CURL_FORMADD_OK on success
+ * CURL_FORMADD_MEMORY if the FormInfo allocation fails
+ * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
+ * CURL_FORMADD_NULL if a null pointer was given for a char
+ * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
+ * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
+ * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
+ * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated
+ * CURL_FORMADD_MEMORY if some allocation for string copying failed.
+ * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
+ *
+ ***************************************************************************/
+typedef enum {
+ CURL_FORMADD_OK, /* first, no error */
+
+ CURL_FORMADD_MEMORY,
+ CURL_FORMADD_OPTION_TWICE,
+ CURL_FORMADD_NULL,
+ CURL_FORMADD_UNKNOWN_OPTION,
+ CURL_FORMADD_INCOMPLETE,
+ CURL_FORMADD_ILLEGAL_ARRAY,
+ CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */
+
+ CURL_FORMADD_LAST /* last */
+} CURLFORMcode;
+
+/*
+ * NAME curl_formadd()
+ *
+ * DESCRIPTION
+ *
+ * Pretty advanced function for building multi-part formposts. Each invoke
+ * adds one part that together construct a full post. Then use
+ * CURLOPT_HTTPPOST to send it off to libcurl.
+ */
+CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost,
+ struct curl_httppost **last_post,
+ ...);
+
+/*
+ * callback function for curl_formget()
+ * The void *arg pointer will be the one passed as second argument to
+ * curl_formget().
+ * The character buffer passed to it must not be freed.
+ * Should return the buffer length passed to it as the argument "len" on
+ * success.
+ */
+typedef size_t (*curl_formget_callback)(void *arg, const char *buf,
+ size_t len);
+
+/*
+ * NAME curl_formget()
+ *
+ * DESCRIPTION
+ *
+ * Serialize a curl_httppost struct built with curl_formadd().
+ * Accepts a void pointer as second argument which will be passed to
+ * the curl_formget_callback function.
+ * Returns 0 on success.
+ */
+CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg,
+ curl_formget_callback append);
+/*
+ * NAME curl_formfree()
+ *
+ * DESCRIPTION
+ *
+ * Free a multipart formpost previously built with curl_formadd().
+ */
+CURL_EXTERN void curl_formfree(struct curl_httppost *form);
+
+/*
+ * NAME curl_getenv()
+ *
+ * DESCRIPTION
+ *
+ * Returns a malloc()'ed string that MUST be curl_free()ed after usage is
+ * complete. DEPRECATED - see lib/README.curlx
+ */
+CURL_EXTERN char *curl_getenv(const char *variable);
+
+/*
+ * NAME curl_version()
+ *
+ * DESCRIPTION
+ *
+ * Returns a static ascii string of the libcurl version.
+ */
+CURL_EXTERN char *curl_version(void);
+
+/*
+ * NAME curl_easy_escape()
+ *
+ * DESCRIPTION
+ *
+ * Escapes URL strings (converts all letters consider illegal in URLs to their
+ * %XX versions). This function returns a new allocated string or NULL if an
+ * error occurred.
+ */
+CURL_EXTERN char *curl_easy_escape(CURL *handle,
+ const char *string,
+ int length);
+
+/* the previous version: */
+CURL_EXTERN char *curl_escape(const char *string,
+ int length);
+
+
+/*
+ * NAME curl_easy_unescape()
+ *
+ * DESCRIPTION
+ *
+ * Unescapes URL encoding in strings (converts all %XX codes to their 8bit
+ * versions). This function returns a new allocated string or NULL if an error
+ * occurred.
+ * Conversion Note: On non-ASCII platforms the ASCII %XX codes are
+ * converted into the host encoding.
+ */
+CURL_EXTERN char *curl_easy_unescape(CURL *handle,
+ const char *string,
+ int length,
+ int *outlength);
+
+/* the previous version */
+CURL_EXTERN char *curl_unescape(const char *string,
+ int length);
+
+/*
+ * NAME curl_free()
+ *
+ * DESCRIPTION
+ *
+ * Provided for de-allocation in the same translation unit that did the
+ * allocation. Added in libcurl 7.10
+ */
+CURL_EXTERN void curl_free(void *p);
+
+/*
+ * NAME curl_global_init()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_init() should be invoked exactly once for each application that
+ * uses libcurl and before any call of other libcurl functions.
+ *
+ * This function is not thread-safe!
+ */
+CURL_EXTERN CURLcode curl_global_init(long flags);
+
+/*
+ * NAME curl_global_init_mem()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_init() or curl_global_init_mem() should be invoked exactly once
+ * for each application that uses libcurl. This function can be used to
+ * initialize libcurl and set user defined memory management callback
+ * functions. Users can implement memory management routines to check for
+ * memory leaks, check for mis-use of the curl library etc. User registered
* callback routines will be invoked by this library instead of the system
- * memory management routines like malloc, free etc.
- */
-CURL_EXTERN CURLcode curl_global_init_mem(long flags,
- curl_malloc_callback m,
- curl_free_callback f,
- curl_realloc_callback r,
- curl_strdup_callback s,
- curl_calloc_callback c);
-
-/*
- * NAME curl_global_cleanup()
- *
- * DESCRIPTION
- *
- * curl_global_cleanup() should be invoked exactly once for each application
- * that uses libcurl
- */
-CURL_EXTERN void curl_global_cleanup(void);
-
-/* linked-list structure for the CURLOPT_QUOTE option (and other) */
-struct curl_slist {
- char *data;
- struct curl_slist *next;
-};
-
-/*
+ * memory management routines like malloc, free etc.
+ */
+CURL_EXTERN CURLcode curl_global_init_mem(long flags,
+ curl_malloc_callback m,
+ curl_free_callback f,
+ curl_realloc_callback r,
+ curl_strdup_callback s,
+ curl_calloc_callback c);
+
+/*
+ * NAME curl_global_cleanup()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_cleanup() should be invoked exactly once for each application
+ * that uses libcurl
+ */
+CURL_EXTERN void curl_global_cleanup(void);
+
+/* linked-list structure for the CURLOPT_QUOTE option (and other) */
+struct curl_slist {
+ char *data;
+ struct curl_slist *next;
+};
+
+/*
* NAME curl_global_sslset()
*
* DESCRIPTION
@@ -2621,45 +2621,45 @@ CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
const curl_ssl_backend ***avail);
/*
- * NAME curl_slist_append()
- *
- * DESCRIPTION
- *
- * Appends a string to a linked list. If no list exists, it will be created
- * first. Returns the new list, after appending.
- */
-CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *,
- const char *);
-
-/*
- * NAME curl_slist_free_all()
- *
- * DESCRIPTION
- *
- * free a previously built curl_slist.
- */
-CURL_EXTERN void curl_slist_free_all(struct curl_slist *);
-
-/*
- * NAME curl_getdate()
- *
- * DESCRIPTION
- *
- * Returns the time, in seconds since 1 Jan 1970 of the time string given in
- * the first argument. The time argument in the second parameter is unused
- * and should be set to NULL.
- */
-CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused);
-
+ * NAME curl_slist_append()
+ *
+ * DESCRIPTION
+ *
+ * Appends a string to a linked list. If no list exists, it will be created
+ * first. Returns the new list, after appending.
+ */
+CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *,
+ const char *);
+
+/*
+ * NAME curl_slist_free_all()
+ *
+ * DESCRIPTION
+ *
+ * free a previously built curl_slist.
+ */
+CURL_EXTERN void curl_slist_free_all(struct curl_slist *);
+
+/*
+ * NAME curl_getdate()
+ *
+ * DESCRIPTION
+ *
+ * Returns the time, in seconds since 1 Jan 1970 of the time string given in
+ * the first argument. The time argument in the second parameter is unused
+ * and should be set to NULL.
+ */
+CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused);
+
/* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS
and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */
-struct curl_certinfo {
- int num_of_certs; /* number of certificates with information */
- struct curl_slist **certinfo; /* for each index in this array, there's a
- linked list with textual information in the
- format "name: value" */
-};
-
+struct curl_certinfo {
+ int num_of_certs; /* number of certificates with information */
+ struct curl_slist **certinfo; /* for each index in this array, there's a
+ linked list with textual information in the
+ format "name: value" */
+};
+
/* Information about the SSL library used and the respective internal SSL
handle, which can be used to obtain further information regarding the
connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */
@@ -2668,67 +2668,67 @@ struct curl_tlssessioninfo {
void *internals;
};
-#define CURLINFO_STRING 0x100000
-#define CURLINFO_LONG 0x200000
-#define CURLINFO_DOUBLE 0x300000
-#define CURLINFO_SLIST 0x400000
+#define CURLINFO_STRING 0x100000
+#define CURLINFO_LONG 0x200000
+#define CURLINFO_DOUBLE 0x300000
+#define CURLINFO_SLIST 0x400000
#define CURLINFO_PTR 0x400000 /* same as SLIST */
#define CURLINFO_SOCKET 0x500000
#define CURLINFO_OFF_T 0x600000
-#define CURLINFO_MASK 0x0fffff
-#define CURLINFO_TYPEMASK 0xf00000
-
-typedef enum {
- CURLINFO_NONE, /* first, never use this */
- CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1,
- CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2,
- CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3,
- CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4,
- CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5,
- CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6,
- CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7,
+#define CURLINFO_MASK 0x0fffff
+#define CURLINFO_TYPEMASK 0xf00000
+
+typedef enum {
+ CURLINFO_NONE, /* first, never use this */
+ CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1,
+ CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2,
+ CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3,
+ CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4,
+ CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5,
+ CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6,
+ CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7,
CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7,
- CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8,
+ CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8,
CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8,
- CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9,
+ CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9,
CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9,
- CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10,
+ CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10,
CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10,
- CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11,
- CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12,
- CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13,
- CURLINFO_FILETIME = CURLINFO_LONG + 14,
+ CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11,
+ CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12,
+ CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13,
+ CURLINFO_FILETIME = CURLINFO_LONG + 14,
CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14,
- CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15,
+ CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15,
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15,
- CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16,
+ CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16,
CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16,
- CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17,
- CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18,
- CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19,
- CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20,
- CURLINFO_PRIVATE = CURLINFO_STRING + 21,
- CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22,
- CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23,
- CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24,
- CURLINFO_OS_ERRNO = CURLINFO_LONG + 25,
- CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26,
- CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27,
- CURLINFO_COOKIELIST = CURLINFO_SLIST + 28,
- CURLINFO_LASTSOCKET = CURLINFO_LONG + 29,
- CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30,
- CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31,
- CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32,
- CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33,
+ CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17,
+ CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18,
+ CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19,
+ CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20,
+ CURLINFO_PRIVATE = CURLINFO_STRING + 21,
+ CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22,
+ CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23,
+ CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24,
+ CURLINFO_OS_ERRNO = CURLINFO_LONG + 25,
+ CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26,
+ CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27,
+ CURLINFO_COOKIELIST = CURLINFO_SLIST + 28,
+ CURLINFO_LASTSOCKET = CURLINFO_LONG + 29,
+ CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30,
+ CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31,
+ CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32,
+ CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33,
CURLINFO_CERTINFO = CURLINFO_PTR + 34,
- CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35,
- CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36,
- CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37,
- CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38,
- CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39,
- CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40,
- CURLINFO_LOCAL_IP = CURLINFO_STRING + 41,
- CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42,
+ CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35,
+ CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36,
+ CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37,
+ CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38,
+ CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39,
+ CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40,
+ CURLINFO_LOCAL_IP = CURLINFO_STRING + 41,
+ CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42,
CURLINFO_TLS_SESSION = CURLINFO_PTR + 43,
CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44,
CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45,
@@ -2748,143 +2748,143 @@ typedef enum {
CURLINFO_PROXY_ERROR = CURLINFO_LONG + 59,
CURLINFO_LASTONE = 59
-} CURLINFO;
-
-/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as
- CURLINFO_HTTP_CODE */
-#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE
-
-typedef enum {
- CURLCLOSEPOLICY_NONE, /* first, never use this */
-
- CURLCLOSEPOLICY_OLDEST,
- CURLCLOSEPOLICY_LEAST_RECENTLY_USED,
- CURLCLOSEPOLICY_LEAST_TRAFFIC,
- CURLCLOSEPOLICY_SLOWEST,
- CURLCLOSEPOLICY_CALLBACK,
-
- CURLCLOSEPOLICY_LAST /* last, never use this */
-} curl_closepolicy;
-
+} CURLINFO;
+
+/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as
+ CURLINFO_HTTP_CODE */
+#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE
+
+typedef enum {
+ CURLCLOSEPOLICY_NONE, /* first, never use this */
+
+ CURLCLOSEPOLICY_OLDEST,
+ CURLCLOSEPOLICY_LEAST_RECENTLY_USED,
+ CURLCLOSEPOLICY_LEAST_TRAFFIC,
+ CURLCLOSEPOLICY_SLOWEST,
+ CURLCLOSEPOLICY_CALLBACK,
+
+ CURLCLOSEPOLICY_LAST /* last, never use this */
+} curl_closepolicy;
+
#define CURL_GLOBAL_SSL (1<<0) /* no purpose since since 7.57.0 */
-#define CURL_GLOBAL_WIN32 (1<<1)
-#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
-#define CURL_GLOBAL_NOTHING 0
-#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
-#define CURL_GLOBAL_ACK_EINTR (1<<2)
-
-
-/*****************************************************************************
- * Setup defines, protos etc for the sharing stuff.
- */
-
-/* Different data locks for a single share */
-typedef enum {
- CURL_LOCK_DATA_NONE = 0,
- /* CURL_LOCK_DATA_SHARE is used internally to say that
- * the locking is just made to change the internal state of the share
- * itself.
- */
- CURL_LOCK_DATA_SHARE,
- CURL_LOCK_DATA_COOKIE,
- CURL_LOCK_DATA_DNS,
- CURL_LOCK_DATA_SSL_SESSION,
- CURL_LOCK_DATA_CONNECT,
+#define CURL_GLOBAL_WIN32 (1<<1)
+#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
+#define CURL_GLOBAL_NOTHING 0
+#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
+#define CURL_GLOBAL_ACK_EINTR (1<<2)
+
+
+/*****************************************************************************
+ * Setup defines, protos etc for the sharing stuff.
+ */
+
+/* Different data locks for a single share */
+typedef enum {
+ CURL_LOCK_DATA_NONE = 0,
+ /* CURL_LOCK_DATA_SHARE is used internally to say that
+ * the locking is just made to change the internal state of the share
+ * itself.
+ */
+ CURL_LOCK_DATA_SHARE,
+ CURL_LOCK_DATA_COOKIE,
+ CURL_LOCK_DATA_DNS,
+ CURL_LOCK_DATA_SSL_SESSION,
+ CURL_LOCK_DATA_CONNECT,
CURL_LOCK_DATA_PSL,
- CURL_LOCK_DATA_LAST
-} curl_lock_data;
-
-/* Different lock access types */
-typedef enum {
- CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */
- CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */
- CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */
- CURL_LOCK_ACCESS_LAST /* never use */
-} curl_lock_access;
-
-typedef void (*curl_lock_function)(CURL *handle,
- curl_lock_data data,
- curl_lock_access locktype,
- void *userptr);
-typedef void (*curl_unlock_function)(CURL *handle,
- curl_lock_data data,
- void *userptr);
-
-
-typedef enum {
- CURLSHE_OK, /* all is fine */
- CURLSHE_BAD_OPTION, /* 1 */
- CURLSHE_IN_USE, /* 2 */
- CURLSHE_INVALID, /* 3 */
- CURLSHE_NOMEM, /* 4 out of memory */
- CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */
- CURLSHE_LAST /* never use */
-} CURLSHcode;
-
-typedef enum {
- CURLSHOPT_NONE, /* don't use */
- CURLSHOPT_SHARE, /* specify a data type to share */
- CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */
- CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */
- CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */
- CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock
- callback functions */
- CURLSHOPT_LAST /* never use */
-} CURLSHoption;
-
-CURL_EXTERN CURLSH *curl_share_init(void);
-CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...);
-CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *);
-
-/****************************************************************************
- * Structures for querying information about the curl library at runtime.
- */
-
-typedef enum {
- CURLVERSION_FIRST,
- CURLVERSION_SECOND,
- CURLVERSION_THIRD,
- CURLVERSION_FOURTH,
+ CURL_LOCK_DATA_LAST
+} curl_lock_data;
+
+/* Different lock access types */
+typedef enum {
+ CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */
+ CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */
+ CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */
+ CURL_LOCK_ACCESS_LAST /* never use */
+} curl_lock_access;
+
+typedef void (*curl_lock_function)(CURL *handle,
+ curl_lock_data data,
+ curl_lock_access locktype,
+ void *userptr);
+typedef void (*curl_unlock_function)(CURL *handle,
+ curl_lock_data data,
+ void *userptr);
+
+
+typedef enum {
+ CURLSHE_OK, /* all is fine */
+ CURLSHE_BAD_OPTION, /* 1 */
+ CURLSHE_IN_USE, /* 2 */
+ CURLSHE_INVALID, /* 3 */
+ CURLSHE_NOMEM, /* 4 out of memory */
+ CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */
+ CURLSHE_LAST /* never use */
+} CURLSHcode;
+
+typedef enum {
+ CURLSHOPT_NONE, /* don't use */
+ CURLSHOPT_SHARE, /* specify a data type to share */
+ CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */
+ CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */
+ CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */
+ CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock
+ callback functions */
+ CURLSHOPT_LAST /* never use */
+} CURLSHoption;
+
+CURL_EXTERN CURLSH *curl_share_init(void);
+CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...);
+CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *);
+
+/****************************************************************************
+ * Structures for querying information about the curl library at runtime.
+ */
+
+typedef enum {
+ CURLVERSION_FIRST,
+ CURLVERSION_SECOND,
+ CURLVERSION_THIRD,
+ CURLVERSION_FOURTH,
CURLVERSION_FIFTH,
CURLVERSION_SIXTH,
CURLVERSION_SEVENTH,
CURLVERSION_EIGHTH,
- CURLVERSION_LAST /* never actually use this */
-} CURLversion;
-
-/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by
- basically all programs ever that want to get version information. It is
- meant to be a built-in version number for what kind of struct the caller
- expects. If the struct ever changes, we redefine the NOW to another enum
- from above. */
+ CURLVERSION_LAST /* never actually use this */
+} CURLversion;
+
+/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by
+ basically all programs ever that want to get version information. It is
+ meant to be a built-in version number for what kind of struct the caller
+ expects. If the struct ever changes, we redefine the NOW to another enum
+ from above. */
#define CURLVERSION_NOW CURLVERSION_EIGHTH
-
+
struct curl_version_info_data {
- CURLversion age; /* age of the returned struct */
- const char *version; /* LIBCURL_VERSION */
- unsigned int version_num; /* LIBCURL_VERSION_NUM */
- const char *host; /* OS/host/cpu/machine when configured */
- int features; /* bitmask, see defines below */
- const char *ssl_version; /* human readable string */
- long ssl_version_num; /* not used anymore, always 0 */
- const char *libz_version; /* human readable string */
- /* protocols is terminated by an entry with a NULL protoname */
- const char * const *protocols;
-
- /* The fields below this were added in CURLVERSION_SECOND */
- const char *ares;
- int ares_num;
-
- /* This field was added in CURLVERSION_THIRD */
- const char *libidn;
-
- /* These field were added in CURLVERSION_FOURTH */
-
- /* Same as '_libiconv_version' if built with HAVE_ICONV */
- int iconv_ver_num;
-
- const char *libssh_version; /* human readable string */
-
+ CURLversion age; /* age of the returned struct */
+ const char *version; /* LIBCURL_VERSION */
+ unsigned int version_num; /* LIBCURL_VERSION_NUM */
+ const char *host; /* OS/host/cpu/machine when configured */
+ int features; /* bitmask, see defines below */
+ const char *ssl_version; /* human readable string */
+ long ssl_version_num; /* not used anymore, always 0 */
+ const char *libz_version; /* human readable string */
+ /* protocols is terminated by an entry with a NULL protoname */
+ const char * const *protocols;
+
+ /* The fields below this were added in CURLVERSION_SECOND */
+ const char *ares;
+ int ares_num;
+
+ /* This field was added in CURLVERSION_THIRD */
+ const char *libidn;
+
+ /* These field were added in CURLVERSION_FOURTH */
+
+ /* Same as '_libiconv_version' if built with HAVE_ICONV */
+ int iconv_ver_num;
+
+ const char *libssh_version; /* human readable string */
+
/* These fields were added in CURLVERSION_FIFTH */
unsigned int brotli_ver_num; /* Numeric Brotli version
(MAJOR << 24) | (MINOR << 12) | PATCH */
@@ -2896,7 +2896,7 @@ struct curl_version_info_data {
const char *nghttp2_version; /* human readable string. */
const char *quic_version; /* human readable quic (+ HTTP/3) library +
version or NULL */
-
+
/* These fields were added in CURLVERSION_SEVENTH */
const char *cainfo; /* the built-in default CURLOPT_CAINFO, might
be NULL */
@@ -2945,85 +2945,85 @@ typedef struct curl_version_info_data curl_version_info_data;
#define CURL_VERSION_ZSTD (1<<26) /* zstd features are present */
#define CURL_VERSION_UNICODE (1<<27) /* Unicode support on Windows */
#define CURL_VERSION_HSTS (1<<28) /* HSTS is supported */
-
- /*
- * NAME curl_version_info()
- *
- * DESCRIPTION
- *
- * This function returns a pointer to a static copy of the version info
- * struct. See above.
- */
-CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion);
-
-/*
- * NAME curl_easy_strerror()
- *
- * DESCRIPTION
- *
- * The curl_easy_strerror function may be used to turn a CURLcode value
- * into the equivalent human readable error string. This is useful
- * for printing meaningful error messages.
- */
-CURL_EXTERN const char *curl_easy_strerror(CURLcode);
-
-/*
- * NAME curl_share_strerror()
- *
- * DESCRIPTION
- *
- * The curl_share_strerror function may be used to turn a CURLSHcode value
- * into the equivalent human readable error string. This is useful
- * for printing meaningful error messages.
- */
-CURL_EXTERN const char *curl_share_strerror(CURLSHcode);
-
-/*
- * NAME curl_easy_pause()
- *
- * DESCRIPTION
- *
- * The curl_easy_pause function pauses or unpauses transfers. Select the new
- * state by setting the bitmask, use the convenience defines below.
- *
- */
-CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask);
-
-#define CURLPAUSE_RECV (1<<0)
-#define CURLPAUSE_RECV_CONT (0)
-
-#define CURLPAUSE_SEND (1<<2)
-#define CURLPAUSE_SEND_CONT (0)
-
-#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND)
-#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT)
-
-#ifdef __cplusplus
-}
-#endif
-
-/* unfortunately, the easy.h and multi.h include files need options and info
- stuff before they can be included! */
-#include "easy.h" /* nothing in curl is fun without the easy stuff */
-#include "multi.h"
+
+ /*
+ * NAME curl_version_info()
+ *
+ * DESCRIPTION
+ *
+ * This function returns a pointer to a static copy of the version info
+ * struct. See above.
+ */
+CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion);
+
+/*
+ * NAME curl_easy_strerror()
+ *
+ * DESCRIPTION
+ *
+ * The curl_easy_strerror function may be used to turn a CURLcode value
+ * into the equivalent human readable error string. This is useful
+ * for printing meaningful error messages.
+ */
+CURL_EXTERN const char *curl_easy_strerror(CURLcode);
+
+/*
+ * NAME curl_share_strerror()
+ *
+ * DESCRIPTION
+ *
+ * The curl_share_strerror function may be used to turn a CURLSHcode value
+ * into the equivalent human readable error string. This is useful
+ * for printing meaningful error messages.
+ */
+CURL_EXTERN const char *curl_share_strerror(CURLSHcode);
+
+/*
+ * NAME curl_easy_pause()
+ *
+ * DESCRIPTION
+ *
+ * The curl_easy_pause function pauses or unpauses transfers. Select the new
+ * state by setting the bitmask, use the convenience defines below.
+ *
+ */
+CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask);
+
+#define CURLPAUSE_RECV (1<<0)
+#define CURLPAUSE_RECV_CONT (0)
+
+#define CURLPAUSE_SEND (1<<2)
+#define CURLPAUSE_SEND_CONT (0)
+
+#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND)
+#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT)
+
+#ifdef __cplusplus
+}
+#endif
+
+/* unfortunately, the easy.h and multi.h include files need options and info
+ stuff before they can be included! */
+#include "easy.h" /* nothing in curl is fun without the easy stuff */
+#include "multi.h"
#include "urlapi.h"
#include "options.h"
-
-/* the typechecker doesn't work in C++ (yet) */
-#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
- ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \
- !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK)
-#include "typecheck-gcc.h"
-#else
-#if defined(__STDC__) && (__STDC__ >= 1)
-/* This preprocessor magic that replaces a call with the exact same call is
- only done to make sure application authors pass exactly three arguments
- to these functions. */
-#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param)
-#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg)
-#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
-#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
-#endif /* __STDC__ >= 1 */
-#endif /* gcc >= 4.3 && !__cplusplus */
-
+
+/* the typechecker doesn't work in C++ (yet) */
+#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
+ ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \
+ !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK)
+#include "typecheck-gcc.h"
+#else
+#if defined(__STDC__) && (__STDC__ >= 1)
+/* This preprocessor magic that replaces a call with the exact same call is
+ only done to make sure application authors pass exactly three arguments
+ to these functions. */
+#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param)
+#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg)
+#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
+#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
+#endif /* __STDC__ >= 1 */
+#endif /* gcc >= 4.3 && !__cplusplus */
+
#endif /* CURLINC_CURL_H */
diff --git a/contrib/libs/curl/include/curl/curlver.h b/contrib/libs/curl/include/curl/curlver.h
index b4bd4ceb99..0acb5a8cbf 100644
--- a/contrib/libs/curl/include/curl/curlver.h
+++ b/contrib/libs/curl/include/curl/curlver.h
@@ -1,75 +1,75 @@
#ifndef CURLINC_CURLVER_H
#define CURLINC_CURLVER_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* This header file contains nothing but libcurl version info, generated by
- a script at release-time. This was made its own header file in 7.11.2 */
-
-/* This is the global package copyright */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* This header file contains nothing but libcurl version info, generated by
+ a script at release-time. This was made its own header file in 7.11.2 */
+
+/* This is the global package copyright */
#define LIBCURL_COPYRIGHT "1996 - 2020 Daniel Stenberg, <daniel@haxx.se>."
-
-/* This is the version number of the libcurl package from which this header
- file origins: */
+
+/* This is the version number of the libcurl package from which this header
+ file origins: */
#define LIBCURL_VERSION "7.74.0"
-
-/* The numeric version number is also available "in parts" by using these
- defines: */
-#define LIBCURL_VERSION_MAJOR 7
+
+/* The numeric version number is also available "in parts" by using these
+ defines: */
+#define LIBCURL_VERSION_MAJOR 7
#define LIBCURL_VERSION_MINOR 74
-#define LIBCURL_VERSION_PATCH 0
-
-/* This is the numeric version of the libcurl version number, meant for easier
+#define LIBCURL_VERSION_PATCH 0
+
+/* This is the numeric version of the libcurl version number, meant for easier
parsing and comparisons by programs. The LIBCURL_VERSION_NUM define will
- always follow this syntax:
-
- 0xXXYYZZ
-
- Where XX, YY and ZZ are the main version, release and patch numbers in
- hexadecimal (using 8 bits each). All three numbers are always represented
- using two digits. 1.2 would appear as "0x010200" while version 9.11.7
- appears as "0x090b07".
-
- This 6-digit (24 bits) hexadecimal number does not show pre-release number,
- and it is always a greater number in a more recent release. It makes
- comparisons with greater than and less than work.
+ always follow this syntax:
+
+ 0xXXYYZZ
+
+ Where XX, YY and ZZ are the main version, release and patch numbers in
+ hexadecimal (using 8 bits each). All three numbers are always represented
+ using two digits. 1.2 would appear as "0x010200" while version 9.11.7
+ appears as "0x090b07".
+
+ This 6-digit (24 bits) hexadecimal number does not show pre-release number,
+ and it is always a greater number in a more recent release. It makes
+ comparisons with greater than and less than work.
Note: This define is the full hex number and _does not_ use the
CURL_VERSION_BITS() macro since curl's own configure script greps for it
and needs it to contain the full number.
-*/
+*/
#define LIBCURL_VERSION_NUM 0x074a00
-
-/*
- * This is the date and time when the full source package was created. The
- * timestamp is not stored in git, as the timestamp is properly set in the
- * tarballs by the maketgz script.
- *
+
+/*
+ * This is the date and time when the full source package was created. The
+ * timestamp is not stored in git, as the timestamp is properly set in the
+ * tarballs by the maketgz script.
+ *
* The format of the date follows this template:
- *
+ *
* "2007-11-23"
- */
+ */
#define LIBCURL_TIMESTAMP "2020-12-09"
-
+
#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
#define CURL_AT_LEAST_VERSION(x,y,z) \
(LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
diff --git a/contrib/libs/curl/include/curl/easy.h b/contrib/libs/curl/include/curl/easy.h
index fc66f25790..2dbfb26b5b 100644
--- a/contrib/libs/curl/include/curl/easy.h
+++ b/contrib/libs/curl/include/curl/easy.h
@@ -1,30 +1,30 @@
#ifndef CURLINC_EASY_H
#define CURLINC_EASY_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
/* Flag bits in the curl_blob struct: */
#define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */
#define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */
@@ -36,76 +36,76 @@ struct curl_blob {
left zeroes */
};
-CURL_EXTERN CURL *curl_easy_init(void);
-CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
-CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
-CURL_EXTERN void curl_easy_cleanup(CURL *curl);
-
-/*
- * NAME curl_easy_getinfo()
- *
- * DESCRIPTION
- *
- * Request internal information from the curl session with this function. The
- * third argument MUST be a pointer to a long, a pointer to a char * or a
- * pointer to a double (as the documentation describes elsewhere). The data
- * pointed to will be filled in accordingly and can be relied upon only if the
- * function returns CURLE_OK. This function is intended to get used *AFTER* a
- * performed transfer, all results from this function are undefined until the
- * transfer is completed.
- */
-CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
-
-
-/*
- * NAME curl_easy_duphandle()
- *
- * DESCRIPTION
- *
- * Creates a new curl session handle with the same options set for the handle
- * passed in. Duplicating a handle could only be a matter of cloning data and
- * options, internal state info and things like persistent connections cannot
- * be transferred. It is useful in multithreaded applications when you can run
- * curl_easy_duphandle() for each new thread to avoid a series of identical
- * curl_easy_setopt() invokes in every thread.
- */
+CURL_EXTERN CURL *curl_easy_init(void);
+CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
+CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
+CURL_EXTERN void curl_easy_cleanup(CURL *curl);
+
+/*
+ * NAME curl_easy_getinfo()
+ *
+ * DESCRIPTION
+ *
+ * Request internal information from the curl session with this function. The
+ * third argument MUST be a pointer to a long, a pointer to a char * or a
+ * pointer to a double (as the documentation describes elsewhere). The data
+ * pointed to will be filled in accordingly and can be relied upon only if the
+ * function returns CURLE_OK. This function is intended to get used *AFTER* a
+ * performed transfer, all results from this function are undefined until the
+ * transfer is completed.
+ */
+CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
+
+
+/*
+ * NAME curl_easy_duphandle()
+ *
+ * DESCRIPTION
+ *
+ * Creates a new curl session handle with the same options set for the handle
+ * passed in. Duplicating a handle could only be a matter of cloning data and
+ * options, internal state info and things like persistent connections cannot
+ * be transferred. It is useful in multithreaded applications when you can run
+ * curl_easy_duphandle() for each new thread to avoid a series of identical
+ * curl_easy_setopt() invokes in every thread.
+ */
CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl);
-
-/*
- * NAME curl_easy_reset()
- *
- * DESCRIPTION
- *
- * Re-initializes a CURL handle to the default values. This puts back the
- * handle to the same state as it was in when it was just created.
- *
- * It does keep: live connections, the Session ID cache, the DNS cache and the
- * cookies.
- */
-CURL_EXTERN void curl_easy_reset(CURL *curl);
-
-/*
- * NAME curl_easy_recv()
- *
- * DESCRIPTION
- *
- * Receives data from the connected socket. Use after successful
- * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
- */
-CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
- size_t *n);
-
-/*
- * NAME curl_easy_send()
- *
- * DESCRIPTION
- *
- * Sends data over the connected socket. Use after successful
- * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
- */
-CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
- size_t buflen, size_t *n);
-
+
+/*
+ * NAME curl_easy_reset()
+ *
+ * DESCRIPTION
+ *
+ * Re-initializes a CURL handle to the default values. This puts back the
+ * handle to the same state as it was in when it was just created.
+ *
+ * It does keep: live connections, the Session ID cache, the DNS cache and the
+ * cookies.
+ */
+CURL_EXTERN void curl_easy_reset(CURL *curl);
+
+/*
+ * NAME curl_easy_recv()
+ *
+ * DESCRIPTION
+ *
+ * Receives data from the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
+CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
+ size_t *n);
+
+/*
+ * NAME curl_easy_send()
+ *
+ * DESCRIPTION
+ *
+ * Sends data over the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
+CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
+ size_t buflen, size_t *n);
+
/*
* NAME curl_easy_upkeep()
@@ -116,8 +116,8 @@ CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
*/
CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl);
-#ifdef __cplusplus
-}
-#endif
-
-#endif
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/contrib/libs/curl/include/curl/mprintf.h b/contrib/libs/curl/include/curl/mprintf.h
index ee1100f9a9..3549552dba 100644
--- a/contrib/libs/curl/include/curl/mprintf.h
+++ b/contrib/libs/curl/include/curl/mprintf.h
@@ -1,50 +1,50 @@
#ifndef CURLINC_MPRINTF_H
#define CURLINC_MPRINTF_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <stdarg.h>
-#include <stdio.h> /* needed for FILE */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <stdarg.h>
+#include <stdio.h> /* needed for FILE */
#include "curl.h" /* for CURL_EXTERN */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-CURL_EXTERN int curl_mprintf(const char *format, ...);
-CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...);
-CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...);
-CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
- const char *format, ...);
-CURL_EXTERN int curl_mvprintf(const char *format, va_list args);
-CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args);
-CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args);
-CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
- const char *format, va_list args);
-CURL_EXTERN char *curl_maprintf(const char *format, ...);
-CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args);
-
-#ifdef __cplusplus
-}
-#endif
-
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CURL_EXTERN int curl_mprintf(const char *format, ...);
+CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...);
+CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...);
+CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
+ const char *format, ...);
+CURL_EXTERN int curl_mvprintf(const char *format, va_list args);
+CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args);
+CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args);
+CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
+ const char *format, va_list args);
+CURL_EXTERN char *curl_maprintf(const char *format, ...);
+CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args);
+
+#ifdef __cplusplus
+}
+#endif
+
#endif /* CURLINC_MPRINTF_H */
diff --git a/contrib/libs/curl/include/curl/multi.h b/contrib/libs/curl/include/curl/multi.h
index 587362aa9d..37f9829b3b 100644
--- a/contrib/libs/curl/include/curl/multi.h
+++ b/contrib/libs/curl/include/curl/multi.h
@@ -1,180 +1,180 @@
#ifndef CURLINC_MULTI_H
#define CURLINC_MULTI_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-/*
- This is an "external" header file. Don't give away any internals here!
-
- GOALS
-
- o Enable a "pull" interface. The application that uses libcurl decides where
- and when to ask libcurl to get/send data.
-
- o Enable multiple simultaneous transfers in the same thread without making it
- complicated for the application.
-
- o Enable the application to select() on its own file descriptors and curl's
- file descriptors simultaneous easily.
-
-*/
-
-/*
- * This header file should not really need to include "curl.h" since curl.h
- * itself includes this file and we expect user applications to do #include
- * <curl/curl.h> without the need for especially including multi.h.
- *
- * For some reason we added this include here at one point, and rather than to
- * break existing (wrongly written) libcurl applications, we leave it as-is
- * but with this warning attached.
- */
-#include "curl.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+/*
+ This is an "external" header file. Don't give away any internals here!
+
+ GOALS
+
+ o Enable a "pull" interface. The application that uses libcurl decides where
+ and when to ask libcurl to get/send data.
+
+ o Enable multiple simultaneous transfers in the same thread without making it
+ complicated for the application.
+
+ o Enable the application to select() on its own file descriptors and curl's
+ file descriptors simultaneous easily.
+
+*/
+
+/*
+ * This header file should not really need to include "curl.h" since curl.h
+ * itself includes this file and we expect user applications to do #include
+ * <curl/curl.h> without the need for especially including multi.h.
+ *
+ * For some reason we added this include here at one point, and rather than to
+ * break existing (wrongly written) libcurl applications, we leave it as-is
+ * but with this warning attached.
+ */
+#include "curl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER)
typedef struct Curl_multi CURLM;
#else
-typedef void CURLM;
+typedef void CURLM;
#endif
-
-typedef enum {
- CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
- curl_multi_socket*() soon */
- CURLM_OK,
- CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
- CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
- CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */
- CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
- CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
- CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
- CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was
- attempted to get added - again */
+
+typedef enum {
+ CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
+ curl_multi_socket*() soon */
+ CURLM_OK,
+ CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
+ CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
+ CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */
+ CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
+ CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
+ CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
+ CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was
+ attempted to get added - again */
CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a
callback */
CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */
CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */
- CURLM_LAST
-} CURLMcode;
-
-/* just to make code nicer when using curl_multi_socket() you can now check
- for CURLM_CALL_MULTI_SOCKET too in the same style it works for
- curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
-#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
-
+ CURLM_LAST
+} CURLMcode;
+
+/* just to make code nicer when using curl_multi_socket() you can now check
+ for CURLM_CALL_MULTI_SOCKET too in the same style it works for
+ curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
+#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
+
/* bitmask bits for CURLMOPT_PIPELINING */
#define CURLPIPE_NOTHING 0L
#define CURLPIPE_HTTP1 1L
#define CURLPIPE_MULTIPLEX 2L
-typedef enum {
- CURLMSG_NONE, /* first, not used */
- CURLMSG_DONE, /* This easy handle has completed. 'result' contains
- the CURLcode of the transfer */
- CURLMSG_LAST /* last, not used */
-} CURLMSG;
-
-struct CURLMsg {
- CURLMSG msg; /* what this message means */
- CURL *easy_handle; /* the handle it concerns */
- union {
- void *whatever; /* message-specific data */
- CURLcode result; /* return code for transfer */
- } data;
-};
-typedef struct CURLMsg CURLMsg;
-
-/* Based on poll(2) structure and values.
- * We don't use pollfd and POLL* constants explicitly
- * to cover platforms without poll(). */
-#define CURL_WAIT_POLLIN 0x0001
-#define CURL_WAIT_POLLPRI 0x0002
-#define CURL_WAIT_POLLOUT 0x0004
-
-struct curl_waitfd {
- curl_socket_t fd;
- short events;
- short revents; /* not supported yet */
-};
-
-/*
- * Name: curl_multi_init()
- *
- * Desc: inititalize multi-style curl usage
- *
- * Returns: a new CURLM handle to use in all 'curl_multi' functions.
- */
-CURL_EXTERN CURLM *curl_multi_init(void);
-
-/*
- * Name: curl_multi_add_handle()
- *
- * Desc: add a standard curl handle to the multi stack
- *
- * Returns: CURLMcode type, general multi error code.
- */
-CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle,
- CURL *curl_handle);
-
- /*
- * Name: curl_multi_remove_handle()
- *
- * Desc: removes a curl handle from the multi stack again
- *
- * Returns: CURLMcode type, general multi error code.
- */
-CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
- CURL *curl_handle);
-
- /*
- * Name: curl_multi_fdset()
- *
- * Desc: Ask curl for its fd_set sets. The app can use these to select() or
- * poll() on. We want curl_multi_perform() called as soon as one of
- * them are ready.
- *
- * Returns: CURLMcode type, general multi error code.
- */
-CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle,
- fd_set *read_fd_set,
- fd_set *write_fd_set,
- fd_set *exc_fd_set,
- int *max_fd);
-
-/*
- * Name: curl_multi_wait()
- *
- * Desc: Poll on all fds within a CURLM set as well as any
- * additional fds passed to the function.
- *
- * Returns: CURLMcode type, general multi error code.
- */
-CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle,
- struct curl_waitfd extra_fds[],
- unsigned int extra_nfds,
- int timeout_ms,
- int *ret);
-
+typedef enum {
+ CURLMSG_NONE, /* first, not used */
+ CURLMSG_DONE, /* This easy handle has completed. 'result' contains
+ the CURLcode of the transfer */
+ CURLMSG_LAST /* last, not used */
+} CURLMSG;
+
+struct CURLMsg {
+ CURLMSG msg; /* what this message means */
+ CURL *easy_handle; /* the handle it concerns */
+ union {
+ void *whatever; /* message-specific data */
+ CURLcode result; /* return code for transfer */
+ } data;
+};
+typedef struct CURLMsg CURLMsg;
+
+/* Based on poll(2) structure and values.
+ * We don't use pollfd and POLL* constants explicitly
+ * to cover platforms without poll(). */
+#define CURL_WAIT_POLLIN 0x0001
+#define CURL_WAIT_POLLPRI 0x0002
+#define CURL_WAIT_POLLOUT 0x0004
+
+struct curl_waitfd {
+ curl_socket_t fd;
+ short events;
+ short revents; /* not supported yet */
+};
+
+/*
+ * Name: curl_multi_init()
+ *
+ * Desc: inititalize multi-style curl usage
+ *
+ * Returns: a new CURLM handle to use in all 'curl_multi' functions.
+ */
+CURL_EXTERN CURLM *curl_multi_init(void);
+
+/*
+ * Name: curl_multi_add_handle()
+ *
+ * Desc: add a standard curl handle to the multi stack
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle,
+ CURL *curl_handle);
+
+ /*
+ * Name: curl_multi_remove_handle()
+ *
+ * Desc: removes a curl handle from the multi stack again
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
+ CURL *curl_handle);
+
+ /*
+ * Name: curl_multi_fdset()
+ *
+ * Desc: Ask curl for its fd_set sets. The app can use these to select() or
+ * poll() on. We want curl_multi_perform() called as soon as one of
+ * them are ready.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle,
+ fd_set *read_fd_set,
+ fd_set *write_fd_set,
+ fd_set *exc_fd_set,
+ int *max_fd);
+
+/*
+ * Name: curl_multi_wait()
+ *
+ * Desc: Poll on all fds within a CURLM set as well as any
+ * additional fds passed to the function.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle,
+ struct curl_waitfd extra_fds[],
+ unsigned int extra_nfds,
+ int timeout_ms,
+ int *ret);
+
/*
* Name: curl_multi_poll()
*
@@ -198,194 +198,194 @@ CURL_EXTERN CURLMcode curl_multi_poll(CURLM *multi_handle,
*/
CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle);
- /*
- * Name: curl_multi_perform()
- *
- * Desc: When the app thinks there's data available for curl it calls this
- * function to read/write whatever there is right now. This returns
- * as soon as the reads and writes are done. This function does not
- * require that there actually is data available for reading or that
- * data can be written, it can be called just in case. It returns
- * the number of handles that still transfer data in the second
- * argument's integer-pointer.
- *
- * Returns: CURLMcode type, general multi error code. *NOTE* that this only
- * returns errors etc regarding the whole multi stack. There might
+ /*
+ * Name: curl_multi_perform()
+ *
+ * Desc: When the app thinks there's data available for curl it calls this
+ * function to read/write whatever there is right now. This returns
+ * as soon as the reads and writes are done. This function does not
+ * require that there actually is data available for reading or that
+ * data can be written, it can be called just in case. It returns
+ * the number of handles that still transfer data in the second
+ * argument's integer-pointer.
+ *
+ * Returns: CURLMcode type, general multi error code. *NOTE* that this only
+ * returns errors etc regarding the whole multi stack. There might
* still have occurred problems on individual transfers even when
* this returns OK.
- */
-CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle,
- int *running_handles);
-
- /*
- * Name: curl_multi_cleanup()
- *
- * Desc: Cleans up and removes a whole multi stack. It does not free or
- * touch any individual easy handles in any way. We need to define
- * in what state those handles will be if this function is called
- * in the middle of a transfer.
- *
- * Returns: CURLMcode type, general multi error code.
- */
-CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle);
-
-/*
- * Name: curl_multi_info_read()
- *
- * Desc: Ask the multi handle if there's any messages/informationals from
- * the individual transfers. Messages include informationals such as
- * error code from the transfer or just the fact that a transfer is
- * completed. More details on these should be written down as well.
- *
- * Repeated calls to this function will return a new struct each
- * time, until a special "end of msgs" struct is returned as a signal
- * that there is no more to get at this point.
- *
- * The data the returned pointer points to will not survive calling
- * curl_multi_cleanup().
- *
- * The 'CURLMsg' struct is meant to be very simple and only contain
+ */
+CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle,
+ int *running_handles);
+
+ /*
+ * Name: curl_multi_cleanup()
+ *
+ * Desc: Cleans up and removes a whole multi stack. It does not free or
+ * touch any individual easy handles in any way. We need to define
+ * in what state those handles will be if this function is called
+ * in the middle of a transfer.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle);
+
+/*
+ * Name: curl_multi_info_read()
+ *
+ * Desc: Ask the multi handle if there's any messages/informationals from
+ * the individual transfers. Messages include informationals such as
+ * error code from the transfer or just the fact that a transfer is
+ * completed. More details on these should be written down as well.
+ *
+ * Repeated calls to this function will return a new struct each
+ * time, until a special "end of msgs" struct is returned as a signal
+ * that there is no more to get at this point.
+ *
+ * The data the returned pointer points to will not survive calling
+ * curl_multi_cleanup().
+ *
+ * The 'CURLMsg' struct is meant to be very simple and only contain
* very basic information. If more involved information is wanted,
- * we will provide the particular "transfer handle" in that struct
- * and that should/could/would be used in subsequent
- * curl_easy_getinfo() calls (or similar). The point being that we
- * must never expose complex structs to applications, as then we'll
- * undoubtably get backwards compatibility problems in the future.
- *
- * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
- * of structs. It also writes the number of messages left in the
- * queue (after this read) in the integer the second argument points
- * to.
- */
-CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle,
- int *msgs_in_queue);
-
-/*
- * Name: curl_multi_strerror()
- *
- * Desc: The curl_multi_strerror function may be used to turn a CURLMcode
- * value into the equivalent human readable error string. This is
- * useful for printing meaningful error messages.
- *
+ * we will provide the particular "transfer handle" in that struct
+ * and that should/could/would be used in subsequent
+ * curl_easy_getinfo() calls (or similar). The point being that we
+ * must never expose complex structs to applications, as then we'll
+ * undoubtably get backwards compatibility problems in the future.
+ *
+ * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
+ * of structs. It also writes the number of messages left in the
+ * queue (after this read) in the integer the second argument points
+ * to.
+ */
+CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle,
+ int *msgs_in_queue);
+
+/*
+ * Name: curl_multi_strerror()
+ *
+ * Desc: The curl_multi_strerror function may be used to turn a CURLMcode
+ * value into the equivalent human readable error string. This is
+ * useful for printing meaningful error messages.
+ *
* Returns: A pointer to a null-terminated error message.
- */
-CURL_EXTERN const char *curl_multi_strerror(CURLMcode);
-
-/*
- * Name: curl_multi_socket() and
- * curl_multi_socket_all()
- *
- * Desc: An alternative version of curl_multi_perform() that allows the
- * application to pass in one of the file descriptors that have been
- * detected to have "action" on them and let libcurl perform.
- * See man page for details.
- */
-#define CURL_POLL_NONE 0
-#define CURL_POLL_IN 1
-#define CURL_POLL_OUT 2
-#define CURL_POLL_INOUT 3
-#define CURL_POLL_REMOVE 4
-
-#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
-
-#define CURL_CSELECT_IN 0x01
-#define CURL_CSELECT_OUT 0x02
-#define CURL_CSELECT_ERR 0x04
-
-typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
- curl_socket_t s, /* socket */
- int what, /* see above */
- void *userp, /* private callback
- pointer */
- void *socketp); /* private socket
- pointer */
-/*
- * Name: curl_multi_timer_callback
- *
- * Desc: Called by libcurl whenever the library detects a change in the
- * maximum number of milliseconds the app is allowed to wait before
- * curl_multi_socket() or curl_multi_perform() must be called
- * (to allow libcurl's timed events to take place).
- *
- * Returns: The callback should return zero.
- */
-typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */
- long timeout_ms, /* see above */
- void *userp); /* private callback
- pointer */
-
-CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
- int *running_handles);
-
-CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle,
- curl_socket_t s,
- int ev_bitmask,
- int *running_handles);
-
-CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle,
- int *running_handles);
-
-#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
-/* This macro below was added in 7.16.3 to push users who recompile to use
- the new curl_multi_socket_action() instead of the old curl_multi_socket()
-*/
-#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z)
-#endif
-
-/*
- * Name: curl_multi_timeout()
- *
- * Desc: Returns the maximum number of milliseconds the app is allowed to
- * wait before curl_multi_socket() or curl_multi_perform() must be
- * called (to allow libcurl's timed events to take place).
- *
- * Returns: CURLM error code.
- */
-CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle,
- long *milliseconds);
-
-typedef enum {
- /* This is the socket callback function pointer */
+ */
+CURL_EXTERN const char *curl_multi_strerror(CURLMcode);
+
+/*
+ * Name: curl_multi_socket() and
+ * curl_multi_socket_all()
+ *
+ * Desc: An alternative version of curl_multi_perform() that allows the
+ * application to pass in one of the file descriptors that have been
+ * detected to have "action" on them and let libcurl perform.
+ * See man page for details.
+ */
+#define CURL_POLL_NONE 0
+#define CURL_POLL_IN 1
+#define CURL_POLL_OUT 2
+#define CURL_POLL_INOUT 3
+#define CURL_POLL_REMOVE 4
+
+#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
+
+#define CURL_CSELECT_IN 0x01
+#define CURL_CSELECT_OUT 0x02
+#define CURL_CSELECT_ERR 0x04
+
+typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
+ curl_socket_t s, /* socket */
+ int what, /* see above */
+ void *userp, /* private callback
+ pointer */
+ void *socketp); /* private socket
+ pointer */
+/*
+ * Name: curl_multi_timer_callback
+ *
+ * Desc: Called by libcurl whenever the library detects a change in the
+ * maximum number of milliseconds the app is allowed to wait before
+ * curl_multi_socket() or curl_multi_perform() must be called
+ * (to allow libcurl's timed events to take place).
+ *
+ * Returns: The callback should return zero.
+ */
+typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */
+ long timeout_ms, /* see above */
+ void *userp); /* private callback
+ pointer */
+
+CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
+ int *running_handles);
+
+CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle,
+ curl_socket_t s,
+ int ev_bitmask,
+ int *running_handles);
+
+CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle,
+ int *running_handles);
+
+#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
+/* This macro below was added in 7.16.3 to push users who recompile to use
+ the new curl_multi_socket_action() instead of the old curl_multi_socket()
+*/
+#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z)
+#endif
+
+/*
+ * Name: curl_multi_timeout()
+ *
+ * Desc: Returns the maximum number of milliseconds the app is allowed to
+ * wait before curl_multi_socket() or curl_multi_perform() must be
+ * called (to allow libcurl's timed events to take place).
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle,
+ long *milliseconds);
+
+typedef enum {
+ /* This is the socket callback function pointer */
CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1),
-
- /* This is the argument passed to the socket callback */
+
+ /* This is the argument passed to the socket callback */
CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2),
-
- /* set to 1 to enable pipelining for this multi handle */
+
+ /* set to 1 to enable pipelining for this multi handle */
CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3),
-
- /* This is the timer callback function pointer */
+
+ /* This is the timer callback function pointer */
CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4),
-
- /* This is the argument passed to the timer callback */
+
+ /* This is the argument passed to the timer callback */
CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5),
-
- /* maximum number of entries in the connection cache */
+
+ /* maximum number of entries in the connection cache */
CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6),
-
- /* maximum number of (pipelining) connections to one host */
+
+ /* maximum number of (pipelining) connections to one host */
CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7),
-
- /* maximum number of requests in a pipeline */
+
+ /* maximum number of requests in a pipeline */
CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8),
-
- /* a connection with a content-length longer than this
- will not be considered for pipelining */
+
+ /* a connection with a content-length longer than this
+ will not be considered for pipelining */
CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9),
-
- /* a connection with a chunk length longer than this
- will not be considered for pipelining */
+
+ /* a connection with a chunk length longer than this
+ will not be considered for pipelining */
CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10),
-
+
/* a list of site names(+port) that are blocked from pipelining */
CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11),
-
+
/* a list of server types that are blocked from pipelining */
CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12),
-
- /* maximum number of open connections in total */
+
+ /* maximum number of open connections in total */
CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13),
-
+
/* This is the server push callback function pointer */
CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14),
@@ -395,33 +395,33 @@ typedef enum {
/* maximum number of concurrent streams to support on a connection */
CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16),
- CURLMOPT_LASTENTRY /* the last unused */
-} CURLMoption;
-
-
-/*
- * Name: curl_multi_setopt()
- *
- * Desc: Sets options for the multi handle.
- *
- * Returns: CURLM error code.
- */
-CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle,
- CURLMoption option, ...);
-
-
-/*
- * Name: curl_multi_assign()
- *
- * Desc: This function sets an association in the multi handle between the
- * given socket and a private pointer of the application. This is
- * (only) useful for curl_multi_socket uses.
- *
- * Returns: CURLM error code.
- */
-CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle,
- curl_socket_t sockfd, void *sockp);
-
+ CURLMOPT_LASTENTRY /* the last unused */
+} CURLMoption;
+
+
+/*
+ * Name: curl_multi_setopt()
+ *
+ * Desc: Sets options for the multi handle.
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle,
+ CURLMoption option, ...);
+
+
+/*
+ * Name: curl_multi_assign()
+ *
+ * Desc: This function sets an association in the multi handle between the
+ * given socket and a private pointer of the application. This is
+ * (only) useful for curl_multi_socket uses.
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle,
+ curl_socket_t sockfd, void *sockp);
+
/*
* Name: curl_push_callback
@@ -449,8 +449,8 @@ typedef int (*curl_push_callback)(CURL *parent,
struct curl_pushheaders *headers,
void *userp);
-#ifdef __cplusplus
-} /* end of extern "C" */
-#endif
-
-#endif
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+#endif
diff --git a/contrib/libs/curl/include/curl/stdcheaders.h b/contrib/libs/curl/include/curl/stdcheaders.h
index f8cb232e7a..60596c7568 100644
--- a/contrib/libs/curl/include/curl/stdcheaders.h
+++ b/contrib/libs/curl/include/curl/stdcheaders.h
@@ -1,33 +1,33 @@
#ifndef CURLINC_STDCHEADERS_H
#define CURLINC_STDCHEADERS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <sys/types.h>
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <sys/types.h>
+
size_t fread(void *, size_t, size_t, FILE *);
size_t fwrite(const void *, size_t, size_t, FILE *);
-
-int strcasecmp(const char *, const char *);
-int strncasecmp(const char *, const char *, size_t);
-
+
+int strcasecmp(const char *, const char *);
+int strncasecmp(const char *, const char *, size_t);
+
#endif /* CURLINC_STDCHEADERS_H */
diff --git a/contrib/libs/curl/include/curl/typecheck-gcc.h b/contrib/libs/curl/include/curl/typecheck-gcc.h
index 1e57ebb961..6d84150dc2 100644
--- a/contrib/libs/curl/include/curl/typecheck-gcc.h
+++ b/contrib/libs/curl/include/curl/typecheck-gcc.h
@@ -1,43 +1,43 @@
#ifndef CURLINC_TYPECHECK_GCC_H
#define CURLINC_TYPECHECK_GCC_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* wraps curl_easy_setopt() with typechecking */
-
-/* To add a new kind of warning, add an
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* wraps curl_easy_setopt() with typechecking */
+
+/* To add a new kind of warning, add an
* if(curlcheck_sometype_option(_curl_opt))
* if(!curlcheck_sometype(value))
- * _curl_easy_setopt_err_sometype();
+ * _curl_easy_setopt_err_sometype();
* block and define curlcheck_sometype_option, curlcheck_sometype and
- * _curl_easy_setopt_err_sometype below
- *
- * NOTE: We use two nested 'if' statements here instead of the && operator, in
- * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x
- * when compiling with -Wlogical-op.
- *
- * To add an option that uses the same type as an existing option, you'll just
- * need to extend the appropriate _curl_*_option macro
- */
+ * _curl_easy_setopt_err_sometype below
+ *
+ * NOTE: We use two nested 'if' statements here instead of the && operator, in
+ * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x
+ * when compiling with -Wlogical-op.
+ *
+ * To add an option that uses the same type as an existing option, you'll just
+ * need to extend the appropriate _curl_*_option macro
+ */
#define curl_easy_setopt(handle, option, value) \
__extension__({ \
__typeof__(option) _curl_opt = option; \
@@ -111,8 +111,8 @@
} \
curl_easy_setopt(handle, _curl_opt, value); \
})
-
-/* wraps curl_easy_getinfo() with typechecking */
+
+/* wraps curl_easy_getinfo() with typechecking */
#define curl_easy_getinfo(handle, info, arg) \
__extension__({ \
__typeof__(info) _curl_info = info; \
@@ -144,63 +144,63 @@
} \
curl_easy_getinfo(handle, _curl_info, arg); \
})
-
+
/*
* For now, just make sure that the functions are called with three arguments
- */
-#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
-#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
-
-
-/* the actual warnings, triggered by calling the _curl_easy_setopt_err*
- * functions */
-
-/* To define a new warning, use _CURL_WARNING(identifier, "message") */
+ */
+#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
+#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
+
+
+/* the actual warnings, triggered by calling the _curl_easy_setopt_err*
+ * functions */
+
+/* To define a new warning, use _CURL_WARNING(identifier, "message") */
#define CURLWARNING(id, message) \
static void __attribute__((__warning__(message))) \
__attribute__((__unused__)) __attribute__((__noinline__)) \
- id(void) { __asm__(""); }
-
+ id(void) { __asm__(""); }
+
CURLWARNING(_curl_easy_setopt_err_long,
- "curl_easy_setopt expects a long argument for this option")
+ "curl_easy_setopt expects a long argument for this option")
CURLWARNING(_curl_easy_setopt_err_curl_off_t,
- "curl_easy_setopt expects a curl_off_t argument for this option")
+ "curl_easy_setopt expects a curl_off_t argument for this option")
CURLWARNING(_curl_easy_setopt_err_string,
- "curl_easy_setopt expects a "
+ "curl_easy_setopt expects a "
"string ('char *' or char[]) argument for this option"
- )
+ )
CURLWARNING(_curl_easy_setopt_err_write_callback,
- "curl_easy_setopt expects a curl_write_callback argument for this option")
+ "curl_easy_setopt expects a curl_write_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_resolver_start_callback,
"curl_easy_setopt expects a "
"curl_resolver_start_callback argument for this option"
)
CURLWARNING(_curl_easy_setopt_err_read_cb,
- "curl_easy_setopt expects a curl_read_callback argument for this option")
+ "curl_easy_setopt expects a curl_read_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_ioctl_cb,
- "curl_easy_setopt expects a curl_ioctl_callback argument for this option")
+ "curl_easy_setopt expects a curl_ioctl_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_sockopt_cb,
- "curl_easy_setopt expects a curl_sockopt_callback argument for this option")
+ "curl_easy_setopt expects a curl_sockopt_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_opensocket_cb,
- "curl_easy_setopt expects a "
- "curl_opensocket_callback argument for this option"
- )
+ "curl_easy_setopt expects a "
+ "curl_opensocket_callback argument for this option"
+ )
CURLWARNING(_curl_easy_setopt_err_progress_cb,
- "curl_easy_setopt expects a curl_progress_callback argument for this option")
+ "curl_easy_setopt expects a curl_progress_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_debug_cb,
- "curl_easy_setopt expects a curl_debug_callback argument for this option")
+ "curl_easy_setopt expects a curl_debug_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_ssl_ctx_cb,
- "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option")
+ "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_conv_cb,
- "curl_easy_setopt expects a curl_conv_callback argument for this option")
+ "curl_easy_setopt expects a curl_conv_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_seek_cb,
- "curl_easy_setopt expects a curl_seek_callback argument for this option")
+ "curl_easy_setopt expects a curl_seek_callback argument for this option")
CURLWARNING(_curl_easy_setopt_err_cb_data,
- "curl_easy_setopt expects a "
- "private data pointer as argument for this option")
+ "curl_easy_setopt expects a "
+ "private data pointer as argument for this option")
CURLWARNING(_curl_easy_setopt_err_error_buffer,
- "curl_easy_setopt expects a "
- "char buffer of CURL_ERROR_SIZE as argument for this option")
+ "curl_easy_setopt expects a "
+ "char buffer of CURL_ERROR_SIZE as argument for this option")
CURLWARNING(_curl_easy_setopt_err_FILE,
"curl_easy_setopt expects a 'FILE *' argument for this option")
CURLWARNING(_curl_easy_setopt_err_postfields,
@@ -214,14 +214,14 @@ CURLWARNING(_curl_easy_setopt_err_curl_mimepost,
CURLWARNING(_curl_easy_setopt_err_curl_slist,
"curl_easy_setopt expects a 'struct curl_slist *' argument for this option")
CURLWARNING(_curl_easy_setopt_err_CURLSH,
- "curl_easy_setopt expects a CURLSH* argument for this option")
-
+ "curl_easy_setopt expects a CURLSH* argument for this option")
+
CURLWARNING(_curl_easy_getinfo_err_string,
"curl_easy_getinfo expects a pointer to 'char *' for this info")
CURLWARNING(_curl_easy_getinfo_err_long,
- "curl_easy_getinfo expects a pointer to long for this info")
+ "curl_easy_getinfo expects a pointer to long for this info")
CURLWARNING(_curl_easy_getinfo_err_double,
- "curl_easy_getinfo expects a pointer to double for this info")
+ "curl_easy_getinfo expects a pointer to double for this info")
CURLWARNING(_curl_easy_getinfo_err_curl_slist,
"curl_easy_getinfo expects a pointer to 'struct curl_slist *' for this info")
CURLWARNING(_curl_easy_getinfo_err_curl_tlssesssioninfo,
@@ -234,33 +234,33 @@ CURLWARNING(_curl_easy_getinfo_err_curl_socket,
"curl_easy_getinfo expects a pointer to curl_socket_t for this info")
CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
"curl_easy_getinfo expects a pointer to curl_off_t for this info")
-
-/* groups of curl_easy_setops options that take the same type of argument */
-
-/* To add a new option to one of the groups, just add
- * (option) == CURLOPT_SOMETHING
- * to the or-expression. If the option takes a long or curl_off_t, you don't
- * have to do anything
- */
-
-/* evaluates to true if option takes a long argument */
+
+/* groups of curl_easy_setops options that take the same type of argument */
+
+/* To add a new option to one of the groups, just add
+ * (option) == CURLOPT_SOMETHING
+ * to the or-expression. If the option takes a long or curl_off_t, you don't
+ * have to do anything
+ */
+
+/* evaluates to true if option takes a long argument */
#define curlcheck_long_option(option) \
- (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT)
-
+ (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT)
+
#define curlcheck_off_t_option(option) \
(((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB))
-
-/* evaluates to true if option takes a char* argument */
+
+/* evaluates to true if option takes a char* argument */
#define curlcheck_string_option(option) \
((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \
- (option) == CURLOPT_ACCEPT_ENCODING || \
+ (option) == CURLOPT_ACCEPT_ENCODING || \
(option) == CURLOPT_ALTSVC || \
(option) == CURLOPT_CAINFO || \
(option) == CURLOPT_CAPATH || \
- (option) == CURLOPT_COOKIE || \
- (option) == CURLOPT_COOKIEFILE || \
- (option) == CURLOPT_COOKIEJAR || \
- (option) == CURLOPT_COOKIELIST || \
+ (option) == CURLOPT_COOKIE || \
+ (option) == CURLOPT_COOKIEFILE || \
+ (option) == CURLOPT_COOKIEJAR || \
+ (option) == CURLOPT_COOKIELIST || \
(option) == CURLOPT_CRLFILE || \
(option) == CURLOPT_CUSTOMREQUEST || \
(option) == CURLOPT_DEFAULT_PROTOCOL || \
@@ -270,9 +270,9 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
(option) == CURLOPT_DNS_SERVERS || \
(option) == CURLOPT_DOH_URL || \
(option) == CURLOPT_EGDSOCKET || \
- (option) == CURLOPT_FTPPORT || \
+ (option) == CURLOPT_FTPPORT || \
(option) == CURLOPT_FTP_ACCOUNT || \
- (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \
+ (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \
(option) == CURLOPT_HSTS || \
(option) == CURLOPT_INTERFACE || \
(option) == CURLOPT_ISSUERCERT || \
@@ -307,7 +307,7 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
(option) == CURLOPT_PROXY_TLSAUTH_TYPE || \
(option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \
(option) == CURLOPT_RANDOM_FILE || \
- (option) == CURLOPT_RANGE || \
+ (option) == CURLOPT_RANGE || \
(option) == CURLOPT_REFERER || \
(option) == CURLOPT_REQUEST_TARGET || \
(option) == CURLOPT_RTSP_SESSION_ID || \
@@ -320,12 +320,12 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
(option) == CURLOPT_SSH_KNOWNHOSTS || \
(option) == CURLOPT_SSH_PRIVATE_KEYFILE || \
(option) == CURLOPT_SSH_PUBLIC_KEYFILE || \
- (option) == CURLOPT_SSLCERT || \
- (option) == CURLOPT_SSLCERTTYPE || \
+ (option) == CURLOPT_SSLCERT || \
+ (option) == CURLOPT_SSLCERTTYPE || \
(option) == CURLOPT_SSLENGINE || \
- (option) == CURLOPT_SSLKEY || \
- (option) == CURLOPT_SSLKEYTYPE || \
- (option) == CURLOPT_SSL_CIPHER_LIST || \
+ (option) == CURLOPT_SSLKEY || \
+ (option) == CURLOPT_SSLKEYTYPE || \
+ (option) == CURLOPT_SSL_CIPHER_LIST || \
(option) == CURLOPT_TLS13_CIPHERS || \
(option) == CURLOPT_TLSAUTH_PASSWORD || \
(option) == CURLOPT_TLSAUTH_TYPE || \
@@ -335,22 +335,22 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
(option) == CURLOPT_USERAGENT || \
(option) == CURLOPT_USERNAME || \
(option) == CURLOPT_USERPWD || \
- (option) == CURLOPT_XOAUTH2_BEARER || \
+ (option) == CURLOPT_XOAUTH2_BEARER || \
(option) == CURLOPT_SSL_EC_CURVES || \
- 0)
-
-/* evaluates to true if option takes a curl_write_callback argument */
+ 0)
+
+/* evaluates to true if option takes a curl_write_callback argument */
#define curlcheck_write_cb_option(option) \
((option) == CURLOPT_HEADERFUNCTION || \
- (option) == CURLOPT_WRITEFUNCTION)
-
-/* evaluates to true if option takes a curl_conv_callback argument */
+ (option) == CURLOPT_WRITEFUNCTION)
+
+/* evaluates to true if option takes a curl_conv_callback argument */
#define curlcheck_conv_cb_option(option) \
((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \
(option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \
- (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION)
-
-/* evaluates to true if option takes a data argument to pass to a callback */
+ (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION)
+
+/* evaluates to true if option takes a data argument to pass to a callback */
#define curlcheck_cb_data_option(option) \
((option) == CURLOPT_CHUNK_DATA || \
(option) == CURLOPT_CLOSESOCKETDATA || \
@@ -360,62 +360,62 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
(option) == CURLOPT_HSTSREADDATA || \
(option) == CURLOPT_HSTSWRITEDATA || \
(option) == CURLOPT_INTERLEAVEDATA || \
- (option) == CURLOPT_IOCTLDATA || \
- (option) == CURLOPT_OPENSOCKETDATA || \
- (option) == CURLOPT_PROGRESSDATA || \
+ (option) == CURLOPT_IOCTLDATA || \
+ (option) == CURLOPT_OPENSOCKETDATA || \
+ (option) == CURLOPT_PROGRESSDATA || \
(option) == CURLOPT_READDATA || \
- (option) == CURLOPT_SEEKDATA || \
+ (option) == CURLOPT_SEEKDATA || \
(option) == CURLOPT_SOCKOPTDATA || \
- (option) == CURLOPT_SSH_KEYDATA || \
+ (option) == CURLOPT_SSH_KEYDATA || \
(option) == CURLOPT_SSL_CTX_DATA || \
(option) == CURLOPT_WRITEDATA || \
(option) == CURLOPT_RESOLVER_START_DATA || \
(option) == CURLOPT_TRAILERDATA || \
- 0)
-
-/* evaluates to true if option takes a POST data argument (void* or char*) */
+ 0)
+
+/* evaluates to true if option takes a POST data argument (void* or char*) */
#define curlcheck_postfields_option(option) \
- ((option) == CURLOPT_POSTFIELDS || \
- (option) == CURLOPT_COPYPOSTFIELDS || \
- 0)
-
-/* evaluates to true if option takes a struct curl_slist * argument */
+ ((option) == CURLOPT_POSTFIELDS || \
+ (option) == CURLOPT_COPYPOSTFIELDS || \
+ 0)
+
+/* evaluates to true if option takes a struct curl_slist * argument */
#define curlcheck_slist_option(option) \
((option) == CURLOPT_HTTP200ALIASES || \
(option) == CURLOPT_HTTPHEADER || \
(option) == CURLOPT_MAIL_RCPT || \
- (option) == CURLOPT_POSTQUOTE || \
- (option) == CURLOPT_PREQUOTE || \
+ (option) == CURLOPT_POSTQUOTE || \
+ (option) == CURLOPT_PREQUOTE || \
(option) == CURLOPT_PROXYHEADER || \
(option) == CURLOPT_QUOTE || \
(option) == CURLOPT_RESOLVE || \
- (option) == CURLOPT_TELNETOPTIONS || \
+ (option) == CURLOPT_TELNETOPTIONS || \
(option) == CURLOPT_CONNECT_TO || \
- 0)
-
-/* groups of curl_easy_getinfo infos that take the same type of argument */
-
-/* evaluates to true if info expects a pointer to char * argument */
+ 0)
+
+/* groups of curl_easy_getinfo infos that take the same type of argument */
+
+/* evaluates to true if info expects a pointer to char * argument */
#define curlcheck_string_info(info) \
(CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \
(info) != CURLINFO_PRIVATE)
-
-/* evaluates to true if info expects a pointer to long argument */
+
+/* evaluates to true if info expects a pointer to long argument */
#define curlcheck_long_info(info) \
- (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE)
-
-/* evaluates to true if info expects a pointer to double argument */
+ (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE)
+
+/* evaluates to true if info expects a pointer to double argument */
#define curlcheck_double_info(info) \
- (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST)
-
-/* true if info expects a pointer to struct curl_slist * argument */
+ (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST)
+
+/* true if info expects a pointer to struct curl_slist * argument */
#define curlcheck_slist_info(info) \
(((info) == CURLINFO_SSL_ENGINES) || ((info) == CURLINFO_COOKIELIST))
-
+
/* true if info expects a pointer to struct curl_tlssessioninfo * argument */
#define curlcheck_tlssessioninfo_info(info) \
(((info) == CURLINFO_TLS_SSL_PTR) || ((info) == CURLINFO_TLS_SESSION))
-
+
/* true if info expects a pointer to struct curl_certinfo * argument */
#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO)
@@ -428,104 +428,104 @@ CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
(CURLINFO_OFF_T < (info))
-/* typecheck helpers -- check whether given expression has requested type*/
-
+/* typecheck helpers -- check whether given expression has requested type*/
+
/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros,
- * otherwise define a new macro. Search for __builtin_types_compatible_p
- * in the GCC manual.
- * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is
- * the actual expression passed to the curl_easy_setopt macro. This
- * means that you can only apply the sizeof and __typeof__ operators, no
- * == or whatsoever.
- */
-
+ * otherwise define a new macro. Search for __builtin_types_compatible_p
+ * in the GCC manual.
+ * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is
+ * the actual expression passed to the curl_easy_setopt macro. This
+ * means that you can only apply the sizeof and __typeof__ operators, no
+ * == or whatsoever.
+ */
+
/* XXX: should evaluate to true if expr is a pointer */
#define curlcheck_any_ptr(expr) \
(sizeof(expr) == sizeof(void *))
-
-/* evaluates to true if expr is NULL */
-/* XXX: must not evaluate expr, so this check is not accurate */
+
+/* evaluates to true if expr is NULL */
+/* XXX: must not evaluate expr, so this check is not accurate */
#define curlcheck_NULL(expr) \
- (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL)))
-
-/* evaluates to true if expr is type*, const type* or NULL */
+ (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL)))
+
+/* evaluates to true if expr is type*, const type* or NULL */
#define curlcheck_ptr(expr, type) \
(curlcheck_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), type *) || \
- __builtin_types_compatible_p(__typeof__(expr), const type *))
-
-/* evaluates to true if expr is one of type[], type*, NULL or const type* */
+ __builtin_types_compatible_p(__typeof__(expr), const type *))
+
+/* evaluates to true if expr is one of type[], type*, NULL or const type* */
#define curlcheck_arr(expr, type) \
(curlcheck_ptr((expr), type) || \
- __builtin_types_compatible_p(__typeof__(expr), type []))
-
-/* evaluates to true if expr is a string */
+ __builtin_types_compatible_p(__typeof__(expr), type []))
+
+/* evaluates to true if expr is a string */
#define curlcheck_string(expr) \
(curlcheck_arr((expr), char) || \
curlcheck_arr((expr), signed char) || \
curlcheck_arr((expr), unsigned char))
-
-/* evaluates to true if expr is a long (no matter the signedness)
- * XXX: for now, int is also accepted (and therefore short and char, which
- * are promoted to int when passed to a variadic function) */
+
+/* evaluates to true if expr is a long (no matter the signedness)
+ * XXX: for now, int is also accepted (and therefore short and char, which
+ * are promoted to int when passed to a variadic function) */
#define curlcheck_long(expr) \
- (__builtin_types_compatible_p(__typeof__(expr), long) || \
- __builtin_types_compatible_p(__typeof__(expr), signed long) || \
- __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \
- __builtin_types_compatible_p(__typeof__(expr), int) || \
- __builtin_types_compatible_p(__typeof__(expr), signed int) || \
- __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \
- __builtin_types_compatible_p(__typeof__(expr), short) || \
- __builtin_types_compatible_p(__typeof__(expr), signed short) || \
- __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \
- __builtin_types_compatible_p(__typeof__(expr), char) || \
- __builtin_types_compatible_p(__typeof__(expr), signed char) || \
- __builtin_types_compatible_p(__typeof__(expr), unsigned char))
-
-/* evaluates to true if expr is of type curl_off_t */
+ (__builtin_types_compatible_p(__typeof__(expr), long) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed long) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \
+ __builtin_types_compatible_p(__typeof__(expr), int) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed int) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \
+ __builtin_types_compatible_p(__typeof__(expr), short) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed short) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \
+ __builtin_types_compatible_p(__typeof__(expr), char) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed char) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned char))
+
+/* evaluates to true if expr is of type curl_off_t */
#define curlcheck_off_t(expr) \
- (__builtin_types_compatible_p(__typeof__(expr), curl_off_t))
-
-/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */
-/* XXX: also check size of an char[] array? */
+ (__builtin_types_compatible_p(__typeof__(expr), curl_off_t))
+
+/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */
+/* XXX: also check size of an char[] array? */
#define curlcheck_error_buffer(expr) \
(curlcheck_NULL(expr) || \
__builtin_types_compatible_p(__typeof__(expr), char *) || \
- __builtin_types_compatible_p(__typeof__(expr), char[]))
-
-/* evaluates to true if expr is of type (const) void* or (const) FILE* */
-#if 0
+ __builtin_types_compatible_p(__typeof__(expr), char[]))
+
+/* evaluates to true if expr is of type (const) void* or (const) FILE* */
+#if 0
#define curlcheck_cb_data(expr) \
(curlcheck_ptr((expr), void) || \
curlcheck_ptr((expr), FILE))
-#else /* be less strict */
+#else /* be less strict */
#define curlcheck_cb_data(expr) \
curlcheck_any_ptr(expr)
-#endif
-
-/* evaluates to true if expr is of type FILE* */
+#endif
+
+/* evaluates to true if expr is of type FILE* */
#define curlcheck_FILE(expr) \
(curlcheck_NULL(expr) || \
(__builtin_types_compatible_p(__typeof__(expr), FILE *)))
-
-/* evaluates to true if expr can be passed as POST data (void* or char*) */
+
+/* evaluates to true if expr can be passed as POST data (void* or char*) */
#define curlcheck_postfields(expr) \
(curlcheck_ptr((expr), void) || \
curlcheck_arr((expr), char) || \
curlcheck_arr((expr), unsigned char))
-
-/* helper: __builtin_types_compatible_p distinguishes between functions and
- * function pointers, hide it */
+
+/* helper: __builtin_types_compatible_p distinguishes between functions and
+ * function pointers, hide it */
#define curlcheck_cb_compatible(func, type) \
(__builtin_types_compatible_p(__typeof__(func), type) || \
__builtin_types_compatible_p(__typeof__(func) *, type))
-
+
/* evaluates to true if expr is of type curl_resolver_start_callback */
#define curlcheck_resolver_start_callback(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_resolver_start_callback))
-/* evaluates to true if expr is of type curl_read_callback or "similar" */
+/* evaluates to true if expr is of type curl_read_callback or "similar" */
#define curlcheck_read_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), __typeof__(fread) *) || \
@@ -542,8 +542,8 @@ typedef size_t (*_curl_read_callback3)(char *, size_t, size_t, FILE *);
typedef size_t (*_curl_read_callback4)(void *, size_t, size_t, void *);
typedef size_t (*_curl_read_callback5)(void *, size_t, size_t, const void *);
typedef size_t (*_curl_read_callback6)(void *, size_t, size_t, FILE *);
-
-/* evaluates to true if expr is of type curl_write_callback or "similar" */
+
+/* evaluates to true if expr is of type curl_write_callback or "similar" */
#define curlcheck_write_cb(expr) \
(curlcheck_read_cb(expr) || \
curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \
@@ -562,8 +562,8 @@ typedef size_t (*_curl_write_callback4)(const void *, size_t, size_t, void *);
typedef size_t (*_curl_write_callback5)(const void *, size_t, size_t,
const void *);
typedef size_t (*_curl_write_callback6)(const void *, size_t, size_t, FILE *);
-
-/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */
+
+/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */
#define curlcheck_ioctl_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_ioctl_callback) || \
@@ -575,8 +575,8 @@ typedef curlioerr (*_curl_ioctl_callback1)(CURL *, int, void *);
typedef curlioerr (*_curl_ioctl_callback2)(CURL *, int, const void *);
typedef curlioerr (*_curl_ioctl_callback3)(CURL *, curliocmd, void *);
typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *);
-
-/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */
+
+/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */
#define curlcheck_sockopt_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_sockopt_callback) || \
@@ -584,10 +584,10 @@ typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *);
curlcheck_cb_compatible((expr), _curl_sockopt_callback2))
typedef int (*_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype);
typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t,
- curlsocktype);
-
-/* evaluates to true if expr is of type curl_opensocket_callback or
- "similar" */
+ curlsocktype);
+
+/* evaluates to true if expr is of type curl_opensocket_callback or
+ "similar" */
#define curlcheck_opensocket_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_opensocket_callback) || \
@@ -596,26 +596,26 @@ typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t,
curlcheck_cb_compatible((expr), _curl_opensocket_callback3) || \
curlcheck_cb_compatible((expr), _curl_opensocket_callback4))
typedef curl_socket_t (*_curl_opensocket_callback1)
- (void *, curlsocktype, struct curl_sockaddr *);
+ (void *, curlsocktype, struct curl_sockaddr *);
typedef curl_socket_t (*_curl_opensocket_callback2)
- (void *, curlsocktype, const struct curl_sockaddr *);
+ (void *, curlsocktype, const struct curl_sockaddr *);
typedef curl_socket_t (*_curl_opensocket_callback3)
- (const void *, curlsocktype, struct curl_sockaddr *);
+ (const void *, curlsocktype, struct curl_sockaddr *);
typedef curl_socket_t (*_curl_opensocket_callback4)
- (const void *, curlsocktype, const struct curl_sockaddr *);
-
-/* evaluates to true if expr is of type curl_progress_callback or "similar" */
+ (const void *, curlsocktype, const struct curl_sockaddr *);
+
+/* evaluates to true if expr is of type curl_progress_callback or "similar" */
#define curlcheck_progress_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_progress_callback) || \
curlcheck_cb_compatible((expr), _curl_progress_callback1) || \
curlcheck_cb_compatible((expr), _curl_progress_callback2))
typedef int (*_curl_progress_callback1)(void *,
- double, double, double, double);
+ double, double, double, double);
typedef int (*_curl_progress_callback2)(const void *,
- double, double, double, double);
-
-/* evaluates to true if expr is of type curl_debug_callback or "similar" */
+ double, double, double, double);
+
+/* evaluates to true if expr is of type curl_debug_callback or "similar" */
#define curlcheck_debug_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_debug_callback) || \
@@ -628,24 +628,24 @@ typedef int (*_curl_progress_callback2)(const void *,
curlcheck_cb_compatible((expr), _curl_debug_callback7) || \
curlcheck_cb_compatible((expr), _curl_debug_callback8))
typedef int (*_curl_debug_callback1) (CURL *,
- curl_infotype, char *, size_t, void *);
+ curl_infotype, char *, size_t, void *);
typedef int (*_curl_debug_callback2) (CURL *,
- curl_infotype, char *, size_t, const void *);
+ curl_infotype, char *, size_t, const void *);
typedef int (*_curl_debug_callback3) (CURL *,
- curl_infotype, const char *, size_t, void *);
+ curl_infotype, const char *, size_t, void *);
typedef int (*_curl_debug_callback4) (CURL *,
- curl_infotype, const char *, size_t, const void *);
+ curl_infotype, const char *, size_t, const void *);
typedef int (*_curl_debug_callback5) (CURL *,
- curl_infotype, unsigned char *, size_t, void *);
+ curl_infotype, unsigned char *, size_t, void *);
typedef int (*_curl_debug_callback6) (CURL *,
- curl_infotype, unsigned char *, size_t, const void *);
+ curl_infotype, unsigned char *, size_t, const void *);
typedef int (*_curl_debug_callback7) (CURL *,
- curl_infotype, const unsigned char *, size_t, void *);
+ curl_infotype, const unsigned char *, size_t, void *);
typedef int (*_curl_debug_callback8) (CURL *,
- curl_infotype, const unsigned char *, size_t, const void *);
-
-/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */
-/* this is getting even messier... */
+ curl_infotype, const unsigned char *, size_t, const void *);
+
+/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */
+/* this is getting even messier... */
#define curlcheck_ssl_ctx_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \
@@ -662,23 +662,23 @@ typedef CURLcode (*_curl_ssl_ctx_callback2)(CURL *, void *, const void *);
typedef CURLcode (*_curl_ssl_ctx_callback3)(CURL *, const void *, void *);
typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *,
const void *);
-#ifdef HEADER_SSL_H
-/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX
- * this will of course break if we're included before OpenSSL headers...
- */
+#ifdef HEADER_SSL_H
+/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX
+ * this will of course break if we're included before OpenSSL headers...
+ */
typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX, void *);
typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX, const void *);
typedef CURLcode (*_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX, void *);
typedef CURLcode (*_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX,
- const void *);
-#else
-typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5;
-typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6;
-typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7;
-typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8;
-#endif
-
-/* evaluates to true if expr is of type curl_conv_callback or "similar" */
+ const void *);
+#else
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8;
+#endif
+
+/* evaluates to true if expr is of type curl_conv_callback or "similar" */
#define curlcheck_conv_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_conv_callback) || \
@@ -686,19 +686,19 @@ typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8;
curlcheck_cb_compatible((expr), _curl_conv_callback2) || \
curlcheck_cb_compatible((expr), _curl_conv_callback3) || \
curlcheck_cb_compatible((expr), _curl_conv_callback4))
-typedef CURLcode (*_curl_conv_callback1)(char *, size_t length);
-typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length);
-typedef CURLcode (*_curl_conv_callback3)(void *, size_t length);
-typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length);
-
-/* evaluates to true if expr is of type curl_seek_callback or "similar" */
+typedef CURLcode (*_curl_conv_callback1)(char *, size_t length);
+typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length);
+typedef CURLcode (*_curl_conv_callback3)(void *, size_t length);
+typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length);
+
+/* evaluates to true if expr is of type curl_seek_callback or "similar" */
#define curlcheck_seek_cb(expr) \
(curlcheck_NULL(expr) || \
curlcheck_cb_compatible((expr), curl_seek_callback) || \
curlcheck_cb_compatible((expr), _curl_seek_callback1) || \
curlcheck_cb_compatible((expr), _curl_seek_callback2))
-typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int);
-typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int);
-
-
+typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int);
+typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int);
+
+
#endif /* CURLINC_TYPECHECK_GCC_H */
diff --git a/contrib/libs/curl/lib/amigaos.c b/contrib/libs/curl/lib/amigaos.c
index b584e0ba8b..d3b00d9083 100644
--- a/contrib/libs/curl/lib/amigaos.c
+++ b/contrib/libs/curl/lib/amigaos.c
@@ -1,27 +1,27 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#ifdef __AMIGA__
# include "amigaos.h"
# if defined(HAVE_PROTO_BSDSOCKET_H) && !defined(USE_AMISSL)
@@ -31,58 +31,58 @@
# include <stabs.h>
# endif
#endif
-
+
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
-
+
#ifdef __AMIGA__
#if defined(HAVE_PROTO_BSDSOCKET_H) && !defined(USE_AMISSL)
-struct Library *SocketBase = NULL;
-extern int errno, h_errno;
-
-#ifdef __libnix__
-void __request(const char *msg);
-#else
+struct Library *SocketBase = NULL;
+extern int errno, h_errno;
+
+#ifdef __libnix__
+void __request(const char *msg);
+#else
# define __request(msg) Printf(msg "\n\a")
-#endif
-
-void Curl_amiga_cleanup()
-{
- if(SocketBase) {
- CloseLibrary(SocketBase);
- SocketBase = NULL;
- }
-}
-
-bool Curl_amiga_init()
-{
- if(!SocketBase)
- SocketBase = OpenLibrary("bsdsocket.library", 4);
-
- if(!SocketBase) {
- __request("No TCP/IP Stack running!");
- return FALSE;
- }
-
- if(SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (ULONG) &errno,
+#endif
+
+void Curl_amiga_cleanup()
+{
+ if(SocketBase) {
+ CloseLibrary(SocketBase);
+ SocketBase = NULL;
+ }
+}
+
+bool Curl_amiga_init()
+{
+ if(!SocketBase)
+ SocketBase = OpenLibrary("bsdsocket.library", 4);
+
+ if(!SocketBase) {
+ __request("No TCP/IP Stack running!");
+ return FALSE;
+ }
+
+ if(SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (ULONG) &errno,
SBTM_SETVAL(SBTC_LOGTAGPTR), (ULONG) "curl",
- TAG_DONE)) {
- __request("SocketBaseTags ERROR");
- return FALSE;
- }
-
-#ifndef __libnix__
- atexit(Curl_amiga_cleanup);
-#endif
-
- return TRUE;
-}
-
-#ifdef __libnix__
+ TAG_DONE)) {
+ __request("SocketBaseTags ERROR");
+ return FALSE;
+ }
+
+#ifndef __libnix__
+ atexit(Curl_amiga_cleanup);
+#endif
+
+ return TRUE;
+}
+
+#ifdef __libnix__
ADD2EXIT(Curl_amiga_cleanup, -50);
-#endif
-
+#endif
+
#endif /* HAVE_PROTO_BSDSOCKET_H */
#ifdef USE_AMISSL
diff --git a/contrib/libs/curl/lib/amigaos.h b/contrib/libs/curl/lib/amigaos.h
index c2e14c2f68..02e5bb546a 100644
--- a/contrib/libs/curl/lib/amigaos.h
+++ b/contrib/libs/curl/lib/amigaos.h
@@ -1,44 +1,44 @@
-#ifndef HEADER_CURL_AMIGAOS_H
-#define HEADER_CURL_AMIGAOS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_AMIGAOS_H
+#define HEADER_CURL_AMIGAOS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
#if defined(__AMIGA__) && defined(HAVE_BSDSOCKET_H) && !defined(USE_AMISSL)
-
-bool Curl_amiga_init();
-void Curl_amiga_cleanup();
-
-#else
-
-#define Curl_amiga_init() 1
-#define Curl_amiga_cleanup() Curl_nop_stmt
-
-#endif
-
+
+bool Curl_amiga_init();
+void Curl_amiga_cleanup();
+
+#else
+
+#define Curl_amiga_init() 1
+#define Curl_amiga_cleanup() Curl_nop_stmt
+
+#endif
+
#ifdef USE_AMISSL
#include <openssl/x509v3.h>
void Curl_amiga_X509_free(X509 *a);
#endif /* USE_AMISSL */
-#endif /* HEADER_CURL_AMIGAOS_H */
+#endif /* HEADER_CURL_AMIGAOS_H */
diff --git a/contrib/libs/curl/lib/arpa_telnet.h b/contrib/libs/curl/lib/arpa_telnet.h
index ac1426e049..cbe31de5a3 100644
--- a/contrib/libs/curl/lib/arpa_telnet.h
+++ b/contrib/libs/curl/lib/arpa_telnet.h
@@ -1,108 +1,108 @@
-#ifndef HEADER_CURL_ARPA_TELNET_H
-#define HEADER_CURL_ARPA_TELNET_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_ARPA_TELNET_H
+#define HEADER_CURL_ARPA_TELNET_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifndef CURL_DISABLE_TELNET
-/*
- * Telnet option defines. Add more here if in need.
- */
-#define CURL_TELOPT_BINARY 0 /* binary 8bit data */
-#define CURL_TELOPT_ECHO 1 /* just echo! */
-#define CURL_TELOPT_SGA 3 /* Suppress Go Ahead */
-#define CURL_TELOPT_EXOPL 255 /* EXtended OPtions List */
-#define CURL_TELOPT_TTYPE 24 /* Terminal TYPE */
-#define CURL_TELOPT_NAWS 31 /* Negotiate About Window Size */
-#define CURL_TELOPT_XDISPLOC 35 /* X DISPlay LOCation */
-
-#define CURL_TELOPT_NEW_ENVIRON 39 /* NEW ENVIRONment variables */
-#define CURL_NEW_ENV_VAR 0
-#define CURL_NEW_ENV_VALUE 1
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifndef CURL_DISABLE_TELNET
+/*
+ * Telnet option defines. Add more here if in need.
+ */
+#define CURL_TELOPT_BINARY 0 /* binary 8bit data */
+#define CURL_TELOPT_ECHO 1 /* just echo! */
+#define CURL_TELOPT_SGA 3 /* Suppress Go Ahead */
+#define CURL_TELOPT_EXOPL 255 /* EXtended OPtions List */
+#define CURL_TELOPT_TTYPE 24 /* Terminal TYPE */
+#define CURL_TELOPT_NAWS 31 /* Negotiate About Window Size */
+#define CURL_TELOPT_XDISPLOC 35 /* X DISPlay LOCation */
+
+#define CURL_TELOPT_NEW_ENVIRON 39 /* NEW ENVIRONment variables */
+#define CURL_NEW_ENV_VAR 0
+#define CURL_NEW_ENV_VALUE 1
+
#ifndef CURL_DISABLE_VERBOSE_STRINGS
-/*
- * The telnet options represented as strings
- */
-static const char * const telnetoptions[]=
-{
- "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD",
- "NAME", "STATUS", "TIMING MARK", "RCTE",
- "NAOL", "NAOP", "NAOCRD", "NAOHTS",
- "NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD",
- "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
- "DE TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION",
- "TERM TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING",
- "TTYLOC", "3270 REGIME", "X3 PAD", "NAWS",
- "TERM SPEED", "LFLOW", "LINEMODE", "XDISPLOC",
- "OLD-ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON"
-};
+/*
+ * The telnet options represented as strings
+ */
+static const char * const telnetoptions[]=
+{
+ "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD",
+ "NAME", "STATUS", "TIMING MARK", "RCTE",
+ "NAOL", "NAOP", "NAOCRD", "NAOHTS",
+ "NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD",
+ "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
+ "DE TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION",
+ "TERM TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING",
+ "TTYLOC", "3270 REGIME", "X3 PAD", "NAWS",
+ "TERM SPEED", "LFLOW", "LINEMODE", "XDISPLOC",
+ "OLD-ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON"
+};
#endif
-
-#define CURL_TELOPT_MAXIMUM CURL_TELOPT_NEW_ENVIRON
-
-#define CURL_TELOPT_OK(x) ((x) <= CURL_TELOPT_MAXIMUM)
-#define CURL_TELOPT(x) telnetoptions[x]
-
-#define CURL_NTELOPTS 40
-
-/*
- * First some defines
- */
-#define CURL_xEOF 236 /* End Of File */
-#define CURL_SE 240 /* Sub negotiation End */
-#define CURL_NOP 241 /* No OPeration */
-#define CURL_DM 242 /* Data Mark */
-#define CURL_GA 249 /* Go Ahead, reverse the line */
-#define CURL_SB 250 /* SuBnegotiation */
-#define CURL_WILL 251 /* Our side WILL use this option */
-#define CURL_WONT 252 /* Our side WON'T use this option */
-#define CURL_DO 253 /* DO use this option! */
-#define CURL_DONT 254 /* DON'T use this option! */
-#define CURL_IAC 255 /* Interpret As Command */
-
+
+#define CURL_TELOPT_MAXIMUM CURL_TELOPT_NEW_ENVIRON
+
+#define CURL_TELOPT_OK(x) ((x) <= CURL_TELOPT_MAXIMUM)
+#define CURL_TELOPT(x) telnetoptions[x]
+
+#define CURL_NTELOPTS 40
+
+/*
+ * First some defines
+ */
+#define CURL_xEOF 236 /* End Of File */
+#define CURL_SE 240 /* Sub negotiation End */
+#define CURL_NOP 241 /* No OPeration */
+#define CURL_DM 242 /* Data Mark */
+#define CURL_GA 249 /* Go Ahead, reverse the line */
+#define CURL_SB 250 /* SuBnegotiation */
+#define CURL_WILL 251 /* Our side WILL use this option */
+#define CURL_WONT 252 /* Our side WON'T use this option */
+#define CURL_DO 253 /* DO use this option! */
+#define CURL_DONT 254 /* DON'T use this option! */
+#define CURL_IAC 255 /* Interpret As Command */
+
#ifndef CURL_DISABLE_VERBOSE_STRINGS
-/*
- * Then those numbers represented as strings:
- */
-static const char * const telnetcmds[]=
-{
- "EOF", "SUSP", "ABORT", "EOR", "SE",
- "NOP", "DMARK", "BRK", "IP", "AO",
- "AYT", "EC", "EL", "GA", "SB",
- "WILL", "WONT", "DO", "DONT", "IAC"
-};
+/*
+ * Then those numbers represented as strings:
+ */
+static const char * const telnetcmds[]=
+{
+ "EOF", "SUSP", "ABORT", "EOR", "SE",
+ "NOP", "DMARK", "BRK", "IP", "AO",
+ "AYT", "EC", "EL", "GA", "SB",
+ "WILL", "WONT", "DO", "DONT", "IAC"
+};
#endif
-
-#define CURL_TELCMD_MINIMUM CURL_xEOF /* the first one */
-#define CURL_TELCMD_MAXIMUM CURL_IAC /* surprise, 255 is the last one! ;-) */
-
-#define CURL_TELQUAL_IS 0
-#define CURL_TELQUAL_SEND 1
-#define CURL_TELQUAL_INFO 2
-#define CURL_TELQUAL_NAME 3
-
-#define CURL_TELCMD_OK(x) ( ((unsigned int)(x) >= CURL_TELCMD_MINIMUM) && \
- ((unsigned int)(x) <= CURL_TELCMD_MAXIMUM) )
-#define CURL_TELCMD(x) telnetcmds[(x)-CURL_TELCMD_MINIMUM]
-
-#endif /* CURL_DISABLE_TELNET */
-
-#endif /* HEADER_CURL_ARPA_TELNET_H */
+
+#define CURL_TELCMD_MINIMUM CURL_xEOF /* the first one */
+#define CURL_TELCMD_MAXIMUM CURL_IAC /* surprise, 255 is the last one! ;-) */
+
+#define CURL_TELQUAL_IS 0
+#define CURL_TELQUAL_SEND 1
+#define CURL_TELQUAL_INFO 2
+#define CURL_TELQUAL_NAME 3
+
+#define CURL_TELCMD_OK(x) ( ((unsigned int)(x) >= CURL_TELCMD_MINIMUM) && \
+ ((unsigned int)(x) <= CURL_TELCMD_MAXIMUM) )
+#define CURL_TELCMD(x) telnetcmds[(x)-CURL_TELCMD_MINIMUM]
+
+#endif /* CURL_DISABLE_TELNET */
+
+#endif /* HEADER_CURL_ARPA_TELNET_H */
diff --git a/contrib/libs/curl/lib/asyn-ares.c b/contrib/libs/curl/lib/asyn-ares.c
index 8cf5aa9c0f..1747571889 100644
--- a/contrib/libs/curl/lib/asyn-ares.c
+++ b/contrib/libs/curl/lib/asyn-ares.c
@@ -1,98 +1,98 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
/***********************************************************************
* Only for ares-enabled builds
* And only for functions that fulfill the asynch resolver backend API
* as defined in asyn.h, nothing else belongs in this file!
**********************************************************************/
-
+
#ifdef CURLRES_ARES
-#include <limits.h>
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-
-#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
-#include "multiif.h"
-#include "inet_pton.h"
-#include "connect.h"
-#include "select.h"
-#include "progress.h"
-
+#include <limits.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#ifdef HAVE_PROCESS_H
+#include <process.h>
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
+#include "multiif.h"
+#include "inet_pton.h"
+#include "connect.h"
+#include "select.h"
+#include "progress.h"
+
# if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \
defined(WIN32)
-# define CARES_STATICLIB
-# endif
-# include <ares.h>
-# include <ares_version.h> /* really old c-ares didn't include this by
- itself */
-
-#if ARES_VERSION >= 0x010500
-/* c-ares 1.5.0 or later, the callback proto is modified */
-#define HAVE_CARES_CALLBACK_TIMEOUTS 1
-#endif
-
+# define CARES_STATICLIB
+# endif
+# include <ares.h>
+# include <ares_version.h> /* really old c-ares didn't include this by
+ itself */
+
+#if ARES_VERSION >= 0x010500
+/* c-ares 1.5.0 or later, the callback proto is modified */
+#define HAVE_CARES_CALLBACK_TIMEOUTS 1
+#endif
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
struct thread_data {
- int num_pending; /* number of ares_gethostbyname() requests */
+ int num_pending; /* number of ares_gethostbyname() requests */
struct Curl_addrinfo *temp_ai; /* intermediary result while fetching c-ares
parts */
- int last_status;
+ int last_status;
struct curltime happy_eyeballs_dns_time; /* when this timer started, or 0 */
-};
-
+};
+
/* How long we are willing to wait for additional parallel responses after
obtaining a "definitive" one.
@@ -104,34 +104,34 @@ struct thread_data {
*/
#define HAPPY_EYEBALLS_DNS_TIMEOUT 5000
-/*
- * Curl_resolver_global_init() - the generic low-level asynchronous name
- * resolve API. Called from curl_global_init() to initialize global resolver
- * environment. Initializes ares library.
- */
-int Curl_resolver_global_init(void)
-{
-#ifdef CARES_HAVE_ARES_LIBRARY_INIT
- if(ares_library_init(ARES_LIB_INIT_ALL)) {
- return CURLE_FAILED_INIT;
- }
-#endif
- return CURLE_OK;
-}
-
-/*
- * Curl_resolver_global_cleanup()
- *
- * Called from curl_global_cleanup() to destroy global resolver environment.
- * Deinitializes ares library.
- */
-void Curl_resolver_global_cleanup(void)
-{
-#ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP
- ares_library_cleanup();
-#endif
-}
-
+/*
+ * Curl_resolver_global_init() - the generic low-level asynchronous name
+ * resolve API. Called from curl_global_init() to initialize global resolver
+ * environment. Initializes ares library.
+ */
+int Curl_resolver_global_init(void)
+{
+#ifdef CARES_HAVE_ARES_LIBRARY_INIT
+ if(ares_library_init(ARES_LIB_INIT_ALL)) {
+ return CURLE_FAILED_INIT;
+ }
+#endif
+ return CURLE_OK;
+}
+
+/*
+ * Curl_resolver_global_cleanup()
+ *
+ * Called from curl_global_cleanup() to destroy global resolver environment.
+ * Deinitializes ares library.
+ */
+void Curl_resolver_global_cleanup(void)
+{
+#ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP
+ ares_library_cleanup();
+#endif
+}
+
static void Curl_ares_sock_state_cb(void *data, ares_socket_t socket_fd,
int readable, int writable)
@@ -143,53 +143,53 @@ static void Curl_ares_sock_state_cb(void *data, ares_socket_t socket_fd,
}
}
-/*
- * Curl_resolver_init()
- *
- * Called from curl_easy_init() -> Curl_open() to initialize resolver
- * URL-state specific environment ('resolver' member of the UrlState
- * structure). Fills the passed pointer by the initialized ares_channel.
- */
+/*
+ * Curl_resolver_init()
+ *
+ * Called from curl_easy_init() -> Curl_open() to initialize resolver
+ * URL-state specific environment ('resolver' member of the UrlState
+ * structure). Fills the passed pointer by the initialized ares_channel.
+ */
CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver)
-{
+{
int status;
struct ares_options options;
int optmask = ARES_OPT_SOCK_STATE_CB;
options.sock_state_cb = Curl_ares_sock_state_cb;
options.sock_state_cb_data = easy;
status = ares_init_options((ares_channel*)resolver, &options, optmask);
- if(status != ARES_SUCCESS) {
- if(status == ARES_ENOMEM)
- return CURLE_OUT_OF_MEMORY;
- else
- return CURLE_FAILED_INIT;
- }
- return CURLE_OK;
- /* make sure that all other returns from this function should destroy the
- ares channel before returning error! */
-}
-
-/*
- * Curl_resolver_cleanup()
- *
- * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
- * URL-state specific environment ('resolver' member of the UrlState
- * structure). Destroys the ares channel.
- */
-void Curl_resolver_cleanup(void *resolver)
-{
- ares_destroy((ares_channel)resolver);
-}
-
-/*
- * Curl_resolver_duphandle()
- *
- * Called from curl_easy_duphandle() to duplicate resolver URL-state specific
- * environment ('resolver' member of the UrlState structure). Duplicates the
- * 'from' ares channel and passes the resulting channel to the 'to' pointer.
- */
+ if(status != ARES_SUCCESS) {
+ if(status == ARES_ENOMEM)
+ return CURLE_OUT_OF_MEMORY;
+ else
+ return CURLE_FAILED_INIT;
+ }
+ return CURLE_OK;
+ /* make sure that all other returns from this function should destroy the
+ ares channel before returning error! */
+}
+
+/*
+ * Curl_resolver_cleanup()
+ *
+ * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
+ * URL-state specific environment ('resolver' member of the UrlState
+ * structure). Destroys the ares channel.
+ */
+void Curl_resolver_cleanup(void *resolver)
+{
+ ares_destroy((ares_channel)resolver);
+}
+
+/*
+ * Curl_resolver_duphandle()
+ *
+ * Called from curl_easy_duphandle() to duplicate resolver URL-state specific
+ * environment ('resolver' member of the UrlState structure). Duplicates the
+ * 'from' ares channel and passes the resulting channel to the 'to' pointer.
+ */
CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from)
-{
+{
(void)from;
/*
* it would be better to call ares_dup instead, but right now
@@ -197,21 +197,21 @@ CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from)
* ares_init_options
*/
return Curl_resolver_init(easy, to);
-}
-
+}
+
static void destroy_async_data(struct Curl_async *async);
-
-/*
- * Cancel all possibly still on-going resolves for this connection.
- */
-void Curl_resolver_cancel(struct connectdata *conn)
-{
+
+/*
+ * Cancel all possibly still on-going resolves for this connection.
+ */
+void Curl_resolver_cancel(struct connectdata *conn)
+{
if(conn->data && conn->data->state.resolver)
- ares_cancel((ares_channel)conn->data->state.resolver);
- destroy_async_data(&conn->async);
-}
-
-/*
+ ares_cancel((ares_channel)conn->data->state.resolver);
+ destroy_async_data(&conn->async);
+}
+
+/*
* We're equivalent to Curl_resolver_cancel() for the c-ares resolver. We
* never block.
*/
@@ -223,140 +223,140 @@ void Curl_resolver_kill(struct connectdata *conn)
}
/*
- * destroy_async_data() cleans up async resolver data.
- */
+ * destroy_async_data() cleans up async resolver data.
+ */
static void destroy_async_data(struct Curl_async *async)
-{
+{
free(async->hostname);
-
+
if(async->tdata) {
struct thread_data *res = async->tdata;
- if(res) {
- if(res->temp_ai) {
- Curl_freeaddrinfo(res->temp_ai);
- res->temp_ai = NULL;
- }
- free(res);
- }
+ if(res) {
+ if(res->temp_ai) {
+ Curl_freeaddrinfo(res->temp_ai);
+ res->temp_ai = NULL;
+ }
+ free(res);
+ }
async->tdata = NULL;
- }
-
- async->hostname = NULL;
-}
-
-/*
- * Curl_resolver_getsock() is called when someone from the outside world
- * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking
- * with ares. The caller must make sure that this function is only called when
- * we have a working ares channel.
- *
- * Returns: sockets-in-use-bitmap
- */
-
-int Curl_resolver_getsock(struct connectdata *conn,
+ }
+
+ async->hostname = NULL;
+}
+
+/*
+ * Curl_resolver_getsock() is called when someone from the outside world
+ * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking
+ * with ares. The caller must make sure that this function is only called when
+ * we have a working ares channel.
+ *
+ * Returns: sockets-in-use-bitmap
+ */
+
+int Curl_resolver_getsock(struct connectdata *conn,
curl_socket_t *socks)
-{
- struct timeval maxtime;
- struct timeval timebuf;
- struct timeval *timeout;
- long milli;
- int max = ares_getsock((ares_channel)conn->data->state.resolver,
+{
+ struct timeval maxtime;
+ struct timeval timebuf;
+ struct timeval *timeout;
+ long milli;
+ int max = ares_getsock((ares_channel)conn->data->state.resolver,
(ares_socket_t *)socks, MAX_SOCKSPEREASYHANDLE);
-
- maxtime.tv_sec = CURL_TIMEOUT_RESOLVE;
- maxtime.tv_usec = 0;
-
- timeout = ares_timeout((ares_channel)conn->data->state.resolver, &maxtime,
- &timebuf);
- milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000);
- if(milli == 0)
- milli += 10;
+
+ maxtime.tv_sec = CURL_TIMEOUT_RESOLVE;
+ maxtime.tv_usec = 0;
+
+ timeout = ares_timeout((ares_channel)conn->data->state.resolver, &maxtime,
+ &timebuf);
+ milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000);
+ if(milli == 0)
+ milli += 10;
Curl_expire(conn->data, milli, EXPIRE_ASYNC_NAME);
-
- return max;
-}
-
-/*
- * waitperform()
- *
- * 1) Ask ares what sockets it currently plays with, then
- * 2) wait for the timeout period to check for action on ares' sockets.
- * 3) tell ares to act on all the sockets marked as "with action"
- *
- * return number of sockets it worked on
- */
-
+
+ return max;
+}
+
+/*
+ * waitperform()
+ *
+ * 1) Ask ares what sockets it currently plays with, then
+ * 2) wait for the timeout period to check for action on ares' sockets.
+ * 3) tell ares to act on all the sockets marked as "with action"
+ *
+ * return number of sockets it worked on
+ */
+
static int waitperform(struct connectdata *conn, timediff_t timeout_ms)
-{
+{
struct Curl_easy *data = conn->data;
- int nfds;
- int bitmask;
- ares_socket_t socks[ARES_GETSOCK_MAXNUM];
- struct pollfd pfd[ARES_GETSOCK_MAXNUM];
- int i;
- int num = 0;
-
- bitmask = ares_getsock((ares_channel)data->state.resolver, socks,
- ARES_GETSOCK_MAXNUM);
-
+ int nfds;
+ int bitmask;
+ ares_socket_t socks[ARES_GETSOCK_MAXNUM];
+ struct pollfd pfd[ARES_GETSOCK_MAXNUM];
+ int i;
+ int num = 0;
+
+ bitmask = ares_getsock((ares_channel)data->state.resolver, socks,
+ ARES_GETSOCK_MAXNUM);
+
for(i = 0; i < ARES_GETSOCK_MAXNUM; i++) {
- pfd[i].events = 0;
- pfd[i].revents = 0;
- if(ARES_GETSOCK_READABLE(bitmask, i)) {
- pfd[i].fd = socks[i];
- pfd[i].events |= POLLRDNORM|POLLIN;
- }
- if(ARES_GETSOCK_WRITABLE(bitmask, i)) {
- pfd[i].fd = socks[i];
- pfd[i].events |= POLLWRNORM|POLLOUT;
- }
- if(pfd[i].events != 0)
- num++;
- else
- break;
- }
-
- if(num)
- nfds = Curl_poll(pfd, num, timeout_ms);
- else
- nfds = 0;
-
- if(!nfds)
- /* Call ares_process() unconditonally here, even if we simply timed out
- above, as otherwise the ares name resolve won't timeout! */
- ares_process_fd((ares_channel)data->state.resolver, ARES_SOCKET_BAD,
- ARES_SOCKET_BAD);
- else {
- /* move through the descriptors and ask for processing on them */
+ pfd[i].events = 0;
+ pfd[i].revents = 0;
+ if(ARES_GETSOCK_READABLE(bitmask, i)) {
+ pfd[i].fd = socks[i];
+ pfd[i].events |= POLLRDNORM|POLLIN;
+ }
+ if(ARES_GETSOCK_WRITABLE(bitmask, i)) {
+ pfd[i].fd = socks[i];
+ pfd[i].events |= POLLWRNORM|POLLOUT;
+ }
+ if(pfd[i].events != 0)
+ num++;
+ else
+ break;
+ }
+
+ if(num)
+ nfds = Curl_poll(pfd, num, timeout_ms);
+ else
+ nfds = 0;
+
+ if(!nfds)
+ /* Call ares_process() unconditonally here, even if we simply timed out
+ above, as otherwise the ares name resolve won't timeout! */
+ ares_process_fd((ares_channel)data->state.resolver, ARES_SOCKET_BAD,
+ ARES_SOCKET_BAD);
+ else {
+ /* move through the descriptors and ask for processing on them */
for(i = 0; i < num; i++)
- ares_process_fd((ares_channel)data->state.resolver,
+ ares_process_fd((ares_channel)data->state.resolver,
(pfd[i].revents & (POLLRDNORM|POLLIN))?
- pfd[i].fd:ARES_SOCKET_BAD,
+ pfd[i].fd:ARES_SOCKET_BAD,
(pfd[i].revents & (POLLWRNORM|POLLOUT))?
- pfd[i].fd:ARES_SOCKET_BAD);
- }
- return nfds;
-}
-
-/*
- * Curl_resolver_is_resolved() is called repeatedly to check if a previous
- * name resolve request has completed. It should also make sure to time-out if
- * the operation seems to take too long.
- *
- * Returns normal CURLcode errors.
- */
-CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
- struct Curl_dns_entry **dns)
-{
+ pfd[i].fd:ARES_SOCKET_BAD);
+ }
+ return nfds;
+}
+
+/*
+ * Curl_resolver_is_resolved() is called repeatedly to check if a previous
+ * name resolve request has completed. It should also make sure to time-out if
+ * the operation seems to take too long.
+ *
+ * Returns normal CURLcode errors.
+ */
+CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
+ struct Curl_dns_entry **dns)
+{
struct Curl_easy *data = conn->data;
struct thread_data *res = conn->async.tdata;
CURLcode result = CURLE_OK;
-
+
DEBUGASSERT(dns);
*dns = NULL;
-
- waitperform(conn, 0);
-
+
+ waitperform(conn, 0);
+
/* Now that we've checked for any last minute results above, see if there are
any responses still pending when the EXPIRE_HAPPY_EYEBALLS_DNS timer
expires. */
@@ -380,92 +380,92 @@ CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
DEBUGASSERT(res->num_pending == 0);
}
- if(res && !res->num_pending) {
+ if(res && !res->num_pending) {
(void)Curl_addrinfo_callback(conn, res->last_status, res->temp_ai);
/* temp_ai ownership is moved to the connection, so we need not free-up
them */
res->temp_ai = NULL;
- if(!conn->async.dns) {
- failf(data, "Could not resolve: %s (%s)",
- conn->async.hostname, ares_strerror(conn->async.status));
+ if(!conn->async.dns) {
+ failf(data, "Could not resolve: %s (%s)",
+ conn->async.hostname, ares_strerror(conn->async.status));
result = conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY:
- CURLE_COULDNT_RESOLVE_HOST;
- }
+ CURLE_COULDNT_RESOLVE_HOST;
+ }
else
- *dns = conn->async.dns;
-
- destroy_async_data(&conn->async);
- }
-
+ *dns = conn->async.dns;
+
+ destroy_async_data(&conn->async);
+ }
+
return result;
-}
-
-/*
- * Curl_resolver_wait_resolv()
- *
+}
+
+/*
+ * Curl_resolver_wait_resolv()
+ *
* Waits for a resolve to finish. This function should be avoided since using
- * this risk getting the multi interface to "hang".
- *
+ * this risk getting the multi interface to "hang".
+ *
* 'entry' MUST be non-NULL.
- *
+ *
* Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved,
* CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors.
- */
-CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
- struct Curl_dns_entry **entry)
-{
+ */
+CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
+ struct Curl_dns_entry **entry)
+{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
timediff_t timeout;
struct curltime now = Curl_now();
-
+
DEBUGASSERT(entry);
*entry = NULL; /* clear on entry */
- timeout = Curl_timeleft(data, &now, TRUE);
+ timeout = Curl_timeleft(data, &now, TRUE);
if(timeout < 0) {
/* already expired! */
connclose(conn, "Timed out before name resolve started");
return CURLE_OPERATION_TIMEDOUT;
}
- if(!timeout)
- timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */
-
- /* Wait for the name resolve query to complete. */
+ if(!timeout)
+ timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */
+
+ /* Wait for the name resolve query to complete. */
while(!result) {
- struct timeval *tvp, tv, store;
- int itimeout;
+ struct timeval *tvp, tv, store;
+ int itimeout;
timediff_t timeout_ms;
-
+
#if TIMEDIFF_T_MAX > INT_MAX
itimeout = (timeout > INT_MAX) ? INT_MAX : (int)timeout;
#else
itimeout = (int)timeout;
#endif
-
- store.tv_sec = itimeout/1000;
- store.tv_usec = (itimeout%1000)*1000;
-
- tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv);
-
- /* use the timeout period ares returned to us above if less than one
- second is left, otherwise just use 1000ms to make sure the progress
- callback gets called frequent enough */
- if(!tvp->tv_sec)
+
+ store.tv_sec = itimeout/1000;
+ store.tv_usec = (itimeout%1000)*1000;
+
+ tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv);
+
+ /* use the timeout period ares returned to us above if less than one
+ second is left, otherwise just use 1000ms to make sure the progress
+ callback gets called frequent enough */
+ if(!tvp->tv_sec)
timeout_ms = (timediff_t)(tvp->tv_usec/1000);
- else
- timeout_ms = 1000;
-
- waitperform(conn, timeout_ms);
+ else
+ timeout_ms = 1000;
+
+ waitperform(conn, timeout_ms);
result = Curl_resolver_is_resolved(conn, entry);
-
+
if(result || conn->async.done)
- break;
-
+ break;
+
if(Curl_pgrsUpdate(conn))
result = CURLE_ABORTED_BY_CALLBACK;
- else {
+ else {
struct curltime now2 = Curl_now();
timediff_t timediff = Curl_timediff(now2, now); /* spent time */
if(timediff <= 0)
@@ -474,79 +474,79 @@ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
timeout = -1;
else
timeout -= timediff;
- now = now2; /* for next loop */
- }
+ now = now2; /* for next loop */
+ }
if(timeout < 0)
result = CURLE_OPERATION_TIMEDOUT;
- }
+ }
if(result)
/* failure, so we cancel the ares operation */
ares_cancel((ares_channel)data->state.resolver);
-
- /* Operation complete, if the lookup was successful we now have the entry
- in the cache. */
- if(entry)
- *entry = conn->async.dns;
-
+
+ /* Operation complete, if the lookup was successful we now have the entry
+ in the cache. */
+ if(entry)
+ *entry = conn->async.dns;
+
if(result)
- /* close the connection, since we can't return failure here without
+ /* close the connection, since we can't return failure here without
cleaning up this connection properly. */
connclose(conn, "c-ares resolve failed");
-
+
return result;
-}
-
-/* Connects results to the list */
+}
+
+/* Connects results to the list */
static void compound_results(struct thread_data *res,
struct Curl_addrinfo *ai)
-{
+{
struct Curl_addrinfo *ai_tail;
- if(!ai)
- return;
- ai_tail = ai;
-
- while(ai_tail->ai_next)
- ai_tail = ai_tail->ai_next;
-
- /* Add the new results to the list of old results. */
- ai_tail->ai_next = res->temp_ai;
- res->temp_ai = ai;
-}
-
-/*
- * ares_query_completed_cb() is the callback that ares will call when
- * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(),
- * when using ares, is completed either successfully or with failure.
- */
-static void query_completed_cb(void *arg, /* (struct connectdata *) */
- int status,
-#ifdef HAVE_CARES_CALLBACK_TIMEOUTS
- int timeouts,
-#endif
- struct hostent *hostent)
-{
- struct connectdata *conn = (struct connectdata *)arg;
+ if(!ai)
+ return;
+ ai_tail = ai;
+
+ while(ai_tail->ai_next)
+ ai_tail = ai_tail->ai_next;
+
+ /* Add the new results to the list of old results. */
+ ai_tail->ai_next = res->temp_ai;
+ res->temp_ai = ai;
+}
+
+/*
+ * ares_query_completed_cb() is the callback that ares will call when
+ * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(),
+ * when using ares, is completed either successfully or with failure.
+ */
+static void query_completed_cb(void *arg, /* (struct connectdata *) */
+ int status,
+#ifdef HAVE_CARES_CALLBACK_TIMEOUTS
+ int timeouts,
+#endif
+ struct hostent *hostent)
+{
+ struct connectdata *conn = (struct connectdata *)arg;
struct thread_data *res;
-
-#ifdef HAVE_CARES_CALLBACK_TIMEOUTS
- (void)timeouts; /* ignored */
-#endif
-
- if(ARES_EDESTRUCTION == status)
- /* when this ares handle is getting destroyed, the 'arg' pointer may not
- be valid so only defer it when we know the 'status' says its fine! */
- return;
-
+
+#ifdef HAVE_CARES_CALLBACK_TIMEOUTS
+ (void)timeouts; /* ignored */
+#endif
+
+ if(ARES_EDESTRUCTION == status)
+ /* when this ares handle is getting destroyed, the 'arg' pointer may not
+ be valid so only defer it when we know the 'status' says its fine! */
+ return;
+
res = conn->async.tdata;
if(res) {
res->num_pending--;
-
+
if(CURL_ASYNC_SUCCESS == status) {
struct Curl_addrinfo *ai = Curl_he2ai(hostent, conn->async.port);
if(ai) {
compound_results(res, ai);
}
- }
+ }
/* A successful result overwrites any previous error */
if(res->last_status != ARES_SUCCESS)
res->last_status = status;
@@ -610,206 +610,206 @@ static void query_completed_cb(void *arg, /* (struct connectdata *) */
Curl_expire(
conn->data, HAPPY_EYEBALLS_DNS_TIMEOUT, EXPIRE_HAPPY_EYEBALLS_DNS);
}
- }
-}
-
-/*
- * Curl_resolver_getaddrinfo() - when using ares
- *
- * Returns name information about the given hostname and port number. If
- * successful, the 'hostent' is returned and the forth argument will point to
- * memory we need to free after use. That memory *MUST* be freed with
- * Curl_freeaddrinfo(), nothing else.
- */
+ }
+}
+
+/*
+ * Curl_resolver_getaddrinfo() - when using ares
+ *
+ * Returns name information about the given hostname and port number. If
+ * successful, the 'hostent' is returned and the forth argument will point to
+ * memory we need to free after use. That memory *MUST* be freed with
+ * Curl_freeaddrinfo(), nothing else.
+ */
struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp)
-{
- char *bufp;
+{
+ char *bufp;
struct Curl_easy *data = conn->data;
- int family = PF_INET;
-
- *waitp = 0; /* default to synchronous response */
-
+ int family = PF_INET;
+
+ *waitp = 0; /* default to synchronous response */
+
#ifdef ENABLE_IPV6
- switch(conn->ip_version) {
- default:
-#if ARES_VERSION >= 0x010601
- family = PF_UNSPEC; /* supported by c-ares since 1.6.1, so for older
- c-ares versions this just falls through and defaults
- to PF_INET */
- break;
-#endif
- case CURL_IPRESOLVE_V4:
- family = PF_INET;
- break;
- case CURL_IPRESOLVE_V6:
- family = PF_INET6;
- break;
- }
+ switch(conn->ip_version) {
+ default:
+#if ARES_VERSION >= 0x010601
+ family = PF_UNSPEC; /* supported by c-ares since 1.6.1, so for older
+ c-ares versions this just falls through and defaults
+ to PF_INET */
+ break;
+#endif
+ case CURL_IPRESOLVE_V4:
+ family = PF_INET;
+ break;
+ case CURL_IPRESOLVE_V6:
+ family = PF_INET6;
+ break;
+ }
#endif /* ENABLE_IPV6 */
-
- bufp = strdup(hostname);
- if(bufp) {
+
+ bufp = strdup(hostname);
+ if(bufp) {
struct thread_data *res = NULL;
free(conn->async.hostname);
- conn->async.hostname = bufp;
- conn->async.port = port;
- conn->async.done = FALSE; /* not done */
- conn->async.status = 0; /* clear */
- conn->async.dns = NULL; /* clear */
+ conn->async.hostname = bufp;
+ conn->async.port = port;
+ conn->async.done = FALSE; /* not done */
+ conn->async.status = 0; /* clear */
+ conn->async.dns = NULL; /* clear */
res = calloc(sizeof(struct thread_data), 1);
- if(!res) {
+ if(!res) {
free(conn->async.hostname);
- conn->async.hostname = NULL;
- return NULL;
- }
+ conn->async.hostname = NULL;
+ return NULL;
+ }
conn->async.tdata = res;
-
- /* initial status - failed */
- res->last_status = ARES_ENOTFOUND;
+
+ /* initial status - failed */
+ res->last_status = ARES_ENOTFOUND;
#ifdef ENABLE_IPV6
- if(family == PF_UNSPEC) {
+ if(family == PF_UNSPEC) {
if(Curl_ipv6works(conn)) {
- res->num_pending = 2;
-
- /* areschannel is already setup in the Curl_open() function */
- ares_gethostbyname((ares_channel)data->state.resolver, hostname,
- PF_INET, query_completed_cb, conn);
- ares_gethostbyname((ares_channel)data->state.resolver, hostname,
- PF_INET6, query_completed_cb, conn);
- }
- else {
- res->num_pending = 1;
-
- /* areschannel is already setup in the Curl_open() function */
- ares_gethostbyname((ares_channel)data->state.resolver, hostname,
- PF_INET, query_completed_cb, conn);
- }
- }
- else
+ res->num_pending = 2;
+
+ /* areschannel is already setup in the Curl_open() function */
+ ares_gethostbyname((ares_channel)data->state.resolver, hostname,
+ PF_INET, query_completed_cb, conn);
+ ares_gethostbyname((ares_channel)data->state.resolver, hostname,
+ PF_INET6, query_completed_cb, conn);
+ }
+ else {
+ res->num_pending = 1;
+
+ /* areschannel is already setup in the Curl_open() function */
+ ares_gethostbyname((ares_channel)data->state.resolver, hostname,
+ PF_INET, query_completed_cb, conn);
+ }
+ }
+ else
#endif /* ENABLE_IPV6 */
- {
- res->num_pending = 1;
-
- /* areschannel is already setup in the Curl_open() function */
- ares_gethostbyname((ares_channel)data->state.resolver, hostname, family,
- query_completed_cb, conn);
- }
-
- *waitp = 1; /* expect asynchronous response */
- }
- return NULL; /* no struct yet */
-}
-
+ {
+ res->num_pending = 1;
+
+ /* areschannel is already setup in the Curl_open() function */
+ ares_gethostbyname((ares_channel)data->state.resolver, hostname, family,
+ query_completed_cb, conn);
+ }
+
+ *waitp = 1; /* expect asynchronous response */
+ }
+ return NULL; /* no struct yet */
+}
+
CURLcode Curl_set_dns_servers(struct Curl_easy *data,
- char *servers)
-{
- CURLcode result = CURLE_NOT_BUILT_IN;
- int ares_result;
-
- /* If server is NULL or empty, this would purge all DNS servers
- * from ares library, which will cause any and all queries to fail.
- * So, just return OK if none are configured and don't actually make
- * any changes to c-ares. This lets c-ares use it's defaults, which
- * it gets from the OS (for instance from /etc/resolv.conf on Linux).
- */
- if(!(servers && servers[0]))
- return CURLE_OK;
-
-#if (ARES_VERSION >= 0x010704)
+ char *servers)
+{
+ CURLcode result = CURLE_NOT_BUILT_IN;
+ int ares_result;
+
+ /* If server is NULL or empty, this would purge all DNS servers
+ * from ares library, which will cause any and all queries to fail.
+ * So, just return OK if none are configured and don't actually make
+ * any changes to c-ares. This lets c-ares use it's defaults, which
+ * it gets from the OS (for instance from /etc/resolv.conf on Linux).
+ */
+ if(!(servers && servers[0]))
+ return CURLE_OK;
+
+#if (ARES_VERSION >= 0x010704)
#if (ARES_VERSION >= 0x010b00)
ares_result = ares_set_servers_ports_csv(data->state.resolver, servers);
#else
- ares_result = ares_set_servers_csv(data->state.resolver, servers);
+ ares_result = ares_set_servers_csv(data->state.resolver, servers);
#endif
- switch(ares_result) {
- case ARES_SUCCESS:
- result = CURLE_OK;
- break;
- case ARES_ENOMEM:
- result = CURLE_OUT_OF_MEMORY;
- break;
- case ARES_ENOTINITIALIZED:
- case ARES_ENODATA:
- case ARES_EBADSTR:
- default:
- result = CURLE_BAD_FUNCTION_ARGUMENT;
- break;
- }
-#else /* too old c-ares version! */
- (void)data;
- (void)(ares_result);
-#endif
- return result;
-}
-
+ switch(ares_result) {
+ case ARES_SUCCESS:
+ result = CURLE_OK;
+ break;
+ case ARES_ENOMEM:
+ result = CURLE_OUT_OF_MEMORY;
+ break;
+ case ARES_ENOTINITIALIZED:
+ case ARES_ENODATA:
+ case ARES_EBADSTR:
+ default:
+ result = CURLE_BAD_FUNCTION_ARGUMENT;
+ break;
+ }
+#else /* too old c-ares version! */
+ (void)data;
+ (void)(ares_result);
+#endif
+ return result;
+}
+
CURLcode Curl_set_dns_interface(struct Curl_easy *data,
- const char *interf)
-{
-#if (ARES_VERSION >= 0x010704)
- if(!interf)
- interf = "";
-
- ares_set_local_dev((ares_channel)data->state.resolver, interf);
-
- return CURLE_OK;
-#else /* c-ares version too old! */
- (void)data;
- (void)interf;
- return CURLE_NOT_BUILT_IN;
-#endif
-}
-
+ const char *interf)
+{
+#if (ARES_VERSION >= 0x010704)
+ if(!interf)
+ interf = "";
+
+ ares_set_local_dev((ares_channel)data->state.resolver, interf);
+
+ return CURLE_OK;
+#else /* c-ares version too old! */
+ (void)data;
+ (void)interf;
+ return CURLE_NOT_BUILT_IN;
+#endif
+}
+
CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data,
- const char *local_ip4)
-{
-#if (ARES_VERSION >= 0x010704)
+ const char *local_ip4)
+{
+#if (ARES_VERSION >= 0x010704)
struct in_addr a4;
-
- if((!local_ip4) || (local_ip4[0] == 0)) {
+
+ if((!local_ip4) || (local_ip4[0] == 0)) {
a4.s_addr = 0; /* disabled: do not bind to a specific address */
- }
- else {
- if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) {
- return CURLE_BAD_FUNCTION_ARGUMENT;
- }
- }
-
+ }
+ else {
+ if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) {
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+ }
+
ares_set_local_ip4((ares_channel)data->state.resolver, ntohl(a4.s_addr));
-
- return CURLE_OK;
-#else /* c-ares version too old! */
- (void)data;
- (void)local_ip4;
- return CURLE_NOT_BUILT_IN;
-#endif
-}
-
+
+ return CURLE_OK;
+#else /* c-ares version too old! */
+ (void)data;
+ (void)local_ip4;
+ return CURLE_NOT_BUILT_IN;
+#endif
+}
+
CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data,
- const char *local_ip6)
-{
+ const char *local_ip6)
+{
#if (ARES_VERSION >= 0x010704) && defined(ENABLE_IPV6)
- unsigned char a6[INET6_ADDRSTRLEN];
-
- if((!local_ip6) || (local_ip6[0] == 0)) {
- /* disabled: do not bind to a specific address */
- memset(a6, 0, sizeof(a6));
- }
- else {
- if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) {
- return CURLE_BAD_FUNCTION_ARGUMENT;
- }
- }
-
- ares_set_local_ip6((ares_channel)data->state.resolver, a6);
-
- return CURLE_OK;
-#else /* c-ares version too old! */
- (void)data;
- (void)local_ip6;
- return CURLE_NOT_BUILT_IN;
-#endif
-}
-#endif /* CURLRES_ARES */
+ unsigned char a6[INET6_ADDRSTRLEN];
+
+ if((!local_ip6) || (local_ip6[0] == 0)) {
+ /* disabled: do not bind to a specific address */
+ memset(a6, 0, sizeof(a6));
+ }
+ else {
+ if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) {
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+ }
+
+ ares_set_local_ip6((ares_channel)data->state.resolver, a6);
+
+ return CURLE_OK;
+#else /* c-ares version too old! */
+ (void)data;
+ (void)local_ip6;
+ return CURLE_NOT_BUILT_IN;
+#endif
+}
+#endif /* CURLRES_ARES */
diff --git a/contrib/libs/curl/lib/asyn-thread.c b/contrib/libs/curl/lib/asyn-thread.c
index 88a778cf3b..c49878bb55 100644
--- a/contrib/libs/curl/lib/asyn-thread.c
+++ b/contrib/libs/curl/lib/asyn-thread.c
@@ -1,89 +1,89 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
#include "socketpair.h"
-
+
/***********************************************************************
* Only for threaded name resolves builds
**********************************************************************/
#ifdef CURLRES_THREADED
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#if defined(USE_THREADS_POSIX)
-# ifdef HAVE_PTHREAD_H
-# include <pthread.h>
-# endif
-#elif defined(USE_THREADS_WIN32)
-# ifdef HAVE_PROCESS_H
-# include <process.h>
-# endif
-#endif
-
-#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-#ifdef HAVE_GETADDRINFO
-# define RESOLVER_ENOMEM EAI_MEMORY
-#else
-# define RESOLVER_ENOMEM ENOMEM
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
-#include "multiif.h"
-#include "inet_ntop.h"
-#include "curl_threads.h"
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#if defined(USE_THREADS_POSIX)
+# ifdef HAVE_PTHREAD_H
+# include <pthread.h>
+# endif
+#elif defined(USE_THREADS_WIN32)
+# ifdef HAVE_PROCESS_H
+# include <process.h>
+# endif
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#ifdef HAVE_GETADDRINFO
+# define RESOLVER_ENOMEM EAI_MEMORY
+#else
+# define RESOLVER_ENOMEM ENOMEM
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
+#include "multiif.h"
+#include "inet_ntop.h"
+#include "curl_threads.h"
#include "connect.h"
#include "socketpair.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
struct resdata {
struct curltime start;
};
-
+
/* Doubly linked list of orphaned thread handles. */
struct thread_list {
curl_thread_t handle;
@@ -127,134 +127,134 @@ static void wait_and_destroy_orphaned_threads(int flags);
static void signal_orphan_is_exiting(struct thread_list *orphan);
-/*
- * Curl_resolver_global_init()
- * Called from curl_global_init() to initialize global resolver environment.
- */
-int Curl_resolver_global_init(void)
-{
+/*
+ * Curl_resolver_global_init()
+ * Called from curl_global_init() to initialize global resolver environment.
+ */
+int Curl_resolver_global_init(void)
+{
memset(&orphaned_threads, 0, sizeof(orphaned_threads));
if(Curl_mutex_init(&orphaned_threads.mutex))
return CURLE_FAILED_INIT;
- return CURLE_OK;
-}
-
-/*
- * Curl_resolver_global_cleanup()
- * Called from curl_global_cleanup() to destroy global resolver environment.
- */
-void Curl_resolver_global_cleanup(void)
-{
+ return CURLE_OK;
+}
+
+/*
+ * Curl_resolver_global_cleanup()
+ * Called from curl_global_cleanup() to destroy global resolver environment.
+ */
+void Curl_resolver_global_cleanup(void)
+{
/* Take ownership of all orphaned resolver threads and wait for them to exit.
This is necessary because the user may choose to unload the shared library
that is/contains libcurl. */
wait_and_destroy_orphaned_threads(WAIT_DESTROY_ALL);
Curl_mutex_destroy(&orphaned_threads.mutex);
-}
-
-/*
- * Curl_resolver_init()
- * Called from curl_easy_init() -> Curl_open() to initialize resolver
- * URL-state specific environment ('resolver' member of the UrlState
+}
+
+/*
+ * Curl_resolver_init()
+ * Called from curl_easy_init() -> Curl_open() to initialize resolver
+ * URL-state specific environment ('resolver' member of the UrlState
* structure).
- */
+ */
CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver)
-{
+{
(void)easy;
*resolver = calloc(1, sizeof(struct resdata));
if(!*resolver)
return CURLE_OUT_OF_MEMORY;
- return CURLE_OK;
-}
-
-/*
- * Curl_resolver_cleanup()
- * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
- * URL-state specific environment ('resolver' member of the UrlState
+ return CURLE_OK;
+}
+
+/*
+ * Curl_resolver_cleanup()
+ * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
+ * URL-state specific environment ('resolver' member of the UrlState
* structure).
- */
-void Curl_resolver_cleanup(void *resolver)
-{
+ */
+void Curl_resolver_cleanup(void *resolver)
+{
free(resolver);
-}
-
-/*
- * Curl_resolver_duphandle()
- * Called from curl_easy_duphandle() to duplicate resolver URL state-specific
+}
+
+/*
+ * Curl_resolver_duphandle()
+ * Called from curl_easy_duphandle() to duplicate resolver URL state-specific
* environment ('resolver' member of the UrlState structure).
- */
+ */
CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from)
-{
- (void)from;
+{
+ (void)from;
return Curl_resolver_init(easy, to);
-}
-
-static void destroy_async_data(struct Curl_async *);
-
-/*
- * Cancel all possibly still on-going resolves for this connection.
- */
-void Curl_resolver_cancel(struct connectdata *conn)
-{
- destroy_async_data(&conn->async);
-}
-
-/* This function is used to init a threaded resolve */
-static bool init_resolve_thread(struct connectdata *conn,
- const char *hostname, int port,
- const struct addrinfo *hints);
-
-
-/* Data for synchronization between resolver thread and its parent */
-struct thread_sync_data {
+}
+
+static void destroy_async_data(struct Curl_async *);
+
+/*
+ * Cancel all possibly still on-going resolves for this connection.
+ */
+void Curl_resolver_cancel(struct connectdata *conn)
+{
+ destroy_async_data(&conn->async);
+}
+
+/* This function is used to init a threaded resolve */
+static bool init_resolve_thread(struct connectdata *conn,
+ const char *hostname, int port,
+ const struct addrinfo *hints);
+
+
+/* Data for synchronization between resolver thread and its parent */
+struct thread_sync_data {
curl_mutex_t *mtx;
- int done;
-
+ int done;
+
char *hostname; /* hostname to resolve, Curl_async.hostname
duplicate */
- int port;
+ int port;
#ifdef USE_SOCKETPAIR
struct connectdata *conn;
curl_socket_t sock_pair[2]; /* socket pair */
#endif
- int sock_error;
+ int sock_error;
struct Curl_addrinfo *res;
-#ifdef HAVE_GETADDRINFO
- struct addrinfo hints;
-#endif
+#ifdef HAVE_GETADDRINFO
+ struct addrinfo hints;
+#endif
struct thread_data *td; /* for thread-self cleanup */
-};
-
-struct thread_data {
- curl_thread_t thread_hnd;
- unsigned int poll_interval;
+};
+
+struct thread_data {
+ curl_thread_t thread_hnd;
+ unsigned int poll_interval;
timediff_t interval_end;
- struct thread_sync_data tsd;
+ struct thread_sync_data tsd;
/* 'reserved' memory must be available in case the thread is orphaned */
void *reserved;
-};
-
-static struct thread_sync_data *conn_thread_sync_data(struct connectdata *conn)
-{
+};
+
+static struct thread_sync_data *conn_thread_sync_data(struct connectdata *conn)
+{
return &(conn->async.tdata->tsd);
-}
-
-/* Destroy resolver thread synchronization data */
-static
+}
+
+/* Destroy resolver thread synchronization data */
+static
void destroy_thread_sync_data(struct thread_sync_data *tsd)
-{
- if(tsd->mtx) {
- Curl_mutex_destroy(tsd->mtx);
- free(tsd->mtx);
- }
-
+{
+ if(tsd->mtx) {
+ Curl_mutex_destroy(tsd->mtx);
+ free(tsd->mtx);
+ }
+
free(tsd->hostname);
-
- if(tsd->res)
- Curl_freeaddrinfo(tsd->res);
-
+
+ if(tsd->res)
+ Curl_freeaddrinfo(tsd->res);
+
#ifdef USE_SOCKETPAIR
/*
* close one end of the socket pair (may be done in resolver thread);
@@ -265,42 +265,42 @@ void destroy_thread_sync_data(struct thread_sync_data *tsd)
}
#endif
memset(tsd, 0, sizeof(*tsd));
-}
-
-/* Initialize resolver thread synchronization data */
-static
+}
+
+/* Initialize resolver thread synchronization data */
+static
int init_thread_sync_data(struct thread_data *td,
const char *hostname,
int port,
const struct addrinfo *hints)
-{
+{
struct thread_sync_data *tsd = &td->tsd;
- memset(tsd, 0, sizeof(*tsd));
-
+ memset(tsd, 0, sizeof(*tsd));
+
tsd->td = td;
- tsd->port = port;
+ tsd->port = port;
/* Treat the request as done until the thread actually starts so any early
* cleanup gets done properly.
*/
tsd->done = 1;
#ifdef HAVE_GETADDRINFO
- DEBUGASSERT(hints);
- tsd->hints = *hints;
-#else
- (void) hints;
-#endif
-
- tsd->mtx = malloc(sizeof(curl_mutex_t));
- if(tsd->mtx == NULL)
- goto err_exit;
-
+ DEBUGASSERT(hints);
+ tsd->hints = *hints;
+#else
+ (void) hints;
+#endif
+
+ tsd->mtx = malloc(sizeof(curl_mutex_t));
+ if(tsd->mtx == NULL)
+ goto err_exit;
+
if(Curl_mutex_init(tsd->mtx)) {
free(tsd->mtx);
tsd->mtx = NULL;
goto err_exit;
}
-
+
#ifdef USE_SOCKETPAIR
/* create socket pair, avoid AF_LOCAL since it doesn't build on Solaris */
if(Curl_socketpair(AF_UNIX, SOCK_STREAM, 0, &tsd->sock_pair[0]) < 0) {
@@ -309,71 +309,71 @@ int init_thread_sync_data(struct thread_data *td,
goto err_exit;
}
#endif
- tsd->sock_error = CURL_ASYNC_SUCCESS;
-
- /* Copying hostname string because original can be destroyed by parent
- * thread during gethostbyname execution.
- */
- tsd->hostname = strdup(hostname);
- if(!tsd->hostname)
- goto err_exit;
-
- return 1;
-
- err_exit:
- /* Memory allocation failed */
- destroy_thread_sync_data(tsd);
- return 0;
-}
-
-static int getaddrinfo_complete(struct connectdata *conn)
-{
- struct thread_sync_data *tsd = conn_thread_sync_data(conn);
- int rc;
-
- rc = Curl_addrinfo_callback(conn, tsd->sock_error, tsd->res);
- /* The tsd->res structure has been copied to async.dns and perhaps the DNS
- cache. Set our copy to NULL so destroy_thread_sync_data doesn't free it.
- */
- tsd->res = NULL;
-
- return rc;
-}
-
-
-#ifdef HAVE_GETADDRINFO
-
-/*
- * getaddrinfo_thread() resolves a name and then exits.
- *
- * For builds without ARES, but with ENABLE_IPV6, create a resolver thread
- * and wait on it.
- */
+ tsd->sock_error = CURL_ASYNC_SUCCESS;
+
+ /* Copying hostname string because original can be destroyed by parent
+ * thread during gethostbyname execution.
+ */
+ tsd->hostname = strdup(hostname);
+ if(!tsd->hostname)
+ goto err_exit;
+
+ return 1;
+
+ err_exit:
+ /* Memory allocation failed */
+ destroy_thread_sync_data(tsd);
+ return 0;
+}
+
+static int getaddrinfo_complete(struct connectdata *conn)
+{
+ struct thread_sync_data *tsd = conn_thread_sync_data(conn);
+ int rc;
+
+ rc = Curl_addrinfo_callback(conn, tsd->sock_error, tsd->res);
+ /* The tsd->res structure has been copied to async.dns and perhaps the DNS
+ cache. Set our copy to NULL so destroy_thread_sync_data doesn't free it.
+ */
+ tsd->res = NULL;
+
+ return rc;
+}
+
+
+#ifdef HAVE_GETADDRINFO
+
+/*
+ * getaddrinfo_thread() resolves a name and then exits.
+ *
+ * For builds without ARES, but with ENABLE_IPV6, create a resolver thread
+ * and wait on it.
+ */
static unsigned int CURL_STDCALL getaddrinfo_thread(void *arg)
-{
+{
struct thread_sync_data *tsd = (struct thread_sync_data *)arg;
struct thread_data *td = tsd->td;
struct thread_list *orphan = NULL;
- char service[12];
- int rc;
+ char service[12];
+ int rc;
#ifdef USE_SOCKETPAIR
char buf[1];
#endif
-
+
msnprintf(service, sizeof(service), "%d", tsd->port);
-
- rc = Curl_getaddrinfo_ex(tsd->hostname, service, &tsd->hints, &tsd->res);
-
- if(rc != 0) {
- tsd->sock_error = SOCKERRNO?SOCKERRNO:rc;
- if(tsd->sock_error == 0)
- tsd->sock_error = RESOLVER_ENOMEM;
- }
+
+ rc = Curl_getaddrinfo_ex(tsd->hostname, service, &tsd->hints, &tsd->res);
+
+ if(rc != 0) {
+ tsd->sock_error = SOCKERRNO?SOCKERRNO:rc;
+ if(tsd->sock_error == 0)
+ tsd->sock_error = RESOLVER_ENOMEM;
+ }
else {
Curl_addrinfo_set_port(tsd->res, tsd->port);
}
-
- Curl_mutex_acquire(tsd->mtx);
+
+ Curl_mutex_acquire(tsd->mtx);
if(tsd->done) {
/* too late, gotta clean up the mess */
Curl_mutex_release(tsd->mtx);
@@ -395,33 +395,33 @@ static unsigned int CURL_STDCALL getaddrinfo_thread(void *arg)
tsd->done = 1;
Curl_mutex_release(tsd->mtx);
}
-
+
if(orphan)
signal_orphan_is_exiting(orphan);
- return 0;
-}
-
-#else /* HAVE_GETADDRINFO */
-
-/*
- * gethostbyname_thread() resolves a name and then exits.
- */
+ return 0;
+}
+
+#else /* HAVE_GETADDRINFO */
+
+/*
+ * gethostbyname_thread() resolves a name and then exits.
+ */
static unsigned int CURL_STDCALL gethostbyname_thread(void *arg)
-{
- struct thread_sync_data *tsd = (struct thread_sync_data *)arg;
+{
+ struct thread_sync_data *tsd = (struct thread_sync_data *)arg;
struct thread_data *td = tsd->td;
struct thread_list *orphan = NULL;
-
- tsd->res = Curl_ipv4_resolve_r(tsd->hostname, tsd->port);
-
- if(!tsd->res) {
- tsd->sock_error = SOCKERRNO;
- if(tsd->sock_error == 0)
- tsd->sock_error = RESOLVER_ENOMEM;
- }
-
- Curl_mutex_acquire(tsd->mtx);
+
+ tsd->res = Curl_ipv4_resolve_r(tsd->hostname, tsd->port);
+
+ if(!tsd->res) {
+ tsd->sock_error = SOCKERRNO;
+ if(tsd->sock_error == 0)
+ tsd->sock_error = RESOLVER_ENOMEM;
+ }
+
+ Curl_mutex_acquire(tsd->mtx);
if(tsd->done) {
/* too late, gotta clean up the mess */
Curl_mutex_release(tsd->mtx);
@@ -433,20 +433,20 @@ static unsigned int CURL_STDCALL gethostbyname_thread(void *arg)
tsd->done = 1;
Curl_mutex_release(tsd->mtx);
}
-
+
if(orphan)
signal_orphan_is_exiting(orphan);
- return 0;
-}
-
-#endif /* HAVE_GETADDRINFO */
-
-/*
- * destroy_async_data() cleans up async resolver data and thread handle.
- */
+ return 0;
+}
+
+#endif /* HAVE_GETADDRINFO */
+
+/*
+ * destroy_async_data() cleans up async resolver data and thread handle.
+ */
static void destroy_async_data(struct Curl_async *async)
-{
+{
if(async->tdata) {
struct thread_data *td = async->tdata;
int done;
@@ -454,7 +454,7 @@ static void destroy_async_data(struct Curl_async *async)
curl_socket_t sock_rd = td->tsd.sock_pair[0];
struct connectdata *conn = td->tsd.conn;
#endif
-
+
/* We can't wait any longer for the resolver thread so if it's not done
* then it must be orphaned.
*
@@ -501,11 +501,11 @@ static void destroy_async_data(struct Curl_async *async)
td->tsd.done = 1;
Curl_mutex_release(td->tsd.mtx);
-
+
if(done) {
if(td->thread_hnd != curl_thread_t_null)
Curl_thread_join(&td->thread_hnd);
-
+
destroy_thread_sync_data(&td->tsd);
free(td->reserved);
free(td);
@@ -519,143 +519,143 @@ static void destroy_async_data(struct Curl_async *async)
Curl_multi_closed(conn->data, sock_rd);
sclose(sock_rd);
#endif
- }
+ }
async->tdata = NULL;
free(async->hostname);
- async->hostname = NULL;
-}
-
-/*
- * init_resolve_thread() starts a new thread that performs the actual
- * resolve. This function returns before the resolve is done.
- *
- * Returns FALSE in case of failure, otherwise TRUE.
- */
+ async->hostname = NULL;
+}
+
+/*
+ * init_resolve_thread() starts a new thread that performs the actual
+ * resolve. This function returns before the resolve is done.
+ *
+ * Returns FALSE in case of failure, otherwise TRUE.
+ */
static bool init_resolve_thread(struct connectdata *conn,
const char *hostname, int port,
const struct addrinfo *hints)
-{
- struct thread_data *td = calloc(1, sizeof(struct thread_data));
+{
+ struct thread_data *td = calloc(1, sizeof(struct thread_data));
int err = ENOMEM;
-
+
conn->async.tdata = td;
- if(!td)
+ if(!td)
goto errno_exit;
-
- conn->async.port = port;
- conn->async.done = FALSE;
- conn->async.status = 0;
- conn->async.dns = NULL;
- td->thread_hnd = curl_thread_t_null;
+
+ conn->async.port = port;
+ conn->async.done = FALSE;
+ conn->async.status = 0;
+ conn->async.dns = NULL;
+ td->thread_hnd = curl_thread_t_null;
td->reserved = calloc(1, sizeof(struct thread_list));
-
+
if(!td->reserved || !init_thread_sync_data(td, hostname, port, hints)) {
conn->async.tdata = NULL;
free(td->reserved);
free(td);
goto errno_exit;
}
-
+
free(conn->async.hostname);
- conn->async.hostname = strdup(hostname);
- if(!conn->async.hostname)
- goto err_exit;
-
+ conn->async.hostname = strdup(hostname);
+ if(!conn->async.hostname)
+ goto err_exit;
+
/* The thread will set this to 1 when complete. */
td->tsd.done = 0;
-#ifdef HAVE_GETADDRINFO
- td->thread_hnd = Curl_thread_create(getaddrinfo_thread, &td->tsd);
-#else
- td->thread_hnd = Curl_thread_create(gethostbyname_thread, &td->tsd);
-#endif
-
+#ifdef HAVE_GETADDRINFO
+ td->thread_hnd = Curl_thread_create(getaddrinfo_thread, &td->tsd);
+#else
+ td->thread_hnd = Curl_thread_create(gethostbyname_thread, &td->tsd);
+#endif
+
if(td->thread_hnd == curl_thread_t_null) {
/* The thread never started, so mark it as done here for proper cleanup. */
td->tsd.done = 1;
- err = errno;
- goto err_exit;
- }
-
- return TRUE;
-
- err_exit:
- destroy_async_data(&conn->async);
-
+ err = errno;
+ goto err_exit;
+ }
+
+ return TRUE;
+
+ err_exit:
+ destroy_async_data(&conn->async);
+
errno_exit:
errno = err;
- return FALSE;
-}
-
-/*
- * resolver_error() calls failf() with the appropriate message after a resolve
- * error
- */
-
-static CURLcode resolver_error(struct connectdata *conn)
-{
- const char *host_or_proxy;
+ return FALSE;
+}
+
+/*
+ * resolver_error() calls failf() with the appropriate message after a resolve
+ * error
+ */
+
+static CURLcode resolver_error(struct connectdata *conn)
+{
+ const char *host_or_proxy;
CURLcode result;
#ifndef CURL_DISABLE_PROXY
- if(conn->bits.httpproxy) {
- host_or_proxy = "proxy";
+ if(conn->bits.httpproxy) {
+ host_or_proxy = "proxy";
result = CURLE_COULDNT_RESOLVE_PROXY;
- }
+ }
else
#endif
{
- host_or_proxy = "host";
+ host_or_proxy = "host";
result = CURLE_COULDNT_RESOLVE_HOST;
- }
-
- failf(conn->data, "Could not resolve %s: %s", host_or_proxy,
- conn->async.hostname);
+ }
+
+ failf(conn->data, "Could not resolve %s: %s", host_or_proxy,
+ conn->async.hostname);
return result;
-}
-
+}
+
/*
* 'entry' may be NULL and then no data is returned
*/
static CURLcode thread_wait_resolv(struct connectdata *conn,
struct Curl_dns_entry **entry,
bool report)
-{
+{
struct thread_data *td = conn->async.tdata;
CURLcode result = CURLE_OK;
-
- DEBUGASSERT(conn && td);
+
+ DEBUGASSERT(conn && td);
DEBUGASSERT(td->thread_hnd != curl_thread_t_null);
-
- /* wait for the thread to resolve the name */
+
+ /* wait for the thread to resolve the name */
if(Curl_thread_join(&td->thread_hnd)) {
if(entry)
result = getaddrinfo_complete(conn);
}
- else
- DEBUGASSERT(0);
-
- conn->async.done = TRUE;
-
- if(entry)
- *entry = conn->async.dns;
-
+ else
+ DEBUGASSERT(0);
+
+ conn->async.done = TRUE;
+
+ if(entry)
+ *entry = conn->async.dns;
+
if(!conn->async.dns && report)
- /* a name was not resolved, report error */
+ /* a name was not resolved, report error */
result = resolver_error(conn);
-
- destroy_async_data(&conn->async);
-
+
+ destroy_async_data(&conn->async);
+
if(!conn->async.dns && report)
connclose(conn, "asynch resolve failed");
-
+
return result;
-}
-
+}
-/*
+
+/*
* Until we gain a way to signal the resolver threads to stop early, we must
* simply wait for them and ignore their results.
*/
@@ -692,68 +692,68 @@ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
}
/*
- * Curl_resolver_is_resolved() is called repeatedly to check if a previous
- * name resolve request has completed. It should also make sure to time-out if
- * the operation seems to take too long.
- */
-CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
- struct Curl_dns_entry **entry)
-{
+ * Curl_resolver_is_resolved() is called repeatedly to check if a previous
+ * name resolve request has completed. It should also make sure to time-out if
+ * the operation seems to take too long.
+ */
+CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
+ struct Curl_dns_entry **entry)
+{
struct Curl_easy *data = conn->data;
struct thread_data *td = conn->async.tdata;
- int done = 0;
-
+ int done = 0;
+
DEBUGASSERT(entry);
- *entry = NULL;
-
- if(!td) {
- DEBUGASSERT(td);
- return CURLE_COULDNT_RESOLVE_HOST;
- }
-
- Curl_mutex_acquire(td->tsd.mtx);
- done = td->tsd.done;
- Curl_mutex_release(td->tsd.mtx);
-
- if(done) {
- getaddrinfo_complete(conn);
-
- if(!conn->async.dns) {
+ *entry = NULL;
+
+ if(!td) {
+ DEBUGASSERT(td);
+ return CURLE_COULDNT_RESOLVE_HOST;
+ }
+
+ Curl_mutex_acquire(td->tsd.mtx);
+ done = td->tsd.done;
+ Curl_mutex_release(td->tsd.mtx);
+
+ if(done) {
+ getaddrinfo_complete(conn);
+
+ if(!conn->async.dns) {
CURLcode result = resolver_error(conn);
- destroy_async_data(&conn->async);
+ destroy_async_data(&conn->async);
return result;
- }
- destroy_async_data(&conn->async);
- *entry = conn->async.dns;
- }
- else {
- /* poll for name lookup done with exponential backoff up to 250ms */
+ }
+ destroy_async_data(&conn->async);
+ *entry = conn->async.dns;
+ }
+ else {
+ /* poll for name lookup done with exponential backoff up to 250ms */
/* should be fine even if this converts to 32 bit */
timediff_t elapsed = Curl_timediff(Curl_now(),
data->progress.t_startsingle);
- if(elapsed < 0)
- elapsed = 0;
-
- if(td->poll_interval == 0)
- /* Start at 1ms poll interval */
- td->poll_interval = 1;
- else if(elapsed >= td->interval_end)
- /* Back-off exponentially if last interval expired */
- td->poll_interval *= 2;
-
- if(td->poll_interval > 250)
- td->poll_interval = 250;
-
- td->interval_end = elapsed + td->poll_interval;
+ if(elapsed < 0)
+ elapsed = 0;
+
+ if(td->poll_interval == 0)
+ /* Start at 1ms poll interval */
+ td->poll_interval = 1;
+ else if(elapsed >= td->interval_end)
+ /* Back-off exponentially if last interval expired */
+ td->poll_interval *= 2;
+
+ if(td->poll_interval > 250)
+ td->poll_interval = 250;
+
+ td->interval_end = elapsed + td->poll_interval;
Curl_expire(conn->data, td->poll_interval, EXPIRE_ASYNC_NAME);
- }
-
- return CURLE_OK;
-}
-
-int Curl_resolver_getsock(struct connectdata *conn,
+ }
+
+ return CURLE_OK;
+}
+
+int Curl_resolver_getsock(struct connectdata *conn,
curl_socket_t *socks)
-{
+{
int ret_val = 0;
timediff_t milli;
timediff_t ms;
@@ -762,7 +762,7 @@ int Curl_resolver_getsock(struct connectdata *conn,
#ifdef USE_SOCKETPAIR
struct thread_data *td = conn->async.tdata;
#else
- (void)socks;
+ (void)socks;
#endif
#ifdef USE_SOCKETPAIR
@@ -791,125 +791,125 @@ int Curl_resolver_getsock(struct connectdata *conn,
return ret_val;
-}
-
-#ifndef HAVE_GETADDRINFO
-/*
- * Curl_getaddrinfo() - for platforms without getaddrinfo
- */
+}
+
+#ifndef HAVE_GETADDRINFO
+/*
+ * Curl_getaddrinfo() - for platforms without getaddrinfo
+ */
struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp)
-{
+{
struct Curl_easy *data = conn->data;
struct resdata *reslv = (struct resdata *)data->state.resolver;
-
- *waitp = 0; /* default to synchronous response */
-
+
+ *waitp = 0; /* default to synchronous response */
+
reslv->start = Curl_now();
- /* fire up a new resolver thread! */
- if(init_resolve_thread(conn, hostname, port, NULL)) {
- *waitp = 1; /* expect asynchronous response */
- return NULL;
- }
-
+ /* fire up a new resolver thread! */
+ if(init_resolve_thread(conn, hostname, port, NULL)) {
+ *waitp = 1; /* expect asynchronous response */
+ return NULL;
+ }
+
failf(conn->data, "getaddrinfo() thread failed\n");
return NULL;
-}
-
-#else /* !HAVE_GETADDRINFO */
-
-/*
- * Curl_resolver_getaddrinfo() - for getaddrinfo
- */
+}
+
+#else /* !HAVE_GETADDRINFO */
+
+/*
+ * Curl_resolver_getaddrinfo() - for getaddrinfo
+ */
struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp)
-{
- struct addrinfo hints;
- int pf = PF_INET;
+{
+ struct addrinfo hints;
+ int pf = PF_INET;
struct Curl_easy *data = conn->data;
struct resdata *reslv = (struct resdata *)data->state.resolver;
-
- *waitp = 0; /* default to synchronous response */
-
+
+ *waitp = 0; /* default to synchronous response */
+
#ifdef CURLRES_IPV6
- /*
- * Check if a limited name resolve has been requested.
- */
- switch(conn->ip_version) {
- case CURL_IPRESOLVE_V4:
- pf = PF_INET;
- break;
- case CURL_IPRESOLVE_V6:
- pf = PF_INET6;
- break;
- default:
- pf = PF_UNSPEC;
- break;
- }
-
+ /*
+ * Check if a limited name resolve has been requested.
+ */
+ switch(conn->ip_version) {
+ case CURL_IPRESOLVE_V4:
+ pf = PF_INET;
+ break;
+ case CURL_IPRESOLVE_V6:
+ pf = PF_INET6;
+ break;
+ default:
+ pf = PF_UNSPEC;
+ break;
+ }
+
if((pf != PF_INET) && !Curl_ipv6works(conn))
/* The stack seems to be a non-IPv6 one */
- pf = PF_INET;
-#endif /* CURLRES_IPV6 */
-
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = pf;
+ pf = PF_INET;
+#endif /* CURLRES_IPV6 */
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = pf;
hints.ai_socktype = (conn->transport == TRNSPRT_TCP)?
SOCK_STREAM : SOCK_DGRAM;
-
+
reslv->start = Curl_now();
- /* fire up a new resolver thread! */
- if(init_resolve_thread(conn, hostname, port, &hints)) {
- *waitp = 1; /* expect asynchronous response */
- return NULL;
- }
-
+ /* fire up a new resolver thread! */
+ if(init_resolve_thread(conn, hostname, port, &hints)) {
+ *waitp = 1; /* expect asynchronous response */
+ return NULL;
+ }
+
failf(data, "getaddrinfo() thread failed to start\n");
return NULL;
-
-}
-
-#endif /* !HAVE_GETADDRINFO */
-
+
+}
+
+#endif /* !HAVE_GETADDRINFO */
+
CURLcode Curl_set_dns_servers(struct Curl_easy *data,
- char *servers)
-{
- (void)data;
- (void)servers;
- return CURLE_NOT_BUILT_IN;
-
-}
-
+ char *servers)
+{
+ (void)data;
+ (void)servers;
+ return CURLE_NOT_BUILT_IN;
+
+}
+
CURLcode Curl_set_dns_interface(struct Curl_easy *data,
- const char *interf)
-{
- (void)data;
- (void)interf;
- return CURLE_NOT_BUILT_IN;
-}
-
+ const char *interf)
+{
+ (void)data;
+ (void)interf;
+ return CURLE_NOT_BUILT_IN;
+}
+
CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data,
- const char *local_ip4)
-{
- (void)data;
- (void)local_ip4;
- return CURLE_NOT_BUILT_IN;
-}
-
+ const char *local_ip4)
+{
+ (void)data;
+ (void)local_ip4;
+ return CURLE_NOT_BUILT_IN;
+}
+
CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data,
- const char *local_ip6)
-{
- (void)data;
- (void)local_ip6;
- return CURLE_NOT_BUILT_IN;
-}
-
+ const char *local_ip6)
+{
+ (void)data;
+ (void)local_ip6;
+ return CURLE_NOT_BUILT_IN;
+}
+
/* Helper function to wait and destroy some or all orphaned threads.
*
* WAIT_DESTROY_ALL:
@@ -1006,4 +1006,4 @@ static void signal_orphan_is_exiting(struct thread_list *orphan)
Curl_mutex_release(&orphaned_threads.mutex);
}
-#endif /* CURLRES_THREADED */
+#endif /* CURLRES_THREADED */
diff --git a/contrib/libs/curl/lib/asyn.h b/contrib/libs/curl/lib/asyn.h
index 36fb9aed75..73a9b7268f 100644
--- a/contrib/libs/curl/lib/asyn.h
+++ b/contrib/libs/curl/lib/asyn.h
@@ -1,98 +1,98 @@
-#ifndef HEADER_CURL_ASYN_H
-#define HEADER_CURL_ASYN_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_ASYN_H
+#define HEADER_CURL_ASYN_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-#include "curl_addrinfo.h"
-
-struct addrinfo;
-struct hostent;
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+#include "curl_addrinfo.h"
+
+struct addrinfo;
+struct hostent;
struct Curl_easy;
-struct connectdata;
-struct Curl_dns_entry;
-
-/*
- * This header defines all functions in the internal asynch resolver interface.
- * All asynch resolvers need to provide these functions.
- * asyn-ares.c and asyn-thread.c are the current implementations of asynch
- * resolver backends.
- */
-
-/*
- * Curl_resolver_global_init()
- *
- * Called from curl_global_init() to initialize global resolver environment.
- * Returning anything else than CURLE_OK fails curl_global_init().
- */
-int Curl_resolver_global_init(void);
-
-/*
- * Curl_resolver_global_cleanup()
- * Called from curl_global_cleanup() to destroy global resolver environment.
- */
-void Curl_resolver_global_cleanup(void);
-
-/*
- * Curl_resolver_init()
- * Called from curl_easy_init() -> Curl_open() to initialize resolver
- * URL-state specific environment ('resolver' member of the UrlState
- * structure). Should fill the passed pointer by the initialized handler.
- * Returning anything else than CURLE_OK fails curl_easy_init() with the
- * correspondent code.
- */
+struct connectdata;
+struct Curl_dns_entry;
+
+/*
+ * This header defines all functions in the internal asynch resolver interface.
+ * All asynch resolvers need to provide these functions.
+ * asyn-ares.c and asyn-thread.c are the current implementations of asynch
+ * resolver backends.
+ */
+
+/*
+ * Curl_resolver_global_init()
+ *
+ * Called from curl_global_init() to initialize global resolver environment.
+ * Returning anything else than CURLE_OK fails curl_global_init().
+ */
+int Curl_resolver_global_init(void);
+
+/*
+ * Curl_resolver_global_cleanup()
+ * Called from curl_global_cleanup() to destroy global resolver environment.
+ */
+void Curl_resolver_global_cleanup(void);
+
+/*
+ * Curl_resolver_init()
+ * Called from curl_easy_init() -> Curl_open() to initialize resolver
+ * URL-state specific environment ('resolver' member of the UrlState
+ * structure). Should fill the passed pointer by the initialized handler.
+ * Returning anything else than CURLE_OK fails curl_easy_init() with the
+ * correspondent code.
+ */
CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver);
-
-/*
- * Curl_resolver_cleanup()
- * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
- * URL-state specific environment ('resolver' member of the UrlState
- * structure). Should destroy the handler and free all resources connected to
- * it.
- */
-void Curl_resolver_cleanup(void *resolver);
-
-/*
- * Curl_resolver_duphandle()
- * Called from curl_easy_duphandle() to duplicate resolver URL-state specific
- * environment ('resolver' member of the UrlState structure). Should
- * duplicate the 'from' handle and pass the resulting handle to the 'to'
- * pointer. Returning anything else than CURLE_OK causes failed
- * curl_easy_duphandle() call.
- */
+
+/*
+ * Curl_resolver_cleanup()
+ * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
+ * URL-state specific environment ('resolver' member of the UrlState
+ * structure). Should destroy the handler and free all resources connected to
+ * it.
+ */
+void Curl_resolver_cleanup(void *resolver);
+
+/*
+ * Curl_resolver_duphandle()
+ * Called from curl_easy_duphandle() to duplicate resolver URL-state specific
+ * environment ('resolver' member of the UrlState structure). Should
+ * duplicate the 'from' handle and pass the resulting handle to the 'to'
+ * pointer. Returning anything else than CURLE_OK causes failed
+ * curl_easy_duphandle() call.
+ */
CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to,
void *from);
-
-/*
- * Curl_resolver_cancel().
- *
- * It is called from inside other functions to cancel currently performing
- * resolver request. Should also free any temporary resources allocated to
+
+/*
+ * Curl_resolver_cancel().
+ *
+ * It is called from inside other functions to cancel currently performing
+ * resolver request. Should also free any temporary resources allocated to
* perform a request. This never waits for resolver threads to complete.
*
* It is safe to call this when conn is in any state.
- */
-void Curl_resolver_cancel(struct connectdata *conn);
-
+ */
+void Curl_resolver_cancel(struct connectdata *conn);
+
/*
* Curl_resolver_kill().
*
@@ -106,77 +106,77 @@ void Curl_resolver_cancel(struct connectdata *conn);
*/
void Curl_resolver_kill(struct connectdata *conn);
-/* Curl_resolver_getsock()
- *
- * This function is called from the multi_getsock() function. 'sock' is a
- * pointer to an array to hold the file descriptors, with 'numsock' being the
- * size of that array (in number of entries). This function is supposed to
- * return bitmask indicating what file descriptors (referring to array indexes
- * in the 'sock' array) to wait for, read/write.
- */
+/* Curl_resolver_getsock()
+ *
+ * This function is called from the multi_getsock() function. 'sock' is a
+ * pointer to an array to hold the file descriptors, with 'numsock' being the
+ * size of that array (in number of entries). This function is supposed to
+ * return bitmask indicating what file descriptors (referring to array indexes
+ * in the 'sock' array) to wait for, read/write.
+ */
int Curl_resolver_getsock(struct connectdata *conn, curl_socket_t *sock);
-
-/*
- * Curl_resolver_is_resolved()
- *
- * Called repeatedly to check if a previous name resolve request has
- * completed. It should also make sure to time-out if the operation seems to
- * take too long.
- *
- * Returns normal CURLcode errors.
- */
-CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
- struct Curl_dns_entry **dns);
-
-/*
- * Curl_resolver_wait_resolv()
- *
+
+/*
+ * Curl_resolver_is_resolved()
+ *
+ * Called repeatedly to check if a previous name resolve request has
+ * completed. It should also make sure to time-out if the operation seems to
+ * take too long.
+ *
+ * Returns normal CURLcode errors.
+ */
+CURLcode Curl_resolver_is_resolved(struct connectdata *conn,
+ struct Curl_dns_entry **dns);
+
+/*
+ * Curl_resolver_wait_resolv()
+ *
* Waits for a resolve to finish. This function should be avoided since using
- * this risk getting the multi interface to "hang".
- *
- * If 'entry' is non-NULL, make it point to the resolved dns entry
- *
+ * this risk getting the multi interface to "hang".
+ *
+ * If 'entry' is non-NULL, make it point to the resolved dns entry
+ *
* Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved,
* CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors.
- */
-CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
- struct Curl_dns_entry **dnsentry);
-
-/*
- * Curl_resolver_getaddrinfo() - when using this resolver
- *
- * Returns name information about the given hostname and port number. If
- * successful, the 'hostent' is returned and the forth argument will point to
- * memory we need to free after use. That memory *MUST* be freed with
- * Curl_freeaddrinfo(), nothing else.
- *
- * Each resolver backend must of course make sure to return data in the
- * correct format to comply with this.
- */
+ */
+CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
+ struct Curl_dns_entry **dnsentry);
+
+/*
+ * Curl_resolver_getaddrinfo() - when using this resolver
+ *
+ * Returns name information about the given hostname and port number. If
+ * successful, the 'hostent' is returned and the forth argument will point to
+ * memory we need to free after use. That memory *MUST* be freed with
+ * Curl_freeaddrinfo(), nothing else.
+ *
+ * Each resolver backend must of course make sure to return data in the
+ * correct format to comply with this.
+ */
struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp);
-
-#ifndef CURLRES_ASYNCH
-/* convert these functions if an asynch resolver isn't used */
-#define Curl_resolver_cancel(x) Curl_nop_stmt
+
+#ifndef CURLRES_ASYNCH
+/* convert these functions if an asynch resolver isn't used */
+#define Curl_resolver_cancel(x) Curl_nop_stmt
#define Curl_resolver_kill(x) Curl_nop_stmt
-#define Curl_resolver_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST
-#define Curl_resolver_wait_resolv(x,y) CURLE_COULDNT_RESOLVE_HOST
+#define Curl_resolver_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST
+#define Curl_resolver_wait_resolv(x,y) CURLE_COULDNT_RESOLVE_HOST
#define Curl_resolver_duphandle(x,y,z) CURLE_OK
#define Curl_resolver_init(x,y) CURLE_OK
-#define Curl_resolver_global_init() CURLE_OK
-#define Curl_resolver_global_cleanup() Curl_nop_stmt
-#define Curl_resolver_cleanup(x) Curl_nop_stmt
-#endif
-
-#ifdef CURLRES_ASYNCH
-#define Curl_resolver_asynch() 1
-#else
-#define Curl_resolver_asynch() 0
-#endif
-
-
-/********** end of generic resolver interface functions *****************/
-#endif /* HEADER_CURL_ASYN_H */
+#define Curl_resolver_global_init() CURLE_OK
+#define Curl_resolver_global_cleanup() Curl_nop_stmt
+#define Curl_resolver_cleanup(x) Curl_nop_stmt
+#endif
+
+#ifdef CURLRES_ASYNCH
+#define Curl_resolver_asynch() 1
+#else
+#define Curl_resolver_asynch() 0
+#endif
+
+
+/********** end of generic resolver interface functions *****************/
+#endif /* HEADER_CURL_ASYN_H */
diff --git a/contrib/libs/curl/lib/base64.c b/contrib/libs/curl/lib/base64.c
index fe52b893c7..be6f163dc4 100644
--- a/contrib/libs/curl/lib/base64.c
+++ b/contrib/libs/curl/lib/base64.c
@@ -1,28 +1,28 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* Base64 encoding/decoding */
-
-#include "curl_setup.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* Base64 encoding/decoding */
+
+#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP_AUTH) || defined(USE_SSH) || \
!defined(CURL_DISABLE_LDAP) || \
@@ -32,35 +32,35 @@
!defined(CURL_DISABLE_DOH) || defined(USE_SSL)
#include "urldata.h" /* for the Curl_easy definition */
-#include "warnless.h"
-#include "curl_base64.h"
-#include "non-ascii.h"
-
+#include "warnless.h"
+#include "curl_base64.h"
+#include "non-ascii.h"
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-/* ---- Base64 Encoding/Decoding Table --- */
+#include "memdebug.h"
+
+/* ---- Base64 Encoding/Decoding Table --- */
static const char base64[]=
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
/* The Base 64 encoding with an URL and filename safe alphabet, RFC 4648
section 5 */
static const char base64url[]=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static size_t decodeQuantum(unsigned char *dest, const char *src)
-{
+{
size_t padding = 0;
- const char *s, *p;
+ const char *s, *p;
unsigned long i, x = 0;
-
- for(i = 0, s = src; i < 4; i++, s++) {
+
+ for(i = 0, s = src; i < 4; i++, s++) {
if(*s == '=') {
x = (x << 6);
padding++;
- }
+ }
else {
unsigned long v = 0;
p = base64;
@@ -75,83 +75,83 @@ static size_t decodeQuantum(unsigned char *dest, const char *src)
else
return 0;
}
- }
-
+ }
+
if(padding < 1)
dest[2] = curlx_ultouc(x & 0xFFUL);
- x >>= 8;
+ x >>= 8;
if(padding < 2)
dest[1] = curlx_ultouc(x & 0xFFUL);
- x >>= 8;
- dest[0] = curlx_ultouc(x & 0xFFUL);
+ x >>= 8;
+ dest[0] = curlx_ultouc(x & 0xFFUL);
return 3 - padding;
-}
-
-/*
- * Curl_base64_decode()
- *
- * Given a base64 NUL-terminated string at src, decode it and return a
- * pointer in *outptr to a newly allocated memory area holding decoded
- * data. Size of decoded data is returned in variable pointed by outlen.
- *
- * Returns CURLE_OK on success, otherwise specific error code. Function
- * output shall not be considered valid unless CURLE_OK is returned.
- *
- * When decoded data length is 0, returns NULL in *outptr.
- *
- * @unittest: 1302
- */
-CURLcode Curl_base64_decode(const char *src,
- unsigned char **outptr, size_t *outlen)
-{
+}
+
+/*
+ * Curl_base64_decode()
+ *
+ * Given a base64 NUL-terminated string at src, decode it and return a
+ * pointer in *outptr to a newly allocated memory area holding decoded
+ * data. Size of decoded data is returned in variable pointed by outlen.
+ *
+ * Returns CURLE_OK on success, otherwise specific error code. Function
+ * output shall not be considered valid unless CURLE_OK is returned.
+ *
+ * When decoded data length is 0, returns NULL in *outptr.
+ *
+ * @unittest: 1302
+ */
+CURLcode Curl_base64_decode(const char *src,
+ unsigned char **outptr, size_t *outlen)
+{
size_t srclen = 0;
- size_t length = 0;
+ size_t length = 0;
size_t padding = 0;
- size_t i;
- size_t numQuantums;
- size_t rawlen = 0;
+ size_t i;
+ size_t numQuantums;
+ size_t rawlen = 0;
unsigned char *pos;
- unsigned char *newstr;
-
- *outptr = NULL;
- *outlen = 0;
+ unsigned char *newstr;
+
+ *outptr = NULL;
+ *outlen = 0;
srclen = strlen(src);
-
+
/* Check the length of the input string is valid */
if(!srclen || srclen % 4)
return CURLE_BAD_CONTENT_ENCODING;
/* Find the position of any = padding characters */
- while((src[length] != '=') && src[length])
- length++;
+ while((src[length] != '=') && src[length])
+ length++;
- /* A maximum of two = padding characters is allowed */
- if(src[length] == '=') {
+ /* A maximum of two = padding characters is allowed */
+ if(src[length] == '=') {
padding++;
if(src[length + 1] == '=')
padding++;
- }
-
+ }
+
/* Check the = padding characters weren't part way through the input */
if(length + padding != srclen)
return CURLE_BAD_CONTENT_ENCODING;
-
+
/* Calculate the number of quantums */
numQuantums = srclen / 4;
-
+
/* Calculate the size of the decoded string */
rawlen = (numQuantums * 3) - padding;
/* Allocate our buffer including room for a zero terminator */
newstr = malloc(rawlen + 1);
- if(!newstr)
- return CURLE_OUT_OF_MEMORY;
-
+ if(!newstr)
+ return CURLE_OUT_OF_MEMORY;
+
pos = newstr;
-
+
/* Decode the quantums */
for(i = 0; i < numQuantums; i++) {
size_t result = decodeQuantum(pos, src);
@@ -163,120 +163,120 @@ CURLcode Curl_base64_decode(const char *src,
pos += result;
src += 4;
- }
-
+ }
+
/* Zero terminate */
*pos = '\0';
-
+
/* Return the decoded data */
*outptr = newstr;
*outlen = rawlen;
-
- return CURLE_OK;
-}
-
+
+ return CURLE_OK;
+}
+
static CURLcode base64_encode(const char *table64,
struct Curl_easy *data,
const char *inputbuff, size_t insize,
char **outptr, size_t *outlen)
-{
+{
CURLcode result;
- unsigned char ibuf[3];
- unsigned char obuf[4];
- int i;
- int inputparts;
- char *output;
- char *base64data;
- char *convbuf = NULL;
-
- const char *indata = inputbuff;
-
- *outptr = NULL;
- *outlen = 0;
-
+ unsigned char ibuf[3];
+ unsigned char obuf[4];
+ int i;
+ int inputparts;
+ char *output;
+ char *base64data;
+ char *convbuf = NULL;
+
+ const char *indata = inputbuff;
+
+ *outptr = NULL;
+ *outlen = 0;
+
if(!insize)
- insize = strlen(indata);
-
+ insize = strlen(indata);
+
#if SIZEOF_SIZE_T == 4
if(insize > UINT_MAX/4)
- return CURLE_OUT_OF_MEMORY;
+ return CURLE_OUT_OF_MEMORY;
#endif
-
+
base64data = output = malloc(insize * 4 / 3 + 4);
if(!output)
return CURLE_OUT_OF_MEMORY;
- /*
- * The base64 data needs to be created using the network encoding
- * not the host encoding. And we can't change the actual input
- * so we copy it to a buffer, translate it, and use that instead.
- */
+ /*
+ * The base64 data needs to be created using the network encoding
+ * not the host encoding. And we can't change the actual input
+ * so we copy it to a buffer, translate it, and use that instead.
+ */
result = Curl_convert_clone(data, indata, insize, &convbuf);
if(result) {
- free(output);
+ free(output);
return result;
- }
-
- if(convbuf)
- indata = (char *)convbuf;
-
- while(insize > 0) {
- for(i = inputparts = 0; i < 3; i++) {
- if(insize > 0) {
- inputparts++;
- ibuf[i] = (unsigned char) *indata;
- indata++;
- insize--;
- }
- else
- ibuf[i] = 0;
- }
-
- obuf[0] = (unsigned char) ((ibuf[0] & 0xFC) >> 2);
- obuf[1] = (unsigned char) (((ibuf[0] & 0x03) << 4) | \
- ((ibuf[1] & 0xF0) >> 4));
- obuf[2] = (unsigned char) (((ibuf[1] & 0x0F) << 2) | \
- ((ibuf[2] & 0xC0) >> 6));
- obuf[3] = (unsigned char) (ibuf[2] & 0x3F);
-
- switch(inputparts) {
- case 1: /* only one byte read */
+ }
+
+ if(convbuf)
+ indata = (char *)convbuf;
+
+ while(insize > 0) {
+ for(i = inputparts = 0; i < 3; i++) {
+ if(insize > 0) {
+ inputparts++;
+ ibuf[i] = (unsigned char) *indata;
+ indata++;
+ insize--;
+ }
+ else
+ ibuf[i] = 0;
+ }
+
+ obuf[0] = (unsigned char) ((ibuf[0] & 0xFC) >> 2);
+ obuf[1] = (unsigned char) (((ibuf[0] & 0x03) << 4) | \
+ ((ibuf[1] & 0xF0) >> 4));
+ obuf[2] = (unsigned char) (((ibuf[1] & 0x0F) << 2) | \
+ ((ibuf[2] & 0xC0) >> 6));
+ obuf[3] = (unsigned char) (ibuf[2] & 0x3F);
+
+ switch(inputparts) {
+ case 1: /* only one byte read */
msnprintf(output, 5, "%c%c==",
table64[obuf[0]],
table64[obuf[1]]);
- break;
+ break;
- case 2: /* two bytes read */
+ case 2: /* two bytes read */
msnprintf(output, 5, "%c%c%c=",
table64[obuf[0]],
table64[obuf[1]],
table64[obuf[2]]);
- break;
+ break;
- default:
+ default:
msnprintf(output, 5, "%c%c%c%c",
table64[obuf[0]],
table64[obuf[1]],
table64[obuf[2]],
table64[obuf[3]]);
- break;
- }
- output += 4;
- }
+ break;
+ }
+ output += 4;
+ }
/* Zero terminate */
- *output = '\0';
-
+ *output = '\0';
+
/* Return the pointer to the new data (allocated memory) */
*outptr = base64data;
-
+
free(convbuf);
-
+
/* Return the length of the new data */
*outlen = strlen(base64data);
- return CURLE_OK;
-}
+ return CURLE_OK;
+}
/*
* Curl_base64_encode()
diff --git a/contrib/libs/curl/lib/config-amigaos.h b/contrib/libs/curl/lib/config-amigaos.h
index c95fb2be4c..3c9d76ef3d 100644
--- a/contrib/libs/curl/lib/config-amigaos.h
+++ b/contrib/libs/curl/lib/config-amigaos.h
@@ -1,164 +1,164 @@
-#ifndef HEADER_CURL_CONFIG_AMIGAOS_H
-#define HEADER_CURL_CONFIG_AMIGAOS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_AMIGAOS_H
+#define HEADER_CURL_CONFIG_AMIGAOS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* Hand crafted config file for AmigaOS */
-/* ================================================================ */
-
-#ifdef __AMIGA__ /* Any AmigaOS flavour */
-
-#define HAVE_ARPA_INET_H 1
-#define HAVE_CLOSESOCKET_CAMEL 1
-#define HAVE_ERRNO_H 1
-#define HAVE_GETHOSTBYADDR 1
-#define HAVE_INET_ADDR 1
-#define HAVE_INTTYPES_H 1
-#define HAVE_IOCTLSOCKET_CAMEL 1
-#define HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1
-#define HAVE_LIBZ 1
-#define HAVE_LONGLONG 1
-#define HAVE_MALLOC_H 1
-#define HAVE_MEMORY_H 1
-#define HAVE_NETDB_H 1
-#define HAVE_NETINET_IN_H 1
-#define HAVE_NET_IF_H 1
-#define HAVE_OPENSSL_CRYPTO_H 1
-#define HAVE_OPENSSL_ERR_H 1
-#define HAVE_OPENSSL_PEM_H 1
-#define HAVE_OPENSSL_RSA_H 1
-#define HAVE_OPENSSL_SSL_H 1
-#define HAVE_OPENSSL_X509_H 1
-#define HAVE_PERROR 1
-#define HAVE_PWD_H 1
-#define HAVE_RAND_EGD 1
-#define HAVE_RAND_STATUS 1
-#define HAVE_SELECT 1
-#define HAVE_SETJMP_H 1
-#define HAVE_SGTTY_H 1
-#define HAVE_SIGNAL 1
-#define HAVE_SIGNAL_H 1
-#define HAVE_SIG_ATOMIC_T 1
-#define HAVE_SOCKET 1
-#define HAVE_STRCASECMP 1
-#define HAVE_STRDUP 1
-#define HAVE_STRFTIME 1
-#define HAVE_STRICMP 1
-#define HAVE_STRINGS_H 1
-#define HAVE_STRING_H 1
-#define HAVE_STRSTR 1
-#define HAVE_STRUCT_TIMEVAL 1
-#define HAVE_SYS_PARAM_H 1
-#define HAVE_SYS_SOCKET_H 1
-#define HAVE_SYS_SOCKIO_H 1
-#define HAVE_SYS_STAT_H 1
-#define HAVE_SYS_TIME_H 1
-#define HAVE_SYS_TYPES_H 1
-#define HAVE_TIME_H 1
-#define HAVE_UNAME 1
-#define HAVE_UNISTD_H 1
-#define HAVE_UTIME 1
-#define HAVE_UTIME_H 1
-#define HAVE_WRITABLE_ARGV 1
-#define HAVE_ZLIB_H 1
-#define HAVE_SYS_IOCTL_H 1
-
-#define NEED_MALLOC_H 1
-
-#define SIZEOF_INT 4
-#define SIZEOF_SHORT 2
-#define SIZEOF_SIZE_T 4
-
-#define USE_MANUAL 1
-#define USE_OPENSSL 1
-#define CURL_DISABLE_LDAP 1
-
-#define OS "AmigaOS"
-
-#define PACKAGE "curl"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* ================================================================ */
+/* Hand crafted config file for AmigaOS */
+/* ================================================================ */
+
+#ifdef __AMIGA__ /* Any AmigaOS flavour */
+
+#define HAVE_ARPA_INET_H 1
+#define HAVE_CLOSESOCKET_CAMEL 1
+#define HAVE_ERRNO_H 1
+#define HAVE_GETHOSTBYADDR 1
+#define HAVE_INET_ADDR 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_IOCTLSOCKET_CAMEL 1
+#define HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1
+#define HAVE_LIBZ 1
+#define HAVE_LONGLONG 1
+#define HAVE_MALLOC_H 1
+#define HAVE_MEMORY_H 1
+#define HAVE_NETDB_H 1
+#define HAVE_NETINET_IN_H 1
+#define HAVE_NET_IF_H 1
+#define HAVE_OPENSSL_CRYPTO_H 1
+#define HAVE_OPENSSL_ERR_H 1
+#define HAVE_OPENSSL_PEM_H 1
+#define HAVE_OPENSSL_RSA_H 1
+#define HAVE_OPENSSL_SSL_H 1
+#define HAVE_OPENSSL_X509_H 1
+#define HAVE_PERROR 1
+#define HAVE_PWD_H 1
+#define HAVE_RAND_EGD 1
+#define HAVE_RAND_STATUS 1
+#define HAVE_SELECT 1
+#define HAVE_SETJMP_H 1
+#define HAVE_SGTTY_H 1
+#define HAVE_SIGNAL 1
+#define HAVE_SIGNAL_H 1
+#define HAVE_SIG_ATOMIC_T 1
+#define HAVE_SOCKET 1
+#define HAVE_STRCASECMP 1
+#define HAVE_STRDUP 1
+#define HAVE_STRFTIME 1
+#define HAVE_STRICMP 1
+#define HAVE_STRINGS_H 1
+#define HAVE_STRING_H 1
+#define HAVE_STRSTR 1
+#define HAVE_STRUCT_TIMEVAL 1
+#define HAVE_SYS_PARAM_H 1
+#define HAVE_SYS_SOCKET_H 1
+#define HAVE_SYS_SOCKIO_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_SYS_TIME_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_TIME_H 1
+#define HAVE_UNAME 1
+#define HAVE_UNISTD_H 1
+#define HAVE_UTIME 1
+#define HAVE_UTIME_H 1
+#define HAVE_WRITABLE_ARGV 1
+#define HAVE_ZLIB_H 1
+#define HAVE_SYS_IOCTL_H 1
+
+#define NEED_MALLOC_H 1
+
+#define SIZEOF_INT 4
+#define SIZEOF_SHORT 2
+#define SIZEOF_SIZE_T 4
+
+#define USE_MANUAL 1
+#define USE_OPENSSL 1
+#define CURL_DISABLE_LDAP 1
+
+#define OS "AmigaOS"
+
+#define PACKAGE "curl"
#define PACKAGE_BUGREPORT "a suitable mailing list: https://curl.se/mail/"
-#define PACKAGE_NAME "curl"
-#define PACKAGE_STRING "curl -"
-#define PACKAGE_TARNAME "curl"
-#define PACKAGE_VERSION "-"
-#define CURL_CA_BUNDLE "s:curl-ca-bundle.crt"
-
-#define RETSIGTYPE void
-#define SELECT_TYPE_ARG1 int
-#define SELECT_TYPE_ARG234 (fd_set *)
-#define SELECT_TYPE_ARG5 (struct timeval *)
-
-#define STDC_HEADERS 1
-#define TIME_WITH_SYS_TIME 1
-
-#define in_addr_t int
-
-#ifndef F_OK
-# define F_OK 0
-#endif
-
-#ifndef O_RDONLY
-# define O_RDONLY 0x0000
-#endif
-
-#ifndef LONG_MAX
-# define LONG_MAX 0x7fffffffL
-#endif
-
-#ifndef LONG_MIN
-# define LONG_MIN (-0x7fffffffL-1)
-#endif
-
-#define HAVE_GETNAMEINFO 1
-#define GETNAMEINFO_QUAL_ARG1 const
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-#define GETNAMEINFO_TYPE_ARG2 int
-#define GETNAMEINFO_TYPE_ARG46 size_t
-#define GETNAMEINFO_TYPE_ARG7 int
-
-#define HAVE_RECV 1
-#define RECV_TYPE_ARG1 long
-#define RECV_TYPE_ARG2 char *
-#define RECV_TYPE_ARG3 long
-#define RECV_TYPE_ARG4 long
-#define RECV_TYPE_RETV long
-
-#define HAVE_RECVFROM 1
-#define RECVFROM_TYPE_ARG1 long
-#define RECVFROM_TYPE_ARG2 char
-#define RECVFROM_TYPE_ARG3 long
-#define RECVFROM_TYPE_ARG4 long
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-#define RECVFROM_TYPE_ARG6 long
-#define RECVFROM_TYPE_RETV long
-
-#define HAVE_SEND 1
-#define SEND_TYPE_ARG1 int
-#define SEND_QUAL_ARG2 const
-#define SEND_TYPE_ARG2 char *
-#define SEND_TYPE_ARG3 int
-#define SEND_TYPE_ARG4 int
-#define SEND_TYPE_RETV int
-
-#endif /* __AMIGA__ */
-#endif /* HEADER_CURL_CONFIG_AMIGAOS_H */
+#define PACKAGE_NAME "curl"
+#define PACKAGE_STRING "curl -"
+#define PACKAGE_TARNAME "curl"
+#define PACKAGE_VERSION "-"
+#define CURL_CA_BUNDLE "s:curl-ca-bundle.crt"
+
+#define RETSIGTYPE void
+#define SELECT_TYPE_ARG1 int
+#define SELECT_TYPE_ARG234 (fd_set *)
+#define SELECT_TYPE_ARG5 (struct timeval *)
+
+#define STDC_HEADERS 1
+#define TIME_WITH_SYS_TIME 1
+
+#define in_addr_t int
+
+#ifndef F_OK
+# define F_OK 0
+#endif
+
+#ifndef O_RDONLY
+# define O_RDONLY 0x0000
+#endif
+
+#ifndef LONG_MAX
+# define LONG_MAX 0x7fffffffL
+#endif
+
+#ifndef LONG_MIN
+# define LONG_MIN (-0x7fffffffL-1)
+#endif
+
+#define HAVE_GETNAMEINFO 1
+#define GETNAMEINFO_QUAL_ARG1 const
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+#define GETNAMEINFO_TYPE_ARG2 int
+#define GETNAMEINFO_TYPE_ARG46 size_t
+#define GETNAMEINFO_TYPE_ARG7 int
+
+#define HAVE_RECV 1
+#define RECV_TYPE_ARG1 long
+#define RECV_TYPE_ARG2 char *
+#define RECV_TYPE_ARG3 long
+#define RECV_TYPE_ARG4 long
+#define RECV_TYPE_RETV long
+
+#define HAVE_RECVFROM 1
+#define RECVFROM_TYPE_ARG1 long
+#define RECVFROM_TYPE_ARG2 char
+#define RECVFROM_TYPE_ARG3 long
+#define RECVFROM_TYPE_ARG4 long
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+#define RECVFROM_TYPE_ARG6 long
+#define RECVFROM_TYPE_RETV long
+
+#define HAVE_SEND 1
+#define SEND_TYPE_ARG1 int
+#define SEND_QUAL_ARG2 const
+#define SEND_TYPE_ARG2 char *
+#define SEND_TYPE_ARG3 int
+#define SEND_TYPE_ARG4 int
+#define SEND_TYPE_RETV int
+
+#endif /* __AMIGA__ */
+#endif /* HEADER_CURL_CONFIG_AMIGAOS_H */
diff --git a/contrib/libs/curl/lib/config-dos.h b/contrib/libs/curl/lib/config-dos.h
index 65478f85c1..50816ac756 100644
--- a/contrib/libs/curl/lib/config-dos.h
+++ b/contrib/libs/curl/lib/config-dos.h
@@ -1,180 +1,180 @@
-#ifndef HEADER_CURL_CONFIG_DOS_H
-#define HEADER_CURL_CONFIG_DOS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_DOS_H
+#define HEADER_CURL_CONFIG_DOS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-
-/* ================================================================ */
-/* lib/config-dos.h - Hand crafted config file for DOS */
-/* ================================================================ */
-
-#if defined(DJGPP)
- #define OS "MSDOS/djgpp"
-#elif defined(__HIGHC__)
- #define OS "MSDOS/HighC"
-#elif defined(__WATCOMC__)
- #define OS "MSDOS/Watcom"
-#else
- #define OS "MSDOS/?"
-#endif
-
-#define PACKAGE "curl"
-
-#define HAVE_ARPA_INET_H 1
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+
+/* ================================================================ */
+/* lib/config-dos.h - Hand crafted config file for DOS */
+/* ================================================================ */
+
+#if defined(DJGPP)
+ #define OS "MSDOS/djgpp"
+#elif defined(__HIGHC__)
+ #define OS "MSDOS/HighC"
+#elif defined(__WATCOMC__)
+ #define OS "MSDOS/Watcom"
+#else
+ #define OS "MSDOS/?"
+#endif
+
+#define PACKAGE "curl"
+
+#define HAVE_ARPA_INET_H 1
#define HAVE_ASSERT_H 1
-#define HAVE_ERRNO_H 1
-#define HAVE_FCNTL_H 1
+#define HAVE_ERRNO_H 1
+#define HAVE_FCNTL_H 1
#define HAVE_FREEADDRINFO 1
-#define HAVE_GETADDRINFO 1
-#define HAVE_GETNAMEINFO 1
-#define HAVE_GETPROTOBYNAME 1
-#define HAVE_GETTIMEOFDAY 1
-#define HAVE_IO_H 1
-#define HAVE_IOCTL 1
-#define HAVE_IOCTL_FIONBIO 1
-#define HAVE_IOCTLSOCKET 1
-#define HAVE_IOCTLSOCKET_FIONBIO 1
-#define HAVE_LOCALE_H 1
-#define HAVE_LONGLONG 1
-#define HAVE_MEMORY_H 1
-#define HAVE_NETDB_H 1
-#define HAVE_NETINET_IN_H 1
-#define HAVE_NETINET_TCP_H 1
-#define HAVE_NET_IF_H 1
-#define HAVE_PROCESS_H 1
-#define HAVE_RECV 1
-#define HAVE_RECVFROM 1
-#define HAVE_SELECT 1
-#define HAVE_SEND 1
-#define HAVE_SETJMP_H 1
-#define HAVE_SETLOCALE 1
-#define HAVE_SETMODE 1
-#define HAVE_SIGNAL 1
-#define HAVE_SOCKET 1
-#define HAVE_STRDUP 1
-#define HAVE_STRICMP 1
-#define HAVE_STRTOLL 1
-#define HAVE_STRUCT_TIMEVAL 1
-#define HAVE_STRUCT_IN6_ADDR 1
-#define HAVE_SYS_IOCTL_H 1
-#define HAVE_SYS_SOCKET_H 1
-#define HAVE_SYS_STAT_H 1
-#define HAVE_SYS_TYPES_H 1
-#define HAVE_TIME_H 1
-#define HAVE_UNISTD_H 1
-
-#define NEED_MALLOC_H 1
-
-#define RETSIGTYPE void
-#define SIZEOF_INT 4
+#define HAVE_GETADDRINFO 1
+#define HAVE_GETNAMEINFO 1
+#define HAVE_GETPROTOBYNAME 1
+#define HAVE_GETTIMEOFDAY 1
+#define HAVE_IO_H 1
+#define HAVE_IOCTL 1
+#define HAVE_IOCTL_FIONBIO 1
+#define HAVE_IOCTLSOCKET 1
+#define HAVE_IOCTLSOCKET_FIONBIO 1
+#define HAVE_LOCALE_H 1
+#define HAVE_LONGLONG 1
+#define HAVE_MEMORY_H 1
+#define HAVE_NETDB_H 1
+#define HAVE_NETINET_IN_H 1
+#define HAVE_NETINET_TCP_H 1
+#define HAVE_NET_IF_H 1
+#define HAVE_PROCESS_H 1
+#define HAVE_RECV 1
+#define HAVE_RECVFROM 1
+#define HAVE_SELECT 1
+#define HAVE_SEND 1
+#define HAVE_SETJMP_H 1
+#define HAVE_SETLOCALE 1
+#define HAVE_SETMODE 1
+#define HAVE_SIGNAL 1
+#define HAVE_SOCKET 1
+#define HAVE_STRDUP 1
+#define HAVE_STRICMP 1
+#define HAVE_STRTOLL 1
+#define HAVE_STRUCT_TIMEVAL 1
+#define HAVE_STRUCT_IN6_ADDR 1
+#define HAVE_SYS_IOCTL_H 1
+#define HAVE_SYS_SOCKET_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_TIME_H 1
+#define HAVE_UNISTD_H 1
+
+#define NEED_MALLOC_H 1
+
+#define RETSIGTYPE void
+#define SIZEOF_INT 4
#define SIZEOF_LONG 4
-#define SIZEOF_LONG_DOUBLE 16
-#define SIZEOF_SHORT 2
-#define SIZEOF_SIZE_T 4
+#define SIZEOF_LONG_DOUBLE 16
+#define SIZEOF_SHORT 2
+#define SIZEOF_SIZE_T 4
#define SIZEOF_CURL_OFF_T 4
-#define STDC_HEADERS 1
-#define TIME_WITH_SYS_TIME 1
-
-/* Qualifiers for send(), recv(), recvfrom() and getnameinfo(). */
-
-#define SEND_TYPE_ARG1 int
-#define SEND_QUAL_ARG2 const
-#define SEND_TYPE_ARG2 void *
-#define SEND_TYPE_ARG3 int
-#define SEND_TYPE_ARG4 int
-#define SEND_TYPE_RETV int
-
-#define RECV_TYPE_ARG1 int
-#define RECV_TYPE_ARG2 void *
-#define RECV_TYPE_ARG3 int
-#define RECV_TYPE_ARG4 int
-#define RECV_TYPE_RETV int
-
-#define RECVFROM_TYPE_ARG1 int
-#define RECVFROM_TYPE_ARG2 void
-#define RECVFROM_TYPE_ARG3 int
-#define RECVFROM_TYPE_ARG4 int
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-#define RECVFROM_TYPE_ARG6 int
-#define RECVFROM_TYPE_RETV int
-#define RECVFROM_TYPE_ARG2_IS_VOID 1
-
-#define GETNAMEINFO_QUAL_ARG1 const
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-#define GETNAMEINFO_TYPE_ARG2 int
-#define GETNAMEINFO_TYPE_ARG46 int
-#define GETNAMEINFO_TYPE_ARG7 int
-
-#define BSD
-
-/* CURLDEBUG definition enables memory tracking */
-/* #define CURLDEBUG */
-
-/* USE_ZLIB on cmd-line */
-#ifdef USE_ZLIB
- #define HAVE_ZLIB_H 1
- #define HAVE_LIBZ 1
-#endif
-
+#define STDC_HEADERS 1
+#define TIME_WITH_SYS_TIME 1
+
+/* Qualifiers for send(), recv(), recvfrom() and getnameinfo(). */
+
+#define SEND_TYPE_ARG1 int
+#define SEND_QUAL_ARG2 const
+#define SEND_TYPE_ARG2 void *
+#define SEND_TYPE_ARG3 int
+#define SEND_TYPE_ARG4 int
+#define SEND_TYPE_RETV int
+
+#define RECV_TYPE_ARG1 int
+#define RECV_TYPE_ARG2 void *
+#define RECV_TYPE_ARG3 int
+#define RECV_TYPE_ARG4 int
+#define RECV_TYPE_RETV int
+
+#define RECVFROM_TYPE_ARG1 int
+#define RECVFROM_TYPE_ARG2 void
+#define RECVFROM_TYPE_ARG3 int
+#define RECVFROM_TYPE_ARG4 int
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+#define RECVFROM_TYPE_ARG6 int
+#define RECVFROM_TYPE_RETV int
+#define RECVFROM_TYPE_ARG2_IS_VOID 1
+
+#define GETNAMEINFO_QUAL_ARG1 const
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+#define GETNAMEINFO_TYPE_ARG2 int
+#define GETNAMEINFO_TYPE_ARG46 int
+#define GETNAMEINFO_TYPE_ARG7 int
+
+#define BSD
+
+/* CURLDEBUG definition enables memory tracking */
+/* #define CURLDEBUG */
+
+/* USE_ZLIB on cmd-line */
+#ifdef USE_ZLIB
+ #define HAVE_ZLIB_H 1
+ #define HAVE_LIBZ 1
+#endif
+
/* USE_OPENSSL on cmd-line */
#ifdef USE_OPENSSL
- #define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
- #define OPENSSL_NO_KRB5 1
-#endif
-
-/* to disable LDAP */
-#define CURL_DISABLE_LDAP 1
-
-#define in_addr_t u_long
-
-#if defined(__HIGHC__) || \
- (defined(__GNUC__) && (__GNUC__ < 4))
- #define ssize_t int
-#endif
-
-/* Target HAVE_x section */
-
-#if defined(DJGPP)
- #define HAVE_BASENAME 1
- #define HAVE_STRCASECMP 1
- #define HAVE_SIGACTION 1
- #define HAVE_SIGSETJMP 1
- #define HAVE_SYS_TIME_H 1
- #define HAVE_TERMIOS_H 1
- #define HAVE_VARIADIC_MACROS_GCC 1
-
-#elif defined(__WATCOMC__)
- #define HAVE_STRCASECMP 1
-
-#elif defined(__HIGHC__)
- #define HAVE_SYS_TIME_H 1
- #define strerror(e) strerror_s_((e))
-#endif
-
-#ifdef MSDOS /* Watt-32 */
- #define HAVE_CLOSE_S 1
-#endif
-
-#undef word
-#undef byte
-
-#endif /* HEADER_CURL_CONFIG_DOS_H */
+ #define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
+ #define OPENSSL_NO_KRB5 1
+#endif
+
+/* to disable LDAP */
+#define CURL_DISABLE_LDAP 1
+
+#define in_addr_t u_long
+
+#if defined(__HIGHC__) || \
+ (defined(__GNUC__) && (__GNUC__ < 4))
+ #define ssize_t int
+#endif
+
+/* Target HAVE_x section */
+
+#if defined(DJGPP)
+ #define HAVE_BASENAME 1
+ #define HAVE_STRCASECMP 1
+ #define HAVE_SIGACTION 1
+ #define HAVE_SIGSETJMP 1
+ #define HAVE_SYS_TIME_H 1
+ #define HAVE_TERMIOS_H 1
+ #define HAVE_VARIADIC_MACROS_GCC 1
+
+#elif defined(__WATCOMC__)
+ #define HAVE_STRCASECMP 1
+
+#elif defined(__HIGHC__)
+ #define HAVE_SYS_TIME_H 1
+ #define strerror(e) strerror_s_((e))
+#endif
+
+#ifdef MSDOS /* Watt-32 */
+ #define HAVE_CLOSE_S 1
+#endif
+
+#undef word
+#undef byte
+
+#endif /* HEADER_CURL_CONFIG_DOS_H */
diff --git a/contrib/libs/curl/lib/config-mac.h b/contrib/libs/curl/lib/config-mac.h
index 3c7cf383a9..4e610562f6 100644
--- a/contrib/libs/curl/lib/config-mac.h
+++ b/contrib/libs/curl/lib/config-mac.h
@@ -1,125 +1,125 @@
-#ifndef HEADER_CURL_CONFIG_MAC_H
-#define HEADER_CURL_CONFIG_MAC_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_MAC_H
+#define HEADER_CURL_CONFIG_MAC_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* =================================================================== */
-/* Hand crafted config file for Mac OS 9 */
-/* =================================================================== */
-/* On Mac OS X you must run configure to generate curl_config.h file */
-/* =================================================================== */
-
-#define OS "mac"
-
-/* Define if you want the built-in manual */
-#define USE_MANUAL 1
-
-#define HAVE_ERRNO_H 1
-#define HAVE_NETINET_IN_H 1
-#define HAVE_SYS_SOCKET_H 1
-#define HAVE_SYS_SELECT_H 1
-#define HAVE_NETDB_H 1
-#define HAVE_ARPA_INET_H 1
-#define HAVE_UNISTD_H 1
-#define HAVE_NET_IF_H 1
-#define HAVE_SYS_TYPES_H 1
-#define HAVE_GETTIMEOFDAY 1
-#define HAVE_FCNTL_H 1
-#define HAVE_SYS_STAT_H 1
-#define HAVE_ALLOCA_H 1
-#define HAVE_STDLIB_H 1
-#define HAVE_TIME_H 1
-#define HAVE_UTIME_H 1
-#define HAVE_SYS_TIME_H 1
-#define HAVE_SYS_UTIME_H 1
-
-#define TIME_WITH_SYS_TIME 1
-
-#define HAVE_ALARM 1
-#define HAVE_FTRUNCATE 1
-#define HAVE_UTIME 1
-#define HAVE_SETVBUF 1
-#define HAVE_STRFTIME 1
-#define HAVE_INET_ADDR 1
-#define HAVE_MEMCPY 1
-#define HAVE_SELECT 1
-#define HAVE_SOCKET 1
-#define HAVE_STRUCT_TIMEVAL 1
-
-#define HAVE_SIGACTION 1
-#define HAVE_SIGNAL_H 1
-#define HAVE_SIG_ATOMIC_T 1
-
-#ifdef MACOS_SSL_SUPPORT
-# define USE_OPENSSL 1
-#endif
-
-#define CURL_DISABLE_LDAP 1
-
-#define HAVE_RAND_STATUS 1
-#define HAVE_RAND_EGD 1
-
-#define HAVE_IOCTL 1
-#define HAVE_IOCTL_FIONBIO 1
-
-#define RETSIGTYPE void
-
-#define SIZEOF_INT 4
-#define SIZEOF_SHORT 2
-#define SIZEOF_SIZE_T 4
-
-#define HAVE_GETNAMEINFO 1
-#define GETNAMEINFO_QUAL_ARG1 const
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-#define GETNAMEINFO_TYPE_ARG2 socklen_t
-#define GETNAMEINFO_TYPE_ARG46 size_t
-#define GETNAMEINFO_TYPE_ARG7 int
-
-#define HAVE_RECV 1
-#define RECV_TYPE_ARG1 int
-#define RECV_TYPE_ARG2 void *
-#define RECV_TYPE_ARG3 size_t
-#define RECV_TYPE_ARG4 int
-#define RECV_TYPE_RETV ssize_t
-
-#define HAVE_RECVFROM 1
-#define RECVFROM_TYPE_ARG1 int
-#define RECVFROM_TYPE_ARG2 void
-#define RECVFROM_TYPE_ARG3 size_t
-#define RECVFROM_TYPE_ARG4 int
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-#define RECVFROM_TYPE_ARG6 int
-#define RECVFROM_TYPE_RETV ssize_t
-#define RECVFROM_TYPE_ARG2_IS_VOID 1
-
-#define HAVE_SEND 1
-#define SEND_TYPE_ARG1 int
-#define SEND_QUAL_ARG2 const
-#define SEND_TYPE_ARG2 void *
-#define SEND_TYPE_ARG3 size_T
-#define SEND_TYPE_ARG4 int
-#define SEND_TYPE_RETV ssize_t
-
-#define HAVE_EXTRA_STRICMP_H 1
-#define HAVE_EXTRA_STRDUP_H 1
-
-#endif /* HEADER_CURL_CONFIG_MAC_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* =================================================================== */
+/* Hand crafted config file for Mac OS 9 */
+/* =================================================================== */
+/* On Mac OS X you must run configure to generate curl_config.h file */
+/* =================================================================== */
+
+#define OS "mac"
+
+/* Define if you want the built-in manual */
+#define USE_MANUAL 1
+
+#define HAVE_ERRNO_H 1
+#define HAVE_NETINET_IN_H 1
+#define HAVE_SYS_SOCKET_H 1
+#define HAVE_SYS_SELECT_H 1
+#define HAVE_NETDB_H 1
+#define HAVE_ARPA_INET_H 1
+#define HAVE_UNISTD_H 1
+#define HAVE_NET_IF_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_GETTIMEOFDAY 1
+#define HAVE_FCNTL_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_ALLOCA_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_TIME_H 1
+#define HAVE_UTIME_H 1
+#define HAVE_SYS_TIME_H 1
+#define HAVE_SYS_UTIME_H 1
+
+#define TIME_WITH_SYS_TIME 1
+
+#define HAVE_ALARM 1
+#define HAVE_FTRUNCATE 1
+#define HAVE_UTIME 1
+#define HAVE_SETVBUF 1
+#define HAVE_STRFTIME 1
+#define HAVE_INET_ADDR 1
+#define HAVE_MEMCPY 1
+#define HAVE_SELECT 1
+#define HAVE_SOCKET 1
+#define HAVE_STRUCT_TIMEVAL 1
+
+#define HAVE_SIGACTION 1
+#define HAVE_SIGNAL_H 1
+#define HAVE_SIG_ATOMIC_T 1
+
+#ifdef MACOS_SSL_SUPPORT
+# define USE_OPENSSL 1
+#endif
+
+#define CURL_DISABLE_LDAP 1
+
+#define HAVE_RAND_STATUS 1
+#define HAVE_RAND_EGD 1
+
+#define HAVE_IOCTL 1
+#define HAVE_IOCTL_FIONBIO 1
+
+#define RETSIGTYPE void
+
+#define SIZEOF_INT 4
+#define SIZEOF_SHORT 2
+#define SIZEOF_SIZE_T 4
+
+#define HAVE_GETNAMEINFO 1
+#define GETNAMEINFO_QUAL_ARG1 const
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+#define GETNAMEINFO_TYPE_ARG2 socklen_t
+#define GETNAMEINFO_TYPE_ARG46 size_t
+#define GETNAMEINFO_TYPE_ARG7 int
+
+#define HAVE_RECV 1
+#define RECV_TYPE_ARG1 int
+#define RECV_TYPE_ARG2 void *
+#define RECV_TYPE_ARG3 size_t
+#define RECV_TYPE_ARG4 int
+#define RECV_TYPE_RETV ssize_t
+
+#define HAVE_RECVFROM 1
+#define RECVFROM_TYPE_ARG1 int
+#define RECVFROM_TYPE_ARG2 void
+#define RECVFROM_TYPE_ARG3 size_t
+#define RECVFROM_TYPE_ARG4 int
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+#define RECVFROM_TYPE_ARG6 int
+#define RECVFROM_TYPE_RETV ssize_t
+#define RECVFROM_TYPE_ARG2_IS_VOID 1
+
+#define HAVE_SEND 1
+#define SEND_TYPE_ARG1 int
+#define SEND_QUAL_ARG2 const
+#define SEND_TYPE_ARG2 void *
+#define SEND_TYPE_ARG3 size_T
+#define SEND_TYPE_ARG4 int
+#define SEND_TYPE_RETV ssize_t
+
+#define HAVE_EXTRA_STRICMP_H 1
+#define HAVE_EXTRA_STRDUP_H 1
+
+#endif /* HEADER_CURL_CONFIG_MAC_H */
diff --git a/contrib/libs/curl/lib/config-os400.h b/contrib/libs/curl/lib/config-os400.h
index eafb368711..b8676113d7 100644
--- a/contrib/libs/curl/lib/config-os400.h
+++ b/contrib/libs/curl/lib/config-os400.h
@@ -1,177 +1,177 @@
-#ifndef HEADER_CURL_CONFIG_OS400_H
-#define HEADER_CURL_CONFIG_OS400_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_OS400_H
+#define HEADER_CURL_CONFIG_OS400_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* Hand crafted config file for OS/400 */
-/* ================================================================ */
-
-#pragma enum(int)
-
-#undef PACKAGE
-
-/* Version number of this archive. */
-#undef VERSION
-
-/* Define if you have the getpass function. */
-#undef HAVE_GETPASS
-
-/* Define cpu-machine-OS */
-#define OS "OS/400"
-
-/* Define if you have the gethostbyaddr_r() function with 5 arguments */
-#define HAVE_GETHOSTBYADDR_R_5
-
-/* Define if you have the gethostbyaddr_r() function with 7 arguments */
-#undef HAVE_GETHOSTBYADDR_R_7
-
-/* Define if you have the gethostbyaddr_r() function with 8 arguments */
-#undef HAVE_GETHOSTBYADDR_R_8
-
-/* OS400 supports a 3-argument ASCII version of gethostbyaddr_r(), but its
- * prototype is incompatible with the "standard" one (1st argument is not
- * const). However, getaddrinfo() is supported (ASCII version defined as
- * a local wrapper in setup-os400.h) in a threadsafe way: we can then
- * configure getaddrinfo() as such and get rid of gethostbyname_r() without
- * loss of threadsafeness. */
-#undef HAVE_GETHOSTBYNAME_R
-#undef HAVE_GETHOSTBYNAME_R_3
-#undef HAVE_GETHOSTBYNAME_R_5
-#undef HAVE_GETHOSTBYNAME_R_6
-#define HAVE_GETADDRINFO
-#define HAVE_GETADDRINFO_THREADSAFE
-
-/* Define if you need the _REENTRANT define for some functions */
-#undef NEED_REENTRANT
-
-/* Define if you have the Kerberos4 libraries (including -ldes) */
-#undef HAVE_KRB4
-
-/* Define if you want to enable IPv6 support */
-#define ENABLE_IPV6
-
-/* Define if struct sockaddr_in6 has the sin6_scope_id member */
-#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
-
-/* Define this to 'int' if ssize_t is not an available typedefed type */
-#undef ssize_t
-
-/* Define this as a suitable file to read random data from */
-#undef RANDOM_FILE
-
-/* Define this to your Entropy Gathering Daemon socket pathname */
-#undef EGD_SOCKET
-
-/* Define to 1 if you have the alarm function. */
-#define HAVE_ALARM 1
-
-/* Define if you have the <alloca.h> header file. */
-#undef HAVE_ALLOCA_H
-
-/* Define if you have the <arpa/inet.h> header file. */
-#define HAVE_ARPA_INET_H
-
-/* Define if you have the `closesocket' function. */
-#undef HAVE_CLOSESOCKET
-
-/* Define if you have the <crypto.h> header file. */
-#undef HAVE_CRYPTO_H
-
-/* Define if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H
-
-/* Define if you have the <err.h> header file. */
-#undef HAVE_ERR_H
-
-/* Define if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H
-
-/* Define if you have the `geteuid' function. */
-#define HAVE_GETEUID
-
-/* Define if you have the `gethostbyaddr' function. */
-#define HAVE_GETHOSTBYADDR
-
-/* Define if you have the `gethostbyaddr_r' function. */
-#define HAVE_GETHOSTBYADDR_R
-
-/* Define if you have the `gethostname' function. */
-#define HAVE_GETHOSTNAME
-
-/* Define if you have the <getopt.h> header file. */
-#undef HAVE_GETOPT_H
-
-/* Define if you have the `getpass_r' function. */
-#undef HAVE_GETPASS_R
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* ================================================================ */
+/* Hand crafted config file for OS/400 */
+/* ================================================================ */
+
+#pragma enum(int)
+
+#undef PACKAGE
+
+/* Version number of this archive. */
+#undef VERSION
+
+/* Define if you have the getpass function. */
+#undef HAVE_GETPASS
+
+/* Define cpu-machine-OS */
+#define OS "OS/400"
+
+/* Define if you have the gethostbyaddr_r() function with 5 arguments */
+#define HAVE_GETHOSTBYADDR_R_5
+
+/* Define if you have the gethostbyaddr_r() function with 7 arguments */
+#undef HAVE_GETHOSTBYADDR_R_7
+
+/* Define if you have the gethostbyaddr_r() function with 8 arguments */
+#undef HAVE_GETHOSTBYADDR_R_8
+
+/* OS400 supports a 3-argument ASCII version of gethostbyaddr_r(), but its
+ * prototype is incompatible with the "standard" one (1st argument is not
+ * const). However, getaddrinfo() is supported (ASCII version defined as
+ * a local wrapper in setup-os400.h) in a threadsafe way: we can then
+ * configure getaddrinfo() as such and get rid of gethostbyname_r() without
+ * loss of threadsafeness. */
+#undef HAVE_GETHOSTBYNAME_R
+#undef HAVE_GETHOSTBYNAME_R_3
+#undef HAVE_GETHOSTBYNAME_R_5
+#undef HAVE_GETHOSTBYNAME_R_6
+#define HAVE_GETADDRINFO
+#define HAVE_GETADDRINFO_THREADSAFE
+
+/* Define if you need the _REENTRANT define for some functions */
+#undef NEED_REENTRANT
+
+/* Define if you have the Kerberos4 libraries (including -ldes) */
+#undef HAVE_KRB4
+
+/* Define if you want to enable IPv6 support */
+#define ENABLE_IPV6
+
+/* Define if struct sockaddr_in6 has the sin6_scope_id member */
+#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
+
+/* Define this to 'int' if ssize_t is not an available typedefed type */
+#undef ssize_t
+
+/* Define this as a suitable file to read random data from */
+#undef RANDOM_FILE
+
+/* Define this to your Entropy Gathering Daemon socket pathname */
+#undef EGD_SOCKET
+
+/* Define to 1 if you have the alarm function. */
+#define HAVE_ALARM 1
+
+/* Define if you have the <alloca.h> header file. */
+#undef HAVE_ALLOCA_H
+
+/* Define if you have the <arpa/inet.h> header file. */
+#define HAVE_ARPA_INET_H
+
+/* Define if you have the `closesocket' function. */
+#undef HAVE_CLOSESOCKET
+
+/* Define if you have the <crypto.h> header file. */
+#undef HAVE_CRYPTO_H
+
+/* Define if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H
+
+/* Define if you have the <err.h> header file. */
+#undef HAVE_ERR_H
+
+/* Define if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H
+
+/* Define if you have the `geteuid' function. */
+#define HAVE_GETEUID
+
+/* Define if you have the `gethostbyaddr' function. */
+#define HAVE_GETHOSTBYADDR
+
+/* Define if you have the `gethostbyaddr_r' function. */
+#define HAVE_GETHOSTBYADDR_R
+
+/* Define if you have the `gethostname' function. */
+#define HAVE_GETHOSTNAME
+
+/* Define if you have the <getopt.h> header file. */
+#undef HAVE_GETOPT_H
+
+/* Define if you have the `getpass_r' function. */
+#undef HAVE_GETPASS_R
+
/* Define to 1 if you have the getpeername function. */
#define HAVE_GETPEERNAME 1
-/* Define if you have the `getpwuid' function. */
-#define HAVE_GETPWUID
-
-/* Define if you have the `getservbyname' function. */
-#define HAVE_GETSERVBYNAME
-
+/* Define if you have the `getpwuid' function. */
+#define HAVE_GETPWUID
+
+/* Define if you have the `getservbyname' function. */
+#define HAVE_GETSERVBYNAME
+
/* Define to 1 if you have the getsockname function. */
#define HAVE_GETSOCKNAME 1
-/* Define if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY
-
-/* Define if you have the `timeval' struct. */
-#define HAVE_STRUCT_TIMEVAL
-
-/* Define if you have the `inet_addr' function. */
-#define HAVE_INET_ADDR
-
-/* Define if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H
-
-/* Define if you have the <io.h> header file. */
-#undef HAVE_IO_H
-
-/* Define if you have the `krb_get_our_ip_for_realm' function. */
-#undef HAVE_KRB_GET_OUR_IP_FOR_REALM
-
-/* Define if you have the <krb.h> header file. */
-#undef HAVE_KRB_H
-
-/* Define if you have the `nsl' library (-lnsl). */
-#undef HAVE_LIBNSL
-
-/* Define if you have the `resolv' library (-lresolv). */
-#undef HAVE_LIBRESOLV
-
-/* Define if you have the `resolve' library (-lresolve). */
-#undef HAVE_LIBRESOLVE
-
-/* Define if you have the `socket' library (-lsocket). */
-#undef HAVE_LIBSOCKET
-
-/* Define if you have GSS API. */
-#define HAVE_GSSAPI
-
+/* Define if you have the `gettimeofday' function. */
+#define HAVE_GETTIMEOFDAY
+
+/* Define if you have the `timeval' struct. */
+#define HAVE_STRUCT_TIMEVAL
+
+/* Define if you have the `inet_addr' function. */
+#define HAVE_INET_ADDR
+
+/* Define if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H
+
+/* Define if you have the <io.h> header file. */
+#undef HAVE_IO_H
+
+/* Define if you have the `krb_get_our_ip_for_realm' function. */
+#undef HAVE_KRB_GET_OUR_IP_FOR_REALM
+
+/* Define if you have the <krb.h> header file. */
+#undef HAVE_KRB_H
+
+/* Define if you have the `nsl' library (-lnsl). */
+#undef HAVE_LIBNSL
+
+/* Define if you have the `resolv' library (-lresolv). */
+#undef HAVE_LIBRESOLV
+
+/* Define if you have the `resolve' library (-lresolve). */
+#undef HAVE_LIBRESOLVE
+
+/* Define if you have the `socket' library (-lsocket). */
+#undef HAVE_LIBSOCKET
+
+/* Define if you have GSS API. */
+#define HAVE_GSSAPI
+
/* Define if you have the GNU gssapi libraries */
#undef HAVE_GSSGNU
@@ -181,389 +181,389 @@
/* Define if you have the MIT gssapi libraries */
#undef HAVE_GSSMIT
-/* Define if you have the `ucb' library (-lucb). */
-#undef HAVE_LIBUCB
-
-/* Define if you have the `localtime_r' function. */
-#define HAVE_LOCALTIME_R
-
-/* Define if you have the <malloc.h> header file. */
-#define HAVE_MALLOC_H
-
-/* Define if you need the malloc.h header file even with stdlib.h */
-/* #define NEED_MALLOC_H 1 */
-
-/* Define if you have the <memory.h> header file. */
-#undef HAVE_MEMORY_H
-
-/* Define if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H
-
-/* Define if you have the <netinet/if_ether.h> header file. */
-#undef HAVE_NETINET_IF_ETHER_H
-
-/* Define if you have the <netinet/in.h> header file. */
-#define HAVE_NETINET_IN_H
-
-/* Define if you have the <net/if.h> header file. */
-#define HAVE_NET_IF_H
-
-/* Define if you have the <openssl/crypto.h> header file. */
-#undef HAVE_OPENSSL_CRYPTO_H
-
-/* Define if you have the <openssl/err.h> header file. */
-#undef HAVE_OPENSSL_ERR_H
-
-/* Define if you have the <openssl/pem.h> header file. */
-#undef HAVE_OPENSSL_PEM_H
-
-/* Define if you have the <openssl/rsa.h> header file. */
-#undef HAVE_OPENSSL_RSA_H
-
-/* Define if you have the <openssl/ssl.h> header file. */
-#undef HAVE_OPENSSL_SSL_H
-
-/* Define if you have the <openssl/x509.h> header file. */
-#undef HAVE_OPENSSL_X509_H
-
-/* Define if you have the <pem.h> header file. */
-#undef HAVE_PEM_H
-
-/* Define if you have the `perror' function. */
-#define HAVE_PERROR
-
-/* Define if you have the <pwd.h> header file. */
-#define HAVE_PWD_H
-
-/* Define if you have the `RAND_egd' function. */
-#undef HAVE_RAND_EGD
-
-/* Define if you have the `RAND_screen' function. */
-#undef HAVE_RAND_SCREEN
-
-/* Define if you have the `RAND_status' function. */
-#undef HAVE_RAND_STATUS
-
-/* Define if you have the <rsa.h> header file. */
-#undef HAVE_RSA_H
-
-/* Define if you have the `select' function. */
-#define HAVE_SELECT
-
-/* Define if you have the `setvbuf' function. */
-#define HAVE_SETVBUF
-
-/* Define if you have the <sgtty.h> header file. */
-#undef HAVE_SGTTY_H
-
-/* Define if you have the `sigaction' function. */
-#define HAVE_SIGACTION
-
-/* Define if you have the `signal' function. */
-#undef HAVE_SIGNAL
-
-/* Define if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H
-
-/* Define if sig_atomic_t is an available typedef. */
-#define HAVE_SIG_ATOMIC_T
-
-/* Define if sig_atomic_t is already defined as volatile. */
-#undef HAVE_SIG_ATOMIC_T_VOLATILE
-
-/* Define if you have the `socket' function. */
-#define HAVE_SOCKET
-
-/* Define if you have the <ssl.h> header file. */
-#undef HAVE_SSL_H
-
-/* Define if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H
-
-
-/* The following define is needed on OS400 to enable strcmpi(), stricmp() and
- strdup(). */
-#define __cplusplus__strings__
-
-/* Define if you have the `strcasecmp' function. */
-#undef HAVE_STRCASECMP
-
-/* Define if you have the `strcmpi' function. */
-#define HAVE_STRCMPI
-
-/* Define if you have the `stricmp' function. */
-#define HAVE_STRICMP
-
-/* Define if you have the `strdup' function. */
-#define HAVE_STRDUP
-
-
-/* Define if you have the `strftime' function. */
-#define HAVE_STRFTIME
-
-/* Define if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H
-
-/* Define if you have the <string.h> header file. */
-#define HAVE_STRING_H
-
-/* Define if you have the `strlcpy' function. */
-#undef HAVE_STRLCPY
-
-/* Define if you have the <stropts.h> header file. */
-#undef HAVE_STROPTS_H
-
-/* Define if you have the `strstr' function. */
-#define HAVE_STRSTR
-
-/* Define if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R
-
-/* Define if you have the `strtoll' function. */
-#undef HAVE_STRTOLL /* Allows ASCII compile on V5R1. */
-
-/* Define if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H
-
-/* Define if you have the <sys/select.h> header file. */
-#undef HAVE_SYS_SELECT_H
-
-/* Define if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H
-
-/* Define if you have the <sys/sockio.h> header file. */
-#undef HAVE_SYS_SOCKIO_H
-
-/* Define if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H
-
-/* Define if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H
-
-/* Define if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H
-
-/* Define if you have the <sys/un.h> header file. */
-#define HAVE_SYS_UN_H
-
-/* Define if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H
-
-/* Define if you have the `tcgetattr' function. */
-#undef HAVE_TCGETATTR
-
-/* Define if you have the `tcsetattr' function. */
-#undef HAVE_TCSETATTR
-
-/* Define if you have the <termios.h> header file. */
-#undef HAVE_TERMIOS_H
-
-/* Define if you have the <termio.h> header file. */
-#undef HAVE_TERMIO_H
-
-/* Define if you have the <time.h> header file. */
-#define HAVE_TIME_H
-
-/* Define if you have the `uname' function. */
-#undef HAVE_UNAME
-
-/* Define if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H
-
-/* Define if you have the <winsock.h> header file. */
-#undef HAVE_WINSOCK_H
-
-/* Define if you have the <x509.h> header file. */
-#undef HAVE_X509_H
-
-/* Name of package */
-#undef PACKAGE
-
-/* Define as the return type of signal handlers (`int' or `void'). */
-#define RETSIGTYPE void
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of a `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 8
-
-/* Define if the compiler supports the 'long long' data type. */
-#define HAVE_LONGLONG
-
-/* The size of a `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
+/* Define if you have the `ucb' library (-lucb). */
+#undef HAVE_LIBUCB
+
+/* Define if you have the `localtime_r' function. */
+#define HAVE_LOCALTIME_R
+
+/* Define if you have the <malloc.h> header file. */
+#define HAVE_MALLOC_H
+
+/* Define if you need the malloc.h header file even with stdlib.h */
+/* #define NEED_MALLOC_H 1 */
+
+/* Define if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H
+
+/* Define if you have the <netinet/if_ether.h> header file. */
+#undef HAVE_NETINET_IF_ETHER_H
+
+/* Define if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H
+
+/* Define if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H
+
+/* Define if you have the <openssl/crypto.h> header file. */
+#undef HAVE_OPENSSL_CRYPTO_H
+
+/* Define if you have the <openssl/err.h> header file. */
+#undef HAVE_OPENSSL_ERR_H
+
+/* Define if you have the <openssl/pem.h> header file. */
+#undef HAVE_OPENSSL_PEM_H
+
+/* Define if you have the <openssl/rsa.h> header file. */
+#undef HAVE_OPENSSL_RSA_H
+
+/* Define if you have the <openssl/ssl.h> header file. */
+#undef HAVE_OPENSSL_SSL_H
+
+/* Define if you have the <openssl/x509.h> header file. */
+#undef HAVE_OPENSSL_X509_H
+
+/* Define if you have the <pem.h> header file. */
+#undef HAVE_PEM_H
+
+/* Define if you have the `perror' function. */
+#define HAVE_PERROR
+
+/* Define if you have the <pwd.h> header file. */
+#define HAVE_PWD_H
+
+/* Define if you have the `RAND_egd' function. */
+#undef HAVE_RAND_EGD
+
+/* Define if you have the `RAND_screen' function. */
+#undef HAVE_RAND_SCREEN
+
+/* Define if you have the `RAND_status' function. */
+#undef HAVE_RAND_STATUS
+
+/* Define if you have the <rsa.h> header file. */
+#undef HAVE_RSA_H
+
+/* Define if you have the `select' function. */
+#define HAVE_SELECT
+
+/* Define if you have the `setvbuf' function. */
+#define HAVE_SETVBUF
+
+/* Define if you have the <sgtty.h> header file. */
+#undef HAVE_SGTTY_H
+
+/* Define if you have the `sigaction' function. */
+#define HAVE_SIGACTION
+
+/* Define if you have the `signal' function. */
+#undef HAVE_SIGNAL
+
+/* Define if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H
+
+/* Define if sig_atomic_t is an available typedef. */
+#define HAVE_SIG_ATOMIC_T
+
+/* Define if sig_atomic_t is already defined as volatile. */
+#undef HAVE_SIG_ATOMIC_T_VOLATILE
+
+/* Define if you have the `socket' function. */
+#define HAVE_SOCKET
+
+/* Define if you have the <ssl.h> header file. */
+#undef HAVE_SSL_H
+
+/* Define if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H
+
+
+/* The following define is needed on OS400 to enable strcmpi(), stricmp() and
+ strdup(). */
+#define __cplusplus__strings__
+
+/* Define if you have the `strcasecmp' function. */
+#undef HAVE_STRCASECMP
+
+/* Define if you have the `strcmpi' function. */
+#define HAVE_STRCMPI
+
+/* Define if you have the `stricmp' function. */
+#define HAVE_STRICMP
+
+/* Define if you have the `strdup' function. */
+#define HAVE_STRDUP
+
+
+/* Define if you have the `strftime' function. */
+#define HAVE_STRFTIME
+
+/* Define if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H
+
+/* Define if you have the <string.h> header file. */
+#define HAVE_STRING_H
+
+/* Define if you have the `strlcpy' function. */
+#undef HAVE_STRLCPY
+
+/* Define if you have the <stropts.h> header file. */
+#undef HAVE_STROPTS_H
+
+/* Define if you have the `strstr' function. */
+#define HAVE_STRSTR
+
+/* Define if you have the `strtok_r' function. */
+#define HAVE_STRTOK_R
+
+/* Define if you have the `strtoll' function. */
+#undef HAVE_STRTOLL /* Allows ASCII compile on V5R1. */
+
+/* Define if you have the <sys/param.h> header file. */
+#define HAVE_SYS_PARAM_H
+
+/* Define if you have the <sys/select.h> header file. */
+#undef HAVE_SYS_SELECT_H
+
+/* Define if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H
+
+/* Define if you have the <sys/sockio.h> header file. */
+#undef HAVE_SYS_SOCKIO_H
+
+/* Define if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H
+
+/* Define if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H
+
+/* Define if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H
+
+/* Define if you have the <sys/un.h> header file. */
+#define HAVE_SYS_UN_H
+
+/* Define if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H
+
+/* Define if you have the `tcgetattr' function. */
+#undef HAVE_TCGETATTR
+
+/* Define if you have the `tcsetattr' function. */
+#undef HAVE_TCSETATTR
+
+/* Define if you have the <termios.h> header file. */
+#undef HAVE_TERMIOS_H
+
+/* Define if you have the <termio.h> header file. */
+#undef HAVE_TERMIO_H
+
+/* Define if you have the <time.h> header file. */
+#define HAVE_TIME_H
+
+/* Define if you have the `uname' function. */
+#undef HAVE_UNAME
+
+/* Define if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H
+
+/* Define if you have the <winsock.h> header file. */
+#undef HAVE_WINSOCK_H
+
+/* Define if you have the <x509.h> header file. */
+#undef HAVE_X509_H
+
+/* Name of package */
+#undef PACKAGE
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#define RETSIGTYPE void
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of a `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 8
+
+/* Define if the compiler supports the 'long long' data type. */
+#define HAVE_LONGLONG
+
+/* The size of a `long long', as computed by sizeof. */
+#define SIZEOF_LONG_LONG 8
+
+/* The size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
/* The size of `long', as computed by sizeof. */
#define SIZEOF_LONG 4
-/* The size of `size_t', as computed by sizeof. */
+/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 4
-
+
/* The size of `curl_off_t', as computed by sizeof. */
#define SIZEOF_CURL_OFF_T 8
-/* Whether long long constants must be suffixed by LL. */
-
-#define HAVE_LL
-
-/* Define this if you have struct sockaddr_storage */
-#define HAVE_STRUCT_SOCKADDR_STORAGE
-
-/* Define if you have the ANSI C header files. */
-#define STDC_HEADERS
-
-/* Define if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME
-
+/* Whether long long constants must be suffixed by LL. */
+
+#define HAVE_LL
+
+/* Define this if you have struct sockaddr_storage */
+#define HAVE_STRUCT_SOCKADDR_STORAGE
+
+/* Define if you have the ANSI C header files. */
+#define STDC_HEADERS
+
+/* Define if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME
+
/* Define to enable HTTP3 support (experimental, requires NGTCP2 or QUICHE) */
#undef ENABLE_QUIC
-/* Version number of package */
-#undef VERSION
-
-/* Number of bits in a file offset, on hosts where this is settable. */
-#undef _FILE_OFFSET_BITS
-
-/* Define for large files, on AIX-style hosts. */
-#define _LARGE_FILES
-
-/* Define to empty if `const' does not conform to ANSI C. */
-#undef const
-
-/* type to use in place of in_addr_t if not defined */
-#define in_addr_t unsigned long
-
-/* Define to `unsigned' if <sys/types.h> does not define. */
-#undef size_t
-
-/* Define if you have the ioctl function. */
-#define HAVE_IOCTL
-
-/* Define if you have a working ioctl FIONBIO function. */
-#define HAVE_IOCTL_FIONBIO
-
-/* Define if you have a working ioctl SIOCGIFADDR function. */
-#define HAVE_IOCTL_SIOCGIFADDR
-
-/* To disable LDAP */
-#undef CURL_DISABLE_LDAP
-
-/* Definition to make a library symbol externally visible. */
-#define CURL_EXTERN_SYMBOL
-
-/* Define if you have the ldap_url_parse procedure. */
-/* #define HAVE_LDAP_URL_PARSE */ /* Disabled because of an IBM bug. */
-
-/* Define if you have the getnameinfo function. */
-/* OS400 has no ASCII version of this procedure: wrapped in setup-os400.h. */
-#define HAVE_GETNAMEINFO
-
-/* Define to the type qualifier of arg 1 for getnameinfo. */
-#define GETNAMEINFO_QUAL_ARG1 const
-
-/* Define to the type of arg 1 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-
-/* Define to the type of arg 2 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG2 socklen_t
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG46 socklen_t
-
-/* Define to the type of arg 7 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG7 int
-
-/* Define if you have the recv function. */
-#define HAVE_RECV
-
-/* Define to the type of arg 1 for recv. */
-#define RECV_TYPE_ARG1 int
-
-/* Define to the type of arg 2 for recv. */
-#define RECV_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for recv. */
-#define RECV_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recv. */
-#define RECV_TYPE_ARG4 int
-
-/* Define to the function return type for recv. */
-#define RECV_TYPE_RETV int
-
-/* Define if you have the recvfrom function. */
-#define HAVE_RECVFROM
-
-/* Define to the type of arg 1 for recvfrom. */
-#define RECVFROM_TYPE_ARG1 int
-
-/* Define to the type pointed by arg 2 for recvfrom. */
-#define RECVFROM_TYPE_ARG2 char
-
-/* Define to the type of arg 3 for recvfrom. */
-#define RECVFROM_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recvfrom. */
-#define RECVFROM_TYPE_ARG4 int
-
-/* Define to the type pointed by arg 5 for recvfrom. */
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-
-/* Define to the type pointed by arg 6 for recvfrom. */
-#define RECVFROM_TYPE_ARG6 int
-
-/* Define to the function return type for recvfrom. */
-#define RECVFROM_TYPE_RETV int
-
-/* Define if you have the send function. */
-#define HAVE_SEND
-
-/* Define to the type of arg 1 for send. */
-#define SEND_TYPE_ARG1 int
-
-/* Define to the type qualifier of arg 2 for send. */
-#define SEND_QUAL_ARG2
-
-/* Define to the type of arg 2 for send. */
-#define SEND_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for send. */
-#define SEND_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for send. */
-#define SEND_TYPE_ARG4 int
-
-/* Define to the function return type for send. */
-#define SEND_TYPE_RETV int
-
-/* Define to use the GSKit package. */
+/* Version number of package */
+#undef VERSION
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+
+/* Define for large files, on AIX-style hosts. */
+#define _LARGE_FILES
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* type to use in place of in_addr_t if not defined */
+#define in_addr_t unsigned long
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+#undef size_t
+
+/* Define if you have the ioctl function. */
+#define HAVE_IOCTL
+
+/* Define if you have a working ioctl FIONBIO function. */
+#define HAVE_IOCTL_FIONBIO
+
+/* Define if you have a working ioctl SIOCGIFADDR function. */
+#define HAVE_IOCTL_SIOCGIFADDR
+
+/* To disable LDAP */
+#undef CURL_DISABLE_LDAP
+
+/* Definition to make a library symbol externally visible. */
+#define CURL_EXTERN_SYMBOL
+
+/* Define if you have the ldap_url_parse procedure. */
+/* #define HAVE_LDAP_URL_PARSE */ /* Disabled because of an IBM bug. */
+
+/* Define if you have the getnameinfo function. */
+/* OS400 has no ASCII version of this procedure: wrapped in setup-os400.h. */
+#define HAVE_GETNAMEINFO
+
+/* Define to the type qualifier of arg 1 for getnameinfo. */
+#define GETNAMEINFO_QUAL_ARG1 const
+
+/* Define to the type of arg 1 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+
+/* Define to the type of arg 2 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG2 socklen_t
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG46 socklen_t
+
+/* Define to the type of arg 7 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG7 int
+
+/* Define if you have the recv function. */
+#define HAVE_RECV
+
+/* Define to the type of arg 1 for recv. */
+#define RECV_TYPE_ARG1 int
+
+/* Define to the type of arg 2 for recv. */
+#define RECV_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for recv. */
+#define RECV_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recv. */
+#define RECV_TYPE_ARG4 int
+
+/* Define to the function return type for recv. */
+#define RECV_TYPE_RETV int
+
+/* Define if you have the recvfrom function. */
+#define HAVE_RECVFROM
+
+/* Define to the type of arg 1 for recvfrom. */
+#define RECVFROM_TYPE_ARG1 int
+
+/* Define to the type pointed by arg 2 for recvfrom. */
+#define RECVFROM_TYPE_ARG2 char
+
+/* Define to the type of arg 3 for recvfrom. */
+#define RECVFROM_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recvfrom. */
+#define RECVFROM_TYPE_ARG4 int
+
+/* Define to the type pointed by arg 5 for recvfrom. */
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+
+/* Define to the type pointed by arg 6 for recvfrom. */
+#define RECVFROM_TYPE_ARG6 int
+
+/* Define to the function return type for recvfrom. */
+#define RECVFROM_TYPE_RETV int
+
+/* Define if you have the send function. */
+#define HAVE_SEND
+
+/* Define to the type of arg 1 for send. */
+#define SEND_TYPE_ARG1 int
+
+/* Define to the type qualifier of arg 2 for send. */
+#define SEND_QUAL_ARG2
+
+/* Define to the type of arg 2 for send. */
+#define SEND_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for send. */
+#define SEND_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for send. */
+#define SEND_TYPE_ARG4 int
+
+/* Define to the function return type for send. */
+#define SEND_TYPE_RETV int
+
+/* Define to use the GSKit package. */
#define USE_GSKIT
-
+
/* Define to use the OS/400 crypto library. */
#define USE_OS400CRYPTO
/* Define to use Unix sockets. */
#define USE_UNIX_SOCKETS
-/* Use the system keyring as the default CA bundle. */
-#define CURL_CA_BUNDLE "/QIBM/UserData/ICSS/Cert/Server/DEFAULT.KDB"
-
-/* ---------------------------------------------------------------- */
-/* ADDITIONAL DEFINITIONS */
-/* ---------------------------------------------------------------- */
-
-/* The following must be defined BEFORE system header files inclusion. */
-
-#define __ptr128 /* No teraspace. */
-#define qadrt_use_fputc_inline /* Generate fputc() wrapper inline. */
-#define qadrt_use_fread_inline /* Generate fread() wrapper inline. */
-#define qadrt_use_fwrite_inline /* Generate fwrite() wrapper inline. */
-
-#endif /* HEADER_CURL_CONFIG_OS400_H */
+/* Use the system keyring as the default CA bundle. */
+#define CURL_CA_BUNDLE "/QIBM/UserData/ICSS/Cert/Server/DEFAULT.KDB"
+
+/* ---------------------------------------------------------------- */
+/* ADDITIONAL DEFINITIONS */
+/* ---------------------------------------------------------------- */
+
+/* The following must be defined BEFORE system header files inclusion. */
+
+#define __ptr128 /* No teraspace. */
+#define qadrt_use_fputc_inline /* Generate fputc() wrapper inline. */
+#define qadrt_use_fread_inline /* Generate fread() wrapper inline. */
+#define qadrt_use_fwrite_inline /* Generate fwrite() wrapper inline. */
+
+#endif /* HEADER_CURL_CONFIG_OS400_H */
diff --git a/contrib/libs/curl/lib/config-riscos.h b/contrib/libs/curl/lib/config-riscos.h
index 7926072e16..9b5f8da921 100644
--- a/contrib/libs/curl/lib/config-riscos.h
+++ b/contrib/libs/curl/lib/config-riscos.h
@@ -1,504 +1,504 @@
-#ifndef HEADER_CURL_CONFIG_RISCOS_H
-#define HEADER_CURL_CONFIG_RISCOS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_RISCOS_H
+#define HEADER_CURL_CONFIG_RISCOS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* Hand crafted config file for RISC OS */
-/* ================================================================ */
-
-/* Name of this package! */
-#undef PACKAGE
-
-/* Version number of this archive. */
-#undef VERSION
-
-/* Define if you have the getpass function. */
-#undef HAVE_GETPASS
-
-/* Define cpu-machine-OS */
-#define OS "ARM-RISC OS"
-
-/* Define if you want the built-in manual */
-#define USE_MANUAL
-
-/* Define if you have the gethostbyaddr_r() function with 5 arguments */
-#undef HAVE_GETHOSTBYADDR_R_5
-
-/* Define if you have the gethostbyaddr_r() function with 7 arguments */
-#undef HAVE_GETHOSTBYADDR_R_7
-
-/* Define if you have the gethostbyaddr_r() function with 8 arguments */
-#undef HAVE_GETHOSTBYADDR_R_8
-
-/* Define if you have the gethostbyname_r() function with 3 arguments */
-#undef HAVE_GETHOSTBYNAME_R_3
-
-/* Define if you have the gethostbyname_r() function with 5 arguments */
-#undef HAVE_GETHOSTBYNAME_R_5
-
-/* Define if you have the gethostbyname_r() function with 6 arguments */
-#undef HAVE_GETHOSTBYNAME_R_6
-
-/* Define if you need the _REENTRANT define for some functions */
-#undef NEED_REENTRANT
-
-/* Define if you have the Kerberos4 libraries (including -ldes) */
-#undef HAVE_KRB4
-
-/* Define if you want to enable IPv6 support */
-#undef ENABLE_IPV6
-
-/* Define if struct sockaddr_in6 has the sin6_scope_id member */
-#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
-
-/* Define this to 'int' if ssize_t is not an available typedefed type */
-#undef ssize_t
-
-/* Define this as a suitable file to read random data from */
-#undef RANDOM_FILE
-
-/* Define this to your Entropy Gathering Daemon socket pathname */
-#undef EGD_SOCKET
-
-/* Define if you want to enable IPv6 support */
-#undef ENABLE_IPV6
-
-/* Define if you have the alarm function. */
-#define HAVE_ALARM
-
-/* Define if you have the <alloca.h> header file. */
-#define HAVE_ALLOCA_H
-
-/* Define if you have the <arpa/inet.h> header file. */
-#define HAVE_ARPA_INET_H
-
-/* Define if you have the `closesocket' function. */
-#undef HAVE_CLOSESOCKET
-
-/* Define if you have the <crypto.h> header file. */
-#undef HAVE_CRYPTO_H
-
-/* Define if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H
-
-/* Define if you have the <err.h> header file. */
-#undef HAVE_ERR_H
-
-/* Define if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H
-
-/* Define if you have the `ftruncate' function. */
-#define HAVE_FTRUNCATE
-
-/* Define if getaddrinfo exists and works */
-#define HAVE_GETADDRINFO
-
-/* Define if you have the `geteuid' function. */
-#undef HAVE_GETEUID
-
-/* Define if you have the `gethostbyaddr' function. */
-#define HAVE_GETHOSTBYADDR
-
-/* Define if you have the `gethostbyaddr_r' function. */
-#undef HAVE_GETHOSTBYADDR_R
-
-/* Define if you have the `gethostbyname_r' function. */
-#undef HAVE_GETHOSTBYNAME_R
-
-/* Define if you have the `gethostname' function. */
-#define HAVE_GETHOSTNAME
-
-/* Define if you have the <getopt.h> header file. */
-#define HAVE_GETOPT_H
-
-/* Define if you have the `getpass_r' function. */
-#undef HAVE_GETPASS_R
-
-/* Define if you have the `getpwuid' function. */
-#undef HAVE_GETPWUID
-
-/* Define if you have the `getservbyname' function. */
-#undef HAVE_GETSERVBYNAME
-
-/* Define if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY
-
-/* Define if you have the `timeval' struct. */
-#define HAVE_STRUCT_TIMEVAL
-
-/* Define if you have the `inet_addr' function. */
-#undef HAVE_INET_ADDR
-
-/* Define if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H
-
-/* Define if you have the <io.h> header file. */
-#undef HAVE_IO_H
-
-/* Define if you have the `krb_get_our_ip_for_realm' function. */
-#undef HAVE_KRB_GET_OUR_IP_FOR_REALM
-
-/* Define if you have the <krb.h> header file. */
-#undef HAVE_KRB_H
-
-/* Define if you have the `nsl' library (-lnsl). */
-#undef HAVE_LIBNSL
-
-/* Define if you have the `resolv' library (-lresolv). */
-#undef HAVE_LIBRESOLV
-
-/* Define if you have the `resolve' library (-lresolve). */
-#undef HAVE_LIBRESOLVE
-
-/* Define if you have the `socket' library (-lsocket). */
-#undef HAVE_LIBSOCKET
-
-/* Define if you have the `ucb' library (-lucb). */
-#undef HAVE_LIBUCB
-
-/* Define if you have the `localtime_r' function. */
-#undef HAVE_LOCALTIME_R
-
-/* Define if you have the <malloc.h> header file. */
-#define HAVE_MALLOC_H
-
-/* Define if you need the malloc.h header file even with stdlib.h */
-/* #define NEED_MALLOC_H 1 */
-
-/* Define if you have the <memory.h> header file. */
-#undef HAVE_MEMORY_H
-
-/* Define if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H
-
-/* Define if you have the <netinet/if_ether.h> header file. */
-#undef HAVE_NETINET_IF_ETHER_H
-
-/* Define if you have the <netinet/in.h> header file. */
-#define HAVE_NETINET_IN_H
-
-/* Define if you have the <net/if.h> header file. */
-#define HAVE_NET_IF_H
-
-/* Define if you have the <openssl/crypto.h> header file. */
-#undef HAVE_OPENSSL_CRYPTO_H
-
-/* Define if you have the <openssl/err.h> header file. */
-#undef HAVE_OPENSSL_ERR_H
-
-/* Define if you have the <openssl/pem.h> header file. */
-#undef HAVE_OPENSSL_PEM_H
-
-/* Define if you have the <openssl/rsa.h> header file. */
-#undef HAVE_OPENSSL_RSA_H
-
-/* Define if you have the <openssl/ssl.h> header file. */
-#undef HAVE_OPENSSL_SSL_H
-
-/* Define if you have the <openssl/x509.h> header file. */
-#undef HAVE_OPENSSL_X509_H
-
-/* Define if you have the <pem.h> header file. */
-#undef HAVE_PEM_H
-
-/* Define if you have the `perror' function. */
-#undef HAVE_PERROR
-
-/* Define if you have the <pwd.h> header file. */
-#undef HAVE_PWD_H
-
-/* Define if you have the `RAND_egd' function. */
-#undef HAVE_RAND_EGD
-
-/* Define if you have the `RAND_screen' function. */
-#undef HAVE_RAND_SCREEN
-
-/* Define if you have the `RAND_status' function. */
-#undef HAVE_RAND_STATUS
-
-/* Define if you have the <rsa.h> header file. */
-#undef HAVE_RSA_H
-
-/* Define if you have the `select' function. */
-#define HAVE_SELECT
-
-/* Define if you have the `setvbuf' function. */
-#undef HAVE_SETVBUF
-
-/* Define if you have the <sgtty.h> header file. */
-#define HAVE_SGTTY_H
-
-/* Define if you have the `sigaction' function. */
-#undef HAVE_SIGACTION
-
-/* Define if you have the `signal' function. */
-#define HAVE_SIGNAL
-
-/* Define if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H
-
-/* Define if sig_atomic_t is an available typedef. */
-#define HAVE_SIG_ATOMIC_T
-
-/* Define if sig_atomic_t is already defined as volatile. */
-#undef HAVE_SIG_ATOMIC_T_VOLATILE
-
-/* Define if you have the `socket' function. */
-#define HAVE_SOCKET
-
-/* Define if you have the <ssl.h> header file. */
-#undef HAVE_SSL_H
-
-/* Define if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H
-
-/* Define if you have the `strcasecmp' function. */
-#undef HAVE_STRCASECMP
-
-/* Define if you have the `strcmpi' function. */
-#undef HAVE_STRCMPI
-
-/* Define if you have the `strdup' function. */
-#define HAVE_STRDUP
-
-/* Define if you have the `strftime' function. */
-#define HAVE_STRFTIME
-
-/* Define if you have the `stricmp' function. */
-#define HAVE_STRICMP
-
-/* Define if you have the <strings.h> header file. */
-#undef HAVE_STRINGS_H
-
-/* Define if you have the <string.h> header file. */
-#define HAVE_STRING_H
-
-/* Define if you have the `strlcpy' function. */
-#undef HAVE_STRLCPY
-
-/* Define if you have the `strstr' function. */
-#define HAVE_STRSTR
-
-/* Define if you have the `strtok_r' function. */
-#undef HAVE_STRTOK_R
-
-/* Define if you have the `strtoll' function. */
-#undef HAVE_STRTOLL
-
-/* Define if you have the <sys/param.h> header file. */
-#undef HAVE_SYS_PARAM_H
-
-/* Define if you have the <sys/select.h> header file. */
-#undef HAVE_SYS_SELECT_H
-
-/* Define if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H
-
-/* Define if you have the <sys/sockio.h> header file. */
-#undef HAVE_SYS_SOCKIO_H
-
-/* Define if you have the <sys/stat.h> header file. */
-#undef HAVE_SYS_STAT_H
-
-/* Define if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H
-
-/* Define if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H
-
-/* Define if you have the `tcgetattr' function. */
-#define HAVE_TCGETATTR
-
-/* Define if you have the `tcsetattr' function. */
-#define HAVE_TCSETATTR
-
-/* Define if you have the <termios.h> header file. */
-#define HAVE_TERMIOS_H
-
-/* Define if you have the <termio.h> header file. */
-#undef HAVE_TERMIO_H
-
-/* Define if you have the <time.h> header file. */
-#undef HAVE_TIME_H
-
-/* Define if you have the `uname' function. */
-#define HAVE_UNAME
-
-/* Define if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H
-
-/* Define if you have the <winsock.h> header file. */
-#undef HAVE_WINSOCK_H
-
-/* Define if you have the <x509.h> header file. */
-#undef HAVE_X509_H
-
-/* Name of package */
-#undef PACKAGE
-
-/* Define as the return type of signal handlers (`int' or `void'). */
-#define RETSIGTYPE void
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long double', as computed by sizeof. */
-#undef SIZEOF_LONG_DOUBLE
-
-/* The size of `long long', as computed by sizeof. */
-#undef SIZEOF_LONG_LONG
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* Define if you have the ANSI C header files. */
-#undef STDC_HEADERS
-
-/* Define if you can safely include both <sys/time.h> and <time.h>. */
-#undef TIME_WITH_SYS_TIME
-
-/* Version number of package */
-#undef VERSION
-
-/* Define if on AIX 3.
- System headers sometimes define this.
- We just want to avoid a redefinition error message. */
-#ifndef _ALL_SOURCE
-# undef _ALL_SOURCE
-#endif
-
-/* Number of bits in a file offset, on hosts where this is settable. */
-#undef _FILE_OFFSET_BITS
-
-/* Define for large files, on AIX-style hosts. */
-#undef _LARGE_FILES
-
-/* Define to empty if `const' does not conform to ANSI C. */
-#undef const
-
-/* Define to `unsigned' if <sys/types.h> does not define. */
-#undef size_t
-
-/* Define to `int' if <sys/types.h> does not define. */
-#undef ssize_t
-
-/* Define if you have the ioctl function. */
-#define HAVE_IOCTL
-
-/* Define if you have a working ioctl FIONBIO function. */
-#define HAVE_IOCTL_FIONBIO
-
-/* to disable LDAP */
-#define CURL_DISABLE_LDAP
-
-/* Define if you have the getnameinfo function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to the type qualifier of arg 1 for getnameinfo. */
-#define GETNAMEINFO_QUAL_ARG1 const
-
-/* Define to the type of arg 1 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-
-/* Define to the type of arg 2 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG2 socklen_t
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG46 size_t
-
-/* Define to the type of arg 7 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG7 int
-
-/* Define if you have the recv function. */
-#define HAVE_RECV 1
-
-/* Define to the type of arg 1 for recv. */
-#define RECV_TYPE_ARG1 int
-
-/* Define to the type of arg 2 for recv. */
-#define RECV_TYPE_ARG2 void *
-
-/* Define to the type of arg 3 for recv. */
-#define RECV_TYPE_ARG3 size_t
-
-/* Define to the type of arg 4 for recv. */
-#define RECV_TYPE_ARG4 int
-
-/* Define to the function return type for recv. */
-#define RECV_TYPE_RETV ssize_t
-
-/* Define 1 if you have the recvfrom function. */
-#define HAVE_RECVFROM 1
-
-/* Define to the type of arg 1 for recvfrom. */
-#define RECVFROM_TYPE_ARG1 int
-
-/* Define to the type pointed by arg 2 for recvfrom. */
-#define RECVFROM_TYPE_ARG2 void
-
-/* Define if the type pointed by arg 2 for recvfrom is void. */
-#define RECVFROM_TYPE_ARG2_IS_VOID
-
-/* Define to the type of arg 3 for recvfrom. */
-#define RECVFROM_TYPE_ARG3 size_t
-
-/* Define to the type of arg 4 for recvfrom. */
-#define RECVFROM_TYPE_ARG4 int
-
-/* Define to the type pointed by arg 5 for recvfrom. */
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-
-/* Define to the type pointed by arg 6 for recvfrom. */
-#define RECVFROM_TYPE_ARG6 int
-
-/* Define to the function return type for recvfrom. */
-#define RECVFROM_TYPE_RETV ssize_t
-
-/* Define if you have the send function. */
-#define HAVE_SEND 1
-
-/* Define to the type of arg 1 for send. */
-#define SEND_TYPE_ARG1 int
-
-/* Define to the type qualifier of arg 2 for send. */
-#define SEND_QUAL_ARG2 const
-
-/* Define to the type of arg 2 for send. */
-#define SEND_TYPE_ARG2 void *
-
-/* Define to the type of arg 3 for send. */
-#define SEND_TYPE_ARG3 size_t
-
-/* Define to the type of arg 4 for send. */
-#define SEND_TYPE_ARG4 int
-
-/* Define to the function return type for send. */
-#define SEND_TYPE_RETV ssize_t
-
-#endif /* HEADER_CURL_CONFIG_RISCOS_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* ================================================================ */
+/* Hand crafted config file for RISC OS */
+/* ================================================================ */
+
+/* Name of this package! */
+#undef PACKAGE
+
+/* Version number of this archive. */
+#undef VERSION
+
+/* Define if you have the getpass function. */
+#undef HAVE_GETPASS
+
+/* Define cpu-machine-OS */
+#define OS "ARM-RISC OS"
+
+/* Define if you want the built-in manual */
+#define USE_MANUAL
+
+/* Define if you have the gethostbyaddr_r() function with 5 arguments */
+#undef HAVE_GETHOSTBYADDR_R_5
+
+/* Define if you have the gethostbyaddr_r() function with 7 arguments */
+#undef HAVE_GETHOSTBYADDR_R_7
+
+/* Define if you have the gethostbyaddr_r() function with 8 arguments */
+#undef HAVE_GETHOSTBYADDR_R_8
+
+/* Define if you have the gethostbyname_r() function with 3 arguments */
+#undef HAVE_GETHOSTBYNAME_R_3
+
+/* Define if you have the gethostbyname_r() function with 5 arguments */
+#undef HAVE_GETHOSTBYNAME_R_5
+
+/* Define if you have the gethostbyname_r() function with 6 arguments */
+#undef HAVE_GETHOSTBYNAME_R_6
+
+/* Define if you need the _REENTRANT define for some functions */
+#undef NEED_REENTRANT
+
+/* Define if you have the Kerberos4 libraries (including -ldes) */
+#undef HAVE_KRB4
+
+/* Define if you want to enable IPv6 support */
+#undef ENABLE_IPV6
+
+/* Define if struct sockaddr_in6 has the sin6_scope_id member */
+#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
+
+/* Define this to 'int' if ssize_t is not an available typedefed type */
+#undef ssize_t
+
+/* Define this as a suitable file to read random data from */
+#undef RANDOM_FILE
+
+/* Define this to your Entropy Gathering Daemon socket pathname */
+#undef EGD_SOCKET
+
+/* Define if you want to enable IPv6 support */
+#undef ENABLE_IPV6
+
+/* Define if you have the alarm function. */
+#define HAVE_ALARM
+
+/* Define if you have the <alloca.h> header file. */
+#define HAVE_ALLOCA_H
+
+/* Define if you have the <arpa/inet.h> header file. */
+#define HAVE_ARPA_INET_H
+
+/* Define if you have the `closesocket' function. */
+#undef HAVE_CLOSESOCKET
+
+/* Define if you have the <crypto.h> header file. */
+#undef HAVE_CRYPTO_H
+
+/* Define if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H
+
+/* Define if you have the <err.h> header file. */
+#undef HAVE_ERR_H
+
+/* Define if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H
+
+/* Define if you have the `ftruncate' function. */
+#define HAVE_FTRUNCATE
+
+/* Define if getaddrinfo exists and works */
+#define HAVE_GETADDRINFO
+
+/* Define if you have the `geteuid' function. */
+#undef HAVE_GETEUID
+
+/* Define if you have the `gethostbyaddr' function. */
+#define HAVE_GETHOSTBYADDR
+
+/* Define if you have the `gethostbyaddr_r' function. */
+#undef HAVE_GETHOSTBYADDR_R
+
+/* Define if you have the `gethostbyname_r' function. */
+#undef HAVE_GETHOSTBYNAME_R
+
+/* Define if you have the `gethostname' function. */
+#define HAVE_GETHOSTNAME
+
+/* Define if you have the <getopt.h> header file. */
+#define HAVE_GETOPT_H
+
+/* Define if you have the `getpass_r' function. */
+#undef HAVE_GETPASS_R
+
+/* Define if you have the `getpwuid' function. */
+#undef HAVE_GETPWUID
+
+/* Define if you have the `getservbyname' function. */
+#undef HAVE_GETSERVBYNAME
+
+/* Define if you have the `gettimeofday' function. */
+#define HAVE_GETTIMEOFDAY
+
+/* Define if you have the `timeval' struct. */
+#define HAVE_STRUCT_TIMEVAL
+
+/* Define if you have the `inet_addr' function. */
+#undef HAVE_INET_ADDR
+
+/* Define if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H
+
+/* Define if you have the <io.h> header file. */
+#undef HAVE_IO_H
+
+/* Define if you have the `krb_get_our_ip_for_realm' function. */
+#undef HAVE_KRB_GET_OUR_IP_FOR_REALM
+
+/* Define if you have the <krb.h> header file. */
+#undef HAVE_KRB_H
+
+/* Define if you have the `nsl' library (-lnsl). */
+#undef HAVE_LIBNSL
+
+/* Define if you have the `resolv' library (-lresolv). */
+#undef HAVE_LIBRESOLV
+
+/* Define if you have the `resolve' library (-lresolve). */
+#undef HAVE_LIBRESOLVE
+
+/* Define if you have the `socket' library (-lsocket). */
+#undef HAVE_LIBSOCKET
+
+/* Define if you have the `ucb' library (-lucb). */
+#undef HAVE_LIBUCB
+
+/* Define if you have the `localtime_r' function. */
+#undef HAVE_LOCALTIME_R
+
+/* Define if you have the <malloc.h> header file. */
+#define HAVE_MALLOC_H
+
+/* Define if you need the malloc.h header file even with stdlib.h */
+/* #define NEED_MALLOC_H 1 */
+
+/* Define if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H
+
+/* Define if you have the <netinet/if_ether.h> header file. */
+#undef HAVE_NETINET_IF_ETHER_H
+
+/* Define if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H
+
+/* Define if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H
+
+/* Define if you have the <openssl/crypto.h> header file. */
+#undef HAVE_OPENSSL_CRYPTO_H
+
+/* Define if you have the <openssl/err.h> header file. */
+#undef HAVE_OPENSSL_ERR_H
+
+/* Define if you have the <openssl/pem.h> header file. */
+#undef HAVE_OPENSSL_PEM_H
+
+/* Define if you have the <openssl/rsa.h> header file. */
+#undef HAVE_OPENSSL_RSA_H
+
+/* Define if you have the <openssl/ssl.h> header file. */
+#undef HAVE_OPENSSL_SSL_H
+
+/* Define if you have the <openssl/x509.h> header file. */
+#undef HAVE_OPENSSL_X509_H
+
+/* Define if you have the <pem.h> header file. */
+#undef HAVE_PEM_H
+
+/* Define if you have the `perror' function. */
+#undef HAVE_PERROR
+
+/* Define if you have the <pwd.h> header file. */
+#undef HAVE_PWD_H
+
+/* Define if you have the `RAND_egd' function. */
+#undef HAVE_RAND_EGD
+
+/* Define if you have the `RAND_screen' function. */
+#undef HAVE_RAND_SCREEN
+
+/* Define if you have the `RAND_status' function. */
+#undef HAVE_RAND_STATUS
+
+/* Define if you have the <rsa.h> header file. */
+#undef HAVE_RSA_H
+
+/* Define if you have the `select' function. */
+#define HAVE_SELECT
+
+/* Define if you have the `setvbuf' function. */
+#undef HAVE_SETVBUF
+
+/* Define if you have the <sgtty.h> header file. */
+#define HAVE_SGTTY_H
+
+/* Define if you have the `sigaction' function. */
+#undef HAVE_SIGACTION
+
+/* Define if you have the `signal' function. */
+#define HAVE_SIGNAL
+
+/* Define if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H
+
+/* Define if sig_atomic_t is an available typedef. */
+#define HAVE_SIG_ATOMIC_T
+
+/* Define if sig_atomic_t is already defined as volatile. */
+#undef HAVE_SIG_ATOMIC_T_VOLATILE
+
+/* Define if you have the `socket' function. */
+#define HAVE_SOCKET
+
+/* Define if you have the <ssl.h> header file. */
+#undef HAVE_SSL_H
+
+/* Define if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H
+
+/* Define if you have the `strcasecmp' function. */
+#undef HAVE_STRCASECMP
+
+/* Define if you have the `strcmpi' function. */
+#undef HAVE_STRCMPI
+
+/* Define if you have the `strdup' function. */
+#define HAVE_STRDUP
+
+/* Define if you have the `strftime' function. */
+#define HAVE_STRFTIME
+
+/* Define if you have the `stricmp' function. */
+#define HAVE_STRICMP
+
+/* Define if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define if you have the <string.h> header file. */
+#define HAVE_STRING_H
+
+/* Define if you have the `strlcpy' function. */
+#undef HAVE_STRLCPY
+
+/* Define if you have the `strstr' function. */
+#define HAVE_STRSTR
+
+/* Define if you have the `strtok_r' function. */
+#undef HAVE_STRTOK_R
+
+/* Define if you have the `strtoll' function. */
+#undef HAVE_STRTOLL
+
+/* Define if you have the <sys/param.h> header file. */
+#undef HAVE_SYS_PARAM_H
+
+/* Define if you have the <sys/select.h> header file. */
+#undef HAVE_SYS_SELECT_H
+
+/* Define if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H
+
+/* Define if you have the <sys/sockio.h> header file. */
+#undef HAVE_SYS_SOCKIO_H
+
+/* Define if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H
+
+/* Define if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H
+
+/* Define if you have the `tcgetattr' function. */
+#define HAVE_TCGETATTR
+
+/* Define if you have the `tcsetattr' function. */
+#define HAVE_TCSETATTR
+
+/* Define if you have the <termios.h> header file. */
+#define HAVE_TERMIOS_H
+
+/* Define if you have the <termio.h> header file. */
+#undef HAVE_TERMIO_H
+
+/* Define if you have the <time.h> header file. */
+#undef HAVE_TIME_H
+
+/* Define if you have the `uname' function. */
+#define HAVE_UNAME
+
+/* Define if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H
+
+/* Define if you have the <winsock.h> header file. */
+#undef HAVE_WINSOCK_H
+
+/* Define if you have the <x509.h> header file. */
+#undef HAVE_X509_H
+
+/* Name of package */
+#undef PACKAGE
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#define RETSIGTYPE void
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `long double', as computed by sizeof. */
+#undef SIZEOF_LONG_DOUBLE
+
+/* The size of `long long', as computed by sizeof. */
+#undef SIZEOF_LONG_LONG
+
+/* The size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* Define if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Define if you can safely include both <sys/time.h> and <time.h>. */
+#undef TIME_WITH_SYS_TIME
+
+/* Version number of package */
+#undef VERSION
+
+/* Define if on AIX 3.
+ System headers sometimes define this.
+ We just want to avoid a redefinition error message. */
+#ifndef _ALL_SOURCE
+# undef _ALL_SOURCE
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+
+/* Define for large files, on AIX-style hosts. */
+#undef _LARGE_FILES
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+#undef size_t
+
+/* Define to `int' if <sys/types.h> does not define. */
+#undef ssize_t
+
+/* Define if you have the ioctl function. */
+#define HAVE_IOCTL
+
+/* Define if you have a working ioctl FIONBIO function. */
+#define HAVE_IOCTL_FIONBIO
+
+/* to disable LDAP */
+#define CURL_DISABLE_LDAP
+
+/* Define if you have the getnameinfo function. */
+#define HAVE_GETNAMEINFO 1
+
+/* Define to the type qualifier of arg 1 for getnameinfo. */
+#define GETNAMEINFO_QUAL_ARG1 const
+
+/* Define to the type of arg 1 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+
+/* Define to the type of arg 2 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG2 socklen_t
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG46 size_t
+
+/* Define to the type of arg 7 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG7 int
+
+/* Define if you have the recv function. */
+#define HAVE_RECV 1
+
+/* Define to the type of arg 1 for recv. */
+#define RECV_TYPE_ARG1 int
+
+/* Define to the type of arg 2 for recv. */
+#define RECV_TYPE_ARG2 void *
+
+/* Define to the type of arg 3 for recv. */
+#define RECV_TYPE_ARG3 size_t
+
+/* Define to the type of arg 4 for recv. */
+#define RECV_TYPE_ARG4 int
+
+/* Define to the function return type for recv. */
+#define RECV_TYPE_RETV ssize_t
+
+/* Define 1 if you have the recvfrom function. */
+#define HAVE_RECVFROM 1
+
+/* Define to the type of arg 1 for recvfrom. */
+#define RECVFROM_TYPE_ARG1 int
+
+/* Define to the type pointed by arg 2 for recvfrom. */
+#define RECVFROM_TYPE_ARG2 void
+
+/* Define if the type pointed by arg 2 for recvfrom is void. */
+#define RECVFROM_TYPE_ARG2_IS_VOID
+
+/* Define to the type of arg 3 for recvfrom. */
+#define RECVFROM_TYPE_ARG3 size_t
+
+/* Define to the type of arg 4 for recvfrom. */
+#define RECVFROM_TYPE_ARG4 int
+
+/* Define to the type pointed by arg 5 for recvfrom. */
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+
+/* Define to the type pointed by arg 6 for recvfrom. */
+#define RECVFROM_TYPE_ARG6 int
+
+/* Define to the function return type for recvfrom. */
+#define RECVFROM_TYPE_RETV ssize_t
+
+/* Define if you have the send function. */
+#define HAVE_SEND 1
+
+/* Define to the type of arg 1 for send. */
+#define SEND_TYPE_ARG1 int
+
+/* Define to the type qualifier of arg 2 for send. */
+#define SEND_QUAL_ARG2 const
+
+/* Define to the type of arg 2 for send. */
+#define SEND_TYPE_ARG2 void *
+
+/* Define to the type of arg 3 for send. */
+#define SEND_TYPE_ARG3 size_t
+
+/* Define to the type of arg 4 for send. */
+#define SEND_TYPE_ARG4 int
+
+/* Define to the function return type for send. */
+#define SEND_TYPE_RETV ssize_t
+
+#endif /* HEADER_CURL_CONFIG_RISCOS_H */
diff --git a/contrib/libs/curl/lib/config-tpf.h b/contrib/libs/curl/lib/config-tpf.h
index 6cae7fcf0d..bf69179fd5 100644
--- a/contrib/libs/curl/lib/config-tpf.h
+++ b/contrib/libs/curl/lib/config-tpf.h
@@ -1,756 +1,756 @@
-#ifndef HEADER_CURL_CONFIG_TPF_H
-#define HEADER_CURL_CONFIG_TPF_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_TPF_H
+#define HEADER_CURL_CONFIG_TPF_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* Hand crafted config file for TPF */
-/* ================================================================ */
-
-/* ---------------------------------------------------------------- */
-/* FEATURES, FUNCTIONS, and DEFINITIONS */
-/* ---------------------------------------------------------------- */
-
-/* NOTE: Refer also to the .mak file for some of the flags below */
-
-/* to disable cookies support */
-/* #undef CURL_DISABLE_COOKIES */
-
-/* to disable cryptographic authentication */
-/* #undef CURL_DISABLE_CRYPTO_AUTH */
-
-/* to disable DICT */
-/* #undef CURL_DISABLE_DICT */
-
-/* to disable FILE */
-/* #undef CURL_DISABLE_FILE */
-
-/* to disable FTP */
-/* #undef CURL_DISABLE_FTP */
-
-/* to disable HTTP */
-/* #undef CURL_DISABLE_HTTP */
-
-/* to disable LDAP */
-/* #undef CURL_DISABLE_LDAP */
-
-/* to disable TELNET */
-/* #undef CURL_DISABLE_TELNET */
-
-/* to disable TFTP */
-/* #undef CURL_DISABLE_TFTP */
-
-/* to disable verbose strings */
-/* #undef CURL_DISABLE_VERBOSE_STRINGS */
-
-/* lber dynamic library file */
-/* #undef DL_LBER_FILE */
-
-/* ldap dynamic library file */
-/* #undef DL_LDAP_FILE */
-
-/* your Entropy Gathering Daemon socket pathname */
-/* #undef EGD_SOCKET */
-
-/* Define if you want to enable IPv6 support */
-/* #undef ENABLE_IPV6 */
-
-/* Define if struct sockaddr_in6 has the sin6_scope_id member */
-/* #undef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID */
-
-/* Define to the type of arg 1 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG1 */
-
-/* Define to the type of arg 2 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG2 */
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG46 */
-
-/* Define to the type of arg 7 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG7 */
-
-/* Define to 1 if you have the alarm function. */
-#define HAVE_ALARM 1
-
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#define HAVE_ARPA_INET_H 1
-
-/* Define to 1 if you have the <arpa/tftp.h> header file. */
-/* #undef HAVE_ARPA_TFTP_H */
-
-/* Define to 1 if you have the <assert.h> header file. */
-#define HAVE_ASSERT_H 1
-
-/* Define to 1 if you have the `basename' function. */
-#define HAVE_BASENAME 1
-
-/* Define to 1 if you have the `closesocket' function. */
-/* #undef HAVE_CLOSESOCKET */
-
-/* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */
-/* #undef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA */
-#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
-
-/* Define to 1 if you have the <crypto.h> header file. */
-/* #undef HAVE_CRYPTO_H */
-#define HAVE_CRYPTO_H 1
-
-/* Define to 1 if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H 1
-
-/* Define to 1 if you have the <err.h> header file. */
-/* #undef HAVE_ERR_H */
-#define HAVE_ERR_H 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if you have the fcntl function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
-#define HAVE_FCNTL_O_NONBLOCK 1
-
-/* Define to 1 if you have the `fork' function. */
-/* #undef HAVE_FORK */
-#define HAVE_FORK 1
-
-/* Define to 1 if you have the `ftruncate' function. */
-#define HAVE_FTRUNCATE 1
-
-/* Define if getaddrinfo exists and works */
-/* #undef HAVE_GETADDRINFO */
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `gethostbyaddr' function. */
-#define HAVE_GETHOSTBYADDR 1
-
-/* If you have gethostbyname */
-#define HAVE_GETHOSTBYNAME 1
-
-/* Define to 1 if you have the `gethostbyname_r' function. */
-/* #undef HAVE_GETHOSTBYNAME_R */
-
-/* gethostbyname_r() takes 3 args */
-/* #undef HAVE_GETHOSTBYNAME_R_3 */
-
-/* gethostbyname_r() takes 5 args */
-/* #undef HAVE_GETHOSTBYNAME_R_5 */
-
-/* gethostbyname_r() takes 6 args */
-/* #undef HAVE_GETHOSTBYNAME_R_6 1 */
-
-/* Define to 1 if you have the getnameinfo function. */
-/* #undef HAVE_GETNAMEINFO */
-
-/* Define to 1 if you have the `getpass_r' function. */
-/* #undef HAVE_GETPASS_R */
-
-/* Define to 1 if you have the `getprotobyname' function. */
-/* #undef HAVE_GETPROTOBYNAME */
-
-/* Define to 1 if you have the `getpwuid' function. */
-#define HAVE_GETPWUID 1
-
-/* Define to 1 if you have the `getrlimit' function. */
-/* #undef HAVE_GETRLIMIT */
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* we have a glibc-style strerror_r() */
-/* #undef HAVE_GLIBC_STRERROR_R */
-#define HAVE_GLIBC_STRERROR_R 1
-
-/* Define to 1 if you have the `gmtime_r' function. */
-#define HAVE_GMTIME_R 1
-
-/* if you have the gssapi libraries */
-/* #undef HAVE_GSSAPI */
-
-/* if you have the GNU gssapi libraries */
-/* #undef HAVE_GSSGNU */
-
-/* if you have the Heimdal gssapi libraries */
-/* #undef HAVE_GSSHEIMDAL */
-
-/* if you have the MIT gssapi libraries */
-/* #undef HAVE_GSSMIT */
-
-/* Define to 1 if you have the `iconv' functions. */
-#define HAVE_ICONV 1
-
-/* Define to 1 if you have the `idna_strerror' function. */
-/* #undef HAVE_IDNA_STRERROR */
-
-/* Define to 1 if you have the `idn_free' function. */
-/* #undef HAVE_IDN_FREE */
-
-/* Define to 1 if you have the <idn-free.h> header file. */
-/* #undef HAVE_IDN_FREE_H */
-
-/* Define to 1 if you have the `inet_addr' function. */
-#define HAVE_INET_ADDR 1
-
-/* Define to 1 if you have a IPv6 capable working inet_ntop function. */
-/* #undef HAVE_INET_NTOP */
-
-/* Define to 1 if you have a IPv6 capable working inet_pton function. */
-/* #undef HAVE_INET_PTON */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the ioctl function. */
-#define HAVE_IOCTL 1
-
-/* Define to 1 if you have a working ioctl FIONBIO function. */
-#define HAVE_IOCTL_FIONBIO 1
-
-/* Define to 1 if you have the ioctlsocket function. */
-/* #undef HAVE_IOCTLSOCKET */
-
-/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
-/* #undef HAVE_IOCTLSOCKET_FIONBIO */
-
-/* Define to 1 if you have the IoctlSocket camel case function. */
-/* #undef HAVE_IOCTLSOCKET_CAMEL */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* ================================================================ */
+/* Hand crafted config file for TPF */
+/* ================================================================ */
+
+/* ---------------------------------------------------------------- */
+/* FEATURES, FUNCTIONS, and DEFINITIONS */
+/* ---------------------------------------------------------------- */
+
+/* NOTE: Refer also to the .mak file for some of the flags below */
+
+/* to disable cookies support */
+/* #undef CURL_DISABLE_COOKIES */
+
+/* to disable cryptographic authentication */
+/* #undef CURL_DISABLE_CRYPTO_AUTH */
+
+/* to disable DICT */
+/* #undef CURL_DISABLE_DICT */
+
+/* to disable FILE */
+/* #undef CURL_DISABLE_FILE */
+
+/* to disable FTP */
+/* #undef CURL_DISABLE_FTP */
+
+/* to disable HTTP */
+/* #undef CURL_DISABLE_HTTP */
+
+/* to disable LDAP */
+/* #undef CURL_DISABLE_LDAP */
+
+/* to disable TELNET */
+/* #undef CURL_DISABLE_TELNET */
+
+/* to disable TFTP */
+/* #undef CURL_DISABLE_TFTP */
+
+/* to disable verbose strings */
+/* #undef CURL_DISABLE_VERBOSE_STRINGS */
+
+/* lber dynamic library file */
+/* #undef DL_LBER_FILE */
+
+/* ldap dynamic library file */
+/* #undef DL_LDAP_FILE */
+
+/* your Entropy Gathering Daemon socket pathname */
+/* #undef EGD_SOCKET */
+
+/* Define if you want to enable IPv6 support */
+/* #undef ENABLE_IPV6 */
+
+/* Define if struct sockaddr_in6 has the sin6_scope_id member */
+/* #undef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID */
+
+/* Define to the type of arg 1 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG1 */
+
+/* Define to the type of arg 2 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG2 */
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG46 */
+
+/* Define to the type of arg 7 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG7 */
+
+/* Define to 1 if you have the alarm function. */
+#define HAVE_ALARM 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the <arpa/tftp.h> header file. */
+/* #undef HAVE_ARPA_TFTP_H */
+
+/* Define to 1 if you have the <assert.h> header file. */
+#define HAVE_ASSERT_H 1
+
+/* Define to 1 if you have the `basename' function. */
+#define HAVE_BASENAME 1
+
+/* Define to 1 if you have the `closesocket' function. */
+/* #undef HAVE_CLOSESOCKET */
+
+/* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */
+/* #undef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA */
+#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
+
+/* Define to 1 if you have the <crypto.h> header file. */
+/* #undef HAVE_CRYPTO_H */
+#define HAVE_CRYPTO_H 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the <err.h> header file. */
+/* #undef HAVE_ERR_H */
+#define HAVE_ERR_H 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the fcntl function. */
+#define HAVE_FCNTL 1
+
+/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
+#define HAVE_FCNTL_O_NONBLOCK 1
+
+/* Define to 1 if you have the `fork' function. */
+/* #undef HAVE_FORK */
+#define HAVE_FORK 1
+
+/* Define to 1 if you have the `ftruncate' function. */
+#define HAVE_FTRUNCATE 1
+
+/* Define if getaddrinfo exists and works */
+/* #undef HAVE_GETADDRINFO */
+
+/* Define to 1 if you have the `geteuid' function. */
+#define HAVE_GETEUID 1
+
+/* Define to 1 if you have the `gethostbyaddr' function. */
+#define HAVE_GETHOSTBYADDR 1
+
+/* If you have gethostbyname */
+#define HAVE_GETHOSTBYNAME 1
+
+/* Define to 1 if you have the `gethostbyname_r' function. */
+/* #undef HAVE_GETHOSTBYNAME_R */
+
+/* gethostbyname_r() takes 3 args */
+/* #undef HAVE_GETHOSTBYNAME_R_3 */
+
+/* gethostbyname_r() takes 5 args */
+/* #undef HAVE_GETHOSTBYNAME_R_5 */
+
+/* gethostbyname_r() takes 6 args */
+/* #undef HAVE_GETHOSTBYNAME_R_6 1 */
+
+/* Define to 1 if you have the getnameinfo function. */
+/* #undef HAVE_GETNAMEINFO */
+
+/* Define to 1 if you have the `getpass_r' function. */
+/* #undef HAVE_GETPASS_R */
+
+/* Define to 1 if you have the `getprotobyname' function. */
+/* #undef HAVE_GETPROTOBYNAME */
+
+/* Define to 1 if you have the `getpwuid' function. */
+#define HAVE_GETPWUID 1
+
+/* Define to 1 if you have the `getrlimit' function. */
+/* #undef HAVE_GETRLIMIT */
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define HAVE_GETTIMEOFDAY 1
+
+/* we have a glibc-style strerror_r() */
+/* #undef HAVE_GLIBC_STRERROR_R */
+#define HAVE_GLIBC_STRERROR_R 1
+
+/* Define to 1 if you have the `gmtime_r' function. */
+#define HAVE_GMTIME_R 1
+
+/* if you have the gssapi libraries */
+/* #undef HAVE_GSSAPI */
+
+/* if you have the GNU gssapi libraries */
+/* #undef HAVE_GSSGNU */
+
+/* if you have the Heimdal gssapi libraries */
+/* #undef HAVE_GSSHEIMDAL */
+
+/* if you have the MIT gssapi libraries */
+/* #undef HAVE_GSSMIT */
+
+/* Define to 1 if you have the `iconv' functions. */
+#define HAVE_ICONV 1
+
+/* Define to 1 if you have the `idna_strerror' function. */
+/* #undef HAVE_IDNA_STRERROR */
+
+/* Define to 1 if you have the `idn_free' function. */
+/* #undef HAVE_IDN_FREE */
+
+/* Define to 1 if you have the <idn-free.h> header file. */
+/* #undef HAVE_IDN_FREE_H */
+
+/* Define to 1 if you have the `inet_addr' function. */
+#define HAVE_INET_ADDR 1
+
+/* Define to 1 if you have a IPv6 capable working inet_ntop function. */
+/* #undef HAVE_INET_NTOP */
+
+/* Define to 1 if you have a IPv6 capable working inet_pton function. */
+/* #undef HAVE_INET_PTON */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the ioctl function. */
+#define HAVE_IOCTL 1
+
+/* Define to 1 if you have a working ioctl FIONBIO function. */
+#define HAVE_IOCTL_FIONBIO 1
+
+/* Define to 1 if you have the ioctlsocket function. */
+/* #undef HAVE_IOCTLSOCKET */
+
+/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
+/* #undef HAVE_IOCTLSOCKET_FIONBIO */
+
+/* Define to 1 if you have the IoctlSocket camel case function. */
+/* #undef HAVE_IOCTLSOCKET_CAMEL */
+
/* Define to 1 if you have a working IoctlSocket camel case FIONBIO
function. */
-/* #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO */
-
-/* Define to 1 if you have the <io.h> header file. */
-/* #undef HAVE_IO_H */
-
-/* if you have the Kerberos4 libraries (including -ldes) */
-/* #undef HAVE_KRB4 */
-
-/* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */
-/* #undef HAVE_KRB_GET_OUR_IP_FOR_REALM */
-
-/* Define to 1 if you have the <krb.h> header file. */
-/* #undef HAVE_KRB_H */
-
-/* Define to 1 if you have the <libgen.h> header file. */
-/* #undef HAVE_LIBGEN_H 1 */
-
-/* Define to 1 if you have the `idn' library (-lidn). */
-/* #undef HAVE_LIBIDN */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `resolve' library (-lresolve). */
-/* #undef HAVE_LIBRESOLVE */
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* if zlib is available */
-/* #undef HAVE_LIBZ */
-
-/* if your compiler supports LL */
-#define HAVE_LL 1
-
-/* Define to 1 if you have the <locale.h> header file. */
-#define HAVE_LOCALE_H 1
-
-/* Define to 1 if you have the `localtime_r' function. */
-#define HAVE_LOCALTIME_R 1
-
-/* Define to 1 if the compiler supports the 'long long' data type. */
-#define HAVE_LONGLONG 1
-
-/* Define to 1 if you need the malloc.h header file even with stdlib.h */
-/* #undef NEED_MALLOC_H */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
-/* Define to 1 if you have the <netinet/in.h> header file. */
-#define HAVE_NETINET_IN_H 1
-
-/* Define to 1 if you have the <netinet/tcp.h> header file. */
-/* undef HAVE_NETINET_TCP_H */
-
-/* Define to 1 if you have the <net/if.h> header file. */
-#define HAVE_NET_IF_H 1
-
-/* Define if NI_WITHSCOPEID exists and works */
-/* #undef HAVE_NI_WITHSCOPEID */
-
-/* we have no strerror_r() proto */
-/* #undef HAVE_NO_STRERROR_R_DECL */
-
-/* Define to 1 if you have the <openssl/crypto.h> header file. */
-/* #undef HAVE_OPENSSL_CRYPTO_H */
-#define HAVE_OPENSSL_CRYPTO_H 1
-
-/* Define to 1 if you have the <openssl/err.h> header file. */
-/* #undef HAVE_OPENSSL_ERR_H */
-#define HAVE_OPENSSL_ERR_H 1
-
-/* Define to 1 if you have the <openssl/pem.h> header file. */
-/* #undef HAVE_OPENSSL_PEM_H */
-#define HAVE_OPENSSL_PEM_H 1
-
-/* Define to 1 if you have the <openssl/pkcs12.h> header file. */
-/* #undef HAVE_OPENSSL_PKCS12_H */
-#define HAVE_OPENSSL_PKCS12_H 1
-
-/* Define to 1 if you have the <openssl/rsa.h> header file. */
-/* #undef HAVE_OPENSSL_RSA_H */
-#define HAVE_OPENSSL_RSA_H 1
-
-/* Define to 1 if you have the <openssl/ssl.h> header file. */
-/* #undef HAVE_OPENSSL_SSL_H */
-#define HAVE_OPENSSL_SSL_H 1
-
-/* Define to 1 if you have the <openssl/x509.h> header file. */
-/* #undef HAVE_OPENSSL_X509_H */
-#define HAVE_OPENSSL_X509_H 1
-
-/* Define to 1 if you have the <pem.h> header file. */
-/* #undef HAVE_PEM_H */
-#define HAVE_PEM_H 1
-
-/* Define to 1 if you have the `perror' function. */
-#define HAVE_PERROR 1
-
-/* Define to 1 if you have the `pipe' function. */
-#define HAVE_PIPE 1
-
-/* Define to 1 if you have the `poll' function. */
-/* #undef HAVE_POLL */
-
-/* If you have a fine poll */
-/* #undef HAVE_POLL_FINE */
-
-/* we have a POSIX-style strerror_r() */
-/* #undef HAVE_POSIX_STRERROR_R */
-
-/* Define to 1 if you have the <pwd.h> header file. */
-#define HAVE_PWD_H 1
-
-/* Define to 1 if you have the `RAND_egd' function. */
-/* #undef HAVE_RAND_EGD */
-#define HAVE_RAND_EGD 1
-
-/* Define to 1 if you have the `RAND_screen' function. */
-/* #undef HAVE_RAND_SCREEN */
-
-/* Define to 1 if you have the `RAND_status' function. */
-/* #undef HAVE_RAND_STATUS */
-#define HAVE_RAND_STATUS 1
-
-/* Define to 1 if you have the <rsa.h> header file. */
-/* #undef HAVE_RSA_H */
-#define HAVE_RSA_H 1
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define to 1 if you have the <setjmp.h> header file. */
-#define HAVE_SETJMP_H 1
-
-/* Define to 1 if you have the `setlocale' function. */
-#define HAVE_SETLOCALE 1
-
-/* Define to 1 if you have the `setrlimit' function. */
-#define HAVE_SETRLIMIT 1
-
-/* Define to 1 if you have the setsockopt function. */
-/* #undef HAVE_SETSOCKOPT */
-
-/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
-/* #undef HAVE_SETSOCKOPT_SO_NONBLOCK */
-
-/* Define to 1 if you have the <sgtty.h> header file. */
-/* #undef HAVE_SGTTY_H 1 */
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `siginterrupt' function. */
-/* #undef HAVE_SIGINTERRUPT */
-
-/* Define to 1 if you have the `signal' function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if sig_atomic_t is an available typedef. */
-#define HAVE_SIG_ATOMIC_T 1
-
-/* Define to 1 if sig_atomic_t is already defined as volatile. */
-/* #undef HAVE_SIG_ATOMIC_T_VOLATILE */
-
-/* If you have sigsetjmp */
-/* #undef HAVE_SIGSETJMP */
-
-/* Define to 1 if you have the `socket' function. */
-#define HAVE_SOCKET 1
-
-/* Define to 1 if you have the <ssl.h> header file. */
-/* #undef HAVE_SSL_H */
-#define HAVE_SSL_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the `strcasecmp' function. */
-#define HAVE_STRCASECMP 1
-
-/* Define to 1 if you have the `strcmpi' function. */
-/* #undef HAVE_STRCMPI */
-
-/* Define to 1 if you have the `strdup' function. */
-#define HAVE_STRDUP 1
-
-/* Define to 1 if you have the `strerror_r' function. */
-#define HAVE_STRERROR_R 1
-
-/* Define to 1 if you have the `stricmp' function. */
-/* #undef HAVE_STRICMP */
-#define HAVE_STRICMP 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef HAVE_STRLCPY */
-
-/* Define to 1 if you have the `strstr' function. */
-#define HAVE_STRSTR 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* if struct sockaddr_storage is defined */
-/* #undef HAVE_STRUCT_SOCKADDR_STORAGE */
-
-/* Define this if you have struct timeval */
-#define HAVE_STRUCT_TIMEVAL 1
-
-/* Define to 1 if you have the <sys/filio.h> header file. */
-#define HAVE_SYS_FILIO_H 1
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/poll.h> header file. */
-/* #undef HAVE_SYS_POLL_H */
-
-/* Define to 1 if you have the <sys/resource.h> header file. */
-#define HAVE_SYS_RESOURCE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/sockio.h> header file. */
-/* #undef HAVE_SYS_SOCKIO_H */
-#define HAVE_SYS_SOCKIO_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <sys/utime.h> header file. */
-/* #undef HAVE_SYS_UTIME_H */
-
-/* Define to 1 if you have the <termios.h> header file. */
-/* #undef HAVE_TERMIOS_H */
-
-/* Define to 1 if you have the <termio.h> header file. */
-/* #undef HAVE_TERMIO_H */
-
-/* Define to 1 if you have the <time.h> header file. */
-#define HAVE_TIME_H 1
-
-/* Define to 1 if you have the <tld.h> header file. */
-/* #undef HAVE_TLD_H */
-
-/* Define to 1 if you have the `tld_strerror' function. */
-/* #undef HAVE_TLD_STRERROR */
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `utime' function. */
-#define HAVE_UTIME 1
-
-/* Define to 1 if you have the <utime.h> header file. */
-#define HAVE_UTIME_H 1
-
-/* Define to 1 if you have the <winsock2.h> header file. */
-/* #undef HAVE_WINSOCK2_H */
-
-/* Define to 1 if you have the <winsock.h> header file. */
-/* #undef HAVE_WINSOCK_H */
-
-/* Define this symbol if your OS supports changing the contents of argv */
-/* #undef HAVE_WRITABLE_ARGV */
-
-/* Define to 1 if you have the ws2tcpip.h header file. */
-/* #undef HAVE_WS2TCPIP_H */
-
-/* Define to 1 if you have the <x509.h> header file. */
-/* #undef HAVE_X509_H */
-
-/* if you have the zlib.h header file */
-/* #undef HAVE_ZLIB_H */
-
-/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
-/* #undef NEED_REENTRANT */
-
-/* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */
-/* #undef NEED_THREAD_SAFE */
-
-/* cpu-machine-OS */
-#define OS "s390x-ibm-tpf"
-
-/* Name of package */
-#define PACKAGE "curl"
-
-/* Define to the address where bug reports for this package should be sent. */
+/* #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO */
+
+/* Define to 1 if you have the <io.h> header file. */
+/* #undef HAVE_IO_H */
+
+/* if you have the Kerberos4 libraries (including -ldes) */
+/* #undef HAVE_KRB4 */
+
+/* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */
+/* #undef HAVE_KRB_GET_OUR_IP_FOR_REALM */
+
+/* Define to 1 if you have the <krb.h> header file. */
+/* #undef HAVE_KRB_H */
+
+/* Define to 1 if you have the <libgen.h> header file. */
+/* #undef HAVE_LIBGEN_H 1 */
+
+/* Define to 1 if you have the `idn' library (-lidn). */
+/* #undef HAVE_LIBIDN */
+
+/* Define to 1 if you have the `resolv' library (-lresolv). */
+/* #undef HAVE_LIBRESOLV */
+
+/* Define to 1 if you have the `resolve' library (-lresolve). */
+/* #undef HAVE_LIBRESOLVE */
+
+/* Define to 1 if you have the `socket' library (-lsocket). */
+/* #undef HAVE_LIBSOCKET */
+
+/* if zlib is available */
+/* #undef HAVE_LIBZ */
+
+/* if your compiler supports LL */
+#define HAVE_LL 1
+
+/* Define to 1 if you have the <locale.h> header file. */
+#define HAVE_LOCALE_H 1
+
+/* Define to 1 if you have the `localtime_r' function. */
+#define HAVE_LOCALTIME_R 1
+
+/* Define to 1 if the compiler supports the 'long long' data type. */
+#define HAVE_LONGLONG 1
+
+/* Define to 1 if you need the malloc.h header file even with stdlib.h */
+/* #undef NEED_MALLOC_H */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+/* undef HAVE_NETINET_TCP_H */
+
+/* Define to 1 if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H 1
+
+/* Define if NI_WITHSCOPEID exists and works */
+/* #undef HAVE_NI_WITHSCOPEID */
+
+/* we have no strerror_r() proto */
+/* #undef HAVE_NO_STRERROR_R_DECL */
+
+/* Define to 1 if you have the <openssl/crypto.h> header file. */
+/* #undef HAVE_OPENSSL_CRYPTO_H */
+#define HAVE_OPENSSL_CRYPTO_H 1
+
+/* Define to 1 if you have the <openssl/err.h> header file. */
+/* #undef HAVE_OPENSSL_ERR_H */
+#define HAVE_OPENSSL_ERR_H 1
+
+/* Define to 1 if you have the <openssl/pem.h> header file. */
+/* #undef HAVE_OPENSSL_PEM_H */
+#define HAVE_OPENSSL_PEM_H 1
+
+/* Define to 1 if you have the <openssl/pkcs12.h> header file. */
+/* #undef HAVE_OPENSSL_PKCS12_H */
+#define HAVE_OPENSSL_PKCS12_H 1
+
+/* Define to 1 if you have the <openssl/rsa.h> header file. */
+/* #undef HAVE_OPENSSL_RSA_H */
+#define HAVE_OPENSSL_RSA_H 1
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+/* #undef HAVE_OPENSSL_SSL_H */
+#define HAVE_OPENSSL_SSL_H 1
+
+/* Define to 1 if you have the <openssl/x509.h> header file. */
+/* #undef HAVE_OPENSSL_X509_H */
+#define HAVE_OPENSSL_X509_H 1
+
+/* Define to 1 if you have the <pem.h> header file. */
+/* #undef HAVE_PEM_H */
+#define HAVE_PEM_H 1
+
+/* Define to 1 if you have the `perror' function. */
+#define HAVE_PERROR 1
+
+/* Define to 1 if you have the `pipe' function. */
+#define HAVE_PIPE 1
+
+/* Define to 1 if you have the `poll' function. */
+/* #undef HAVE_POLL */
+
+/* If you have a fine poll */
+/* #undef HAVE_POLL_FINE */
+
+/* we have a POSIX-style strerror_r() */
+/* #undef HAVE_POSIX_STRERROR_R */
+
+/* Define to 1 if you have the <pwd.h> header file. */
+#define HAVE_PWD_H 1
+
+/* Define to 1 if you have the `RAND_egd' function. */
+/* #undef HAVE_RAND_EGD */
+#define HAVE_RAND_EGD 1
+
+/* Define to 1 if you have the `RAND_screen' function. */
+/* #undef HAVE_RAND_SCREEN */
+
+/* Define to 1 if you have the `RAND_status' function. */
+/* #undef HAVE_RAND_STATUS */
+#define HAVE_RAND_STATUS 1
+
+/* Define to 1 if you have the <rsa.h> header file. */
+/* #undef HAVE_RSA_H */
+#define HAVE_RSA_H 1
+
+/* Define to 1 if you have the `select' function. */
+#define HAVE_SELECT 1
+
+/* Define to 1 if you have the <setjmp.h> header file. */
+#define HAVE_SETJMP_H 1
+
+/* Define to 1 if you have the `setlocale' function. */
+#define HAVE_SETLOCALE 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the setsockopt function. */
+/* #undef HAVE_SETSOCKOPT */
+
+/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
+/* #undef HAVE_SETSOCKOPT_SO_NONBLOCK */
+
+/* Define to 1 if you have the <sgtty.h> header file. */
+/* #undef HAVE_SGTTY_H 1 */
+
+/* Define to 1 if you have the `sigaction' function. */
+#define HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `siginterrupt' function. */
+/* #undef HAVE_SIGINTERRUPT */
+
+/* Define to 1 if you have the `signal' function. */
+#define HAVE_SIGNAL 1
+
+/* Define to 1 if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* Define to 1 if sig_atomic_t is an available typedef. */
+#define HAVE_SIG_ATOMIC_T 1
+
+/* Define to 1 if sig_atomic_t is already defined as volatile. */
+/* #undef HAVE_SIG_ATOMIC_T_VOLATILE */
+
+/* If you have sigsetjmp */
+/* #undef HAVE_SIGSETJMP */
+
+/* Define to 1 if you have the `socket' function. */
+#define HAVE_SOCKET 1
+
+/* Define to 1 if you have the <ssl.h> header file. */
+/* #undef HAVE_SSL_H */
+#define HAVE_SSL_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the `strcasecmp' function. */
+#define HAVE_STRCASECMP 1
+
+/* Define to 1 if you have the `strcmpi' function. */
+/* #undef HAVE_STRCMPI */
+
+/* Define to 1 if you have the `strdup' function. */
+#define HAVE_STRDUP 1
+
+/* Define to 1 if you have the `strerror_r' function. */
+#define HAVE_STRERROR_R 1
+
+/* Define to 1 if you have the `stricmp' function. */
+/* #undef HAVE_STRICMP */
+#define HAVE_STRICMP 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+/* #undef HAVE_STRLCPY */
+
+/* Define to 1 if you have the `strstr' function. */
+#define HAVE_STRSTR 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#define HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#define HAVE_STRTOLL 1
+
+/* if struct sockaddr_storage is defined */
+/* #undef HAVE_STRUCT_SOCKADDR_STORAGE */
+
+/* Define this if you have struct timeval */
+#define HAVE_STRUCT_TIMEVAL 1
+
+/* Define to 1 if you have the <sys/filio.h> header file. */
+#define HAVE_SYS_FILIO_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/poll.h> header file. */
+/* #undef HAVE_SYS_POLL_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/sockio.h> header file. */
+/* #undef HAVE_SYS_SOCKIO_H */
+#define HAVE_SYS_SOCKIO_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/utime.h> header file. */
+/* #undef HAVE_SYS_UTIME_H */
+
+/* Define to 1 if you have the <termios.h> header file. */
+/* #undef HAVE_TERMIOS_H */
+
+/* Define to 1 if you have the <termio.h> header file. */
+/* #undef HAVE_TERMIO_H */
+
+/* Define to 1 if you have the <time.h> header file. */
+#define HAVE_TIME_H 1
+
+/* Define to 1 if you have the <tld.h> header file. */
+/* #undef HAVE_TLD_H */
+
+/* Define to 1 if you have the `tld_strerror' function. */
+/* #undef HAVE_TLD_STRERROR */
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `utime' function. */
+#define HAVE_UTIME 1
+
+/* Define to 1 if you have the <utime.h> header file. */
+#define HAVE_UTIME_H 1
+
+/* Define to 1 if you have the <winsock2.h> header file. */
+/* #undef HAVE_WINSOCK2_H */
+
+/* Define to 1 if you have the <winsock.h> header file. */
+/* #undef HAVE_WINSOCK_H */
+
+/* Define this symbol if your OS supports changing the contents of argv */
+/* #undef HAVE_WRITABLE_ARGV */
+
+/* Define to 1 if you have the ws2tcpip.h header file. */
+/* #undef HAVE_WS2TCPIP_H */
+
+/* Define to 1 if you have the <x509.h> header file. */
+/* #undef HAVE_X509_H */
+
+/* if you have the zlib.h header file */
+/* #undef HAVE_ZLIB_H */
+
+/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
+/* #undef NEED_REENTRANT */
+
+/* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */
+/* #undef NEED_THREAD_SAFE */
+
+/* cpu-machine-OS */
+#define OS "s390x-ibm-tpf"
+
+/* Name of package */
+#define PACKAGE "curl"
+
+/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT \
"a suitable curl mailing list => https://curl.se/mail/"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "curl"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "curl -"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "curl"
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "-"
-
-/* a suitable file to read random data from */
-/* #undef RANDOM_FILE */
-
-/* Define as the return type of signal handlers (`int' or `void'). */
-#define RETSIGTYPE void
-
-/* Define to the type of arg 1 for `select'. */
-#define SELECT_TYPE_ARG1 int
-
-/* Define to the type of args 2, 3 and 4 for `select'. */
-#define SELECT_TYPE_ARG234 (fd_set *)
-
-/* Define to the type of arg 5 for `select'. */
-#define SELECT_TYPE_ARG5 (struct timeval *)
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `off_t', as computed by sizeof. */
-#define SIZEOF_OFF_T 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "curl"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "curl -"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "curl"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "-"
+
+/* a suitable file to read random data from */
+/* #undef RANDOM_FILE */
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#define RETSIGTYPE void
+
+/* Define to the type of arg 1 for `select'. */
+#define SELECT_TYPE_ARG1 int
+
+/* Define to the type of args 2, 3 and 4 for `select'. */
+#define SELECT_TYPE_ARG234 (fd_set *)
+
+/* Define to the type of arg 5 for `select'. */
+#define SELECT_TYPE_ARG5 (struct timeval *)
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `off_t', as computed by sizeof. */
+#define SIZEOF_OFF_T 8
+
+/* The size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
/* Define to the size of `long', as computed by sizeof. */
#define SIZEOF_LONG 8
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 8
-
-/* The size of `time_t', as computed by sizeof. */
-#define SIZEOF_TIME_T 8
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Define if you want to enable ares support */
-/* #undef USE_ARES */
-
-/* Define to disable non-blocking sockets */
-/* #undef USE_BLOCKING_SOCKETS */
-
-/* if GnuTLS is enabled */
-/* #undef USE_GNUTLS */
-
-/* If you want to build curl with the built-in manual */
-/* #undef USE_MANUAL */
-
-/* if OpenSSL is in use */
-/* #undef USE_OPENSSL */
-
-/* if SSL is enabled */
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* The size of `time_t', as computed by sizeof. */
+#define SIZEOF_TIME_T 8
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME 1
+
+/* Define if you want to enable ares support */
+/* #undef USE_ARES */
+
+/* Define to disable non-blocking sockets */
+/* #undef USE_BLOCKING_SOCKETS */
+
+/* if GnuTLS is enabled */
+/* #undef USE_GNUTLS */
+
+/* If you want to build curl with the built-in manual */
+/* #undef USE_MANUAL */
+
+/* if OpenSSL is in use */
+/* #undef USE_OPENSSL */
+
+/* if SSL is enabled */
/* #undef USE_OPENSSL */
-
-/* to enable SSPI support */
-/* #undef USE_WINDOWS_SSPI */
-
-/* Version number of package */
-#define VERSION "not-used"
-
-/* Define to avoid automatic inclusion of winsock.h */
-/* #undef WIN32_LEAN_AND_MEAN */
-
-/* Define to 1 if on AIX 3.
- System headers sometimes define this.
- We just want to avoid a redefinition error message. */
-#ifndef _ALL_SOURCE
-/* # undef _ALL_SOURCE */
-#endif
-
-/* Number of bits in a file offset, on hosts where this is settable. */
-/* #undef _FILE_OFFSET_BITS */
-
-/* Define for large files, on AIX-style hosts. */
-/* #undef _LARGE_FILES */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* type to use in place of in_addr_t if not defined */
-/* #undef in_addr_t */
-
-/* Define to `unsigned' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* the signed version of size_t */
-/* #undef ssize_t */
-
-/* Define to 1 if you have the getnameinfo function. */
-/* #undef HAVE_GETNAMEINFO 1 */
-
-/* Define to the type qualifier of arg 1 for getnameinfo. */
-/* #undef GETNAMEINFO_QUAL_ARG1 const */
-
-/* Define to the type of arg 1 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG1 struct sockaddr * */
-
-/* Define to the type of arg 2 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG2 socklen_t */
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG46 size_t */
-
-/* Define to the type of arg 7 for getnameinfo. */
-/* #undef GETNAMEINFO_TYPE_ARG7 int */
-
-/* Define to 1 if you have the recv function. */
-#define HAVE_RECV 1
-
-/* Define to the type of arg 1 for recv. */
-#define RECV_TYPE_ARG1 int
-
-/* Define to the type of arg 2 for recv. */
-#define RECV_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for recv. */
-#define RECV_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recv. */
-#define RECV_TYPE_ARG4 int
-
-/* Define to the function return type for recv. */
-#define RECV_TYPE_RETV int
-
-/* Define to 1 if you have the recvfrom function. */
-#define HAVE_RECVFROM 1
-
-/* Define to the type of arg 1 for recvfrom. */
-#define RECVFROM_TYPE_ARG1 int
-
-/* Define to the type pointed by arg 2 for recvfrom. */
-#define RECVFROM_TYPE_ARG2 char
-
-/* Define to the type of arg 3 for recvfrom. */
-#define RECVFROM_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recvfrom. */
-#define RECVFROM_TYPE_ARG4 int
-
-/* Define to the type pointed by arg 5 for recvfrom. */
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-
-/* Define to the type pointed by arg 6 for recvfrom. */
-#define RECVFROM_TYPE_ARG6 int
-
-/* Define to the function return type for recvfrom. */
-#define RECVFROM_TYPE_RETV int
-
-/* Define to 1 if you have the send function. */
-#define HAVE_SEND 1
-
-/* Define to the type of arg 1 for send. */
-#define SEND_TYPE_ARG1 int
-
-/* Define to the type qualifier of arg 2 for send. */
-#define SEND_QUAL_ARG2 const
-
-/* Define to the type of arg 2 for send. */
-#define SEND_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for send. */
-#define SEND_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for send. */
-#define SEND_TYPE_ARG4 int
-
-/* Define to the function return type for send. */
-#define SEND_TYPE_RETV int
-
-#define CURL_DOES_CONVERSIONS
-#ifndef CURL_ICONV_CODESET_OF_HOST
-#define CURL_ICONV_CODESET_OF_HOST "IBM-1047"
-#endif
-
-
-#endif /* HEADER_CURL_CONFIG_TPF_H */
+
+/* to enable SSPI support */
+/* #undef USE_WINDOWS_SSPI */
+
+/* Version number of package */
+#define VERSION "not-used"
+
+/* Define to avoid automatic inclusion of winsock.h */
+/* #undef WIN32_LEAN_AND_MEAN */
+
+/* Define to 1 if on AIX 3.
+ System headers sometimes define this.
+ We just want to avoid a redefinition error message. */
+#ifndef _ALL_SOURCE
+/* # undef _ALL_SOURCE */
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* type to use in place of in_addr_t if not defined */
+/* #undef in_addr_t */
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* the signed version of size_t */
+/* #undef ssize_t */
+
+/* Define to 1 if you have the getnameinfo function. */
+/* #undef HAVE_GETNAMEINFO 1 */
+
+/* Define to the type qualifier of arg 1 for getnameinfo. */
+/* #undef GETNAMEINFO_QUAL_ARG1 const */
+
+/* Define to the type of arg 1 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG1 struct sockaddr * */
+
+/* Define to the type of arg 2 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG2 socklen_t */
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG46 size_t */
+
+/* Define to the type of arg 7 for getnameinfo. */
+/* #undef GETNAMEINFO_TYPE_ARG7 int */
+
+/* Define to 1 if you have the recv function. */
+#define HAVE_RECV 1
+
+/* Define to the type of arg 1 for recv. */
+#define RECV_TYPE_ARG1 int
+
+/* Define to the type of arg 2 for recv. */
+#define RECV_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for recv. */
+#define RECV_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recv. */
+#define RECV_TYPE_ARG4 int
+
+/* Define to the function return type for recv. */
+#define RECV_TYPE_RETV int
+
+/* Define to 1 if you have the recvfrom function. */
+#define HAVE_RECVFROM 1
+
+/* Define to the type of arg 1 for recvfrom. */
+#define RECVFROM_TYPE_ARG1 int
+
+/* Define to the type pointed by arg 2 for recvfrom. */
+#define RECVFROM_TYPE_ARG2 char
+
+/* Define to the type of arg 3 for recvfrom. */
+#define RECVFROM_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recvfrom. */
+#define RECVFROM_TYPE_ARG4 int
+
+/* Define to the type pointed by arg 5 for recvfrom. */
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+
+/* Define to the type pointed by arg 6 for recvfrom. */
+#define RECVFROM_TYPE_ARG6 int
+
+/* Define to the function return type for recvfrom. */
+#define RECVFROM_TYPE_RETV int
+
+/* Define to 1 if you have the send function. */
+#define HAVE_SEND 1
+
+/* Define to the type of arg 1 for send. */
+#define SEND_TYPE_ARG1 int
+
+/* Define to the type qualifier of arg 2 for send. */
+#define SEND_QUAL_ARG2 const
+
+/* Define to the type of arg 2 for send. */
+#define SEND_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for send. */
+#define SEND_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for send. */
+#define SEND_TYPE_ARG4 int
+
+/* Define to the function return type for send. */
+#define SEND_TYPE_RETV int
+
+#define CURL_DOES_CONVERSIONS
+#ifndef CURL_ICONV_CODESET_OF_HOST
+#define CURL_ICONV_CODESET_OF_HOST "IBM-1047"
+#endif
+
+
+#endif /* HEADER_CURL_CONFIG_TPF_H */
diff --git a/contrib/libs/curl/lib/config-vxworks.h b/contrib/libs/curl/lib/config-vxworks.h
index 48181007ae..73edd530b4 100644
--- a/contrib/libs/curl/lib/config-vxworks.h
+++ b/contrib/libs/curl/lib/config-vxworks.h
@@ -1,904 +1,904 @@
-#ifndef HEADER_CURL_CONFIG_VXWORKS_H
-#define HEADER_CURL_CONFIG_VXWORKS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_VXWORKS_H
+#define HEADER_CURL_CONFIG_VXWORKS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* =============================================================== */
-/* Hand crafted config file for VxWorks */
-/* =============================================================== */
-
-/* Location of default ca bundle */
-/* #undef CURL_CA_BUNDLE */
-
-/* Location of default ca path */
-/* #undef CURL_CA_PATH */
-
-/* to disable cookies support */
-/* #undef CURL_DISABLE_COOKIES */
-
-/* to disable cryptographic authentication */
-/* #undef CURL_DISABLE_CRYPTO_AUTH */
-
-/* to disable DICT */
-/* #undef CURL_DISABLE_DICT */
-
-/* to disable FILE */
-/* #undef CURL_DISABLE_FILE */
-
-/* to disable FTP */
-#define CURL_DISABLE_FTP 1
-
-/* to disable HTTP */
-/* #undef CURL_DISABLE_HTTP */
-
-/* to disable LDAP */
-#define CURL_DISABLE_LDAP 1
-
-/* to disable LDAPS */
-#define CURL_DISABLE_LDAPS 1
-
-/* to disable NTLM authentication */
-#define CURL_DISABLE_NTLM 1
-
-/* to disable proxies */
-/* #undef CURL_DISABLE_PROXY */
-
-/* to disable TELNET */
-#define CURL_DISABLE_TELNET 1
-
-/* to disable TFTP */
-#define CURL_DISABLE_TFTP 1
-
-/* to disable verbose strings */
-/* #undef CURL_DISABLE_VERBOSE_STRINGS */
-
-/* Definition to make a library symbol externally visible. */
-/* #undef CURL_EXTERN_SYMBOL */
-
-/* Use Windows LDAP implementation */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* =============================================================== */
+/* Hand crafted config file for VxWorks */
+/* =============================================================== */
+
+/* Location of default ca bundle */
+/* #undef CURL_CA_BUNDLE */
+
+/* Location of default ca path */
+/* #undef CURL_CA_PATH */
+
+/* to disable cookies support */
+/* #undef CURL_DISABLE_COOKIES */
+
+/* to disable cryptographic authentication */
+/* #undef CURL_DISABLE_CRYPTO_AUTH */
+
+/* to disable DICT */
+/* #undef CURL_DISABLE_DICT */
+
+/* to disable FILE */
+/* #undef CURL_DISABLE_FILE */
+
+/* to disable FTP */
+#define CURL_DISABLE_FTP 1
+
+/* to disable HTTP */
+/* #undef CURL_DISABLE_HTTP */
+
+/* to disable LDAP */
+#define CURL_DISABLE_LDAP 1
+
+/* to disable LDAPS */
+#define CURL_DISABLE_LDAPS 1
+
+/* to disable NTLM authentication */
+#define CURL_DISABLE_NTLM 1
+
+/* to disable proxies */
+/* #undef CURL_DISABLE_PROXY */
+
+/* to disable TELNET */
+#define CURL_DISABLE_TELNET 1
+
+/* to disable TFTP */
+#define CURL_DISABLE_TFTP 1
+
+/* to disable verbose strings */
+/* #undef CURL_DISABLE_VERBOSE_STRINGS */
+
+/* Definition to make a library symbol externally visible. */
+/* #undef CURL_EXTERN_SYMBOL */
+
+/* Use Windows LDAP implementation */
/* #undef USE_WIN32_LDAP */
-
-/* your Entropy Gathering Daemon socket pathname */
-/* #undef EGD_SOCKET */
-
-/* Define if you want to enable IPv6 support */
-#define ENABLE_IPV6 1
-
-/* Define to the type qualifier of arg 1 for getnameinfo. */
-#define GETNAMEINFO_QUAL_ARG1 const
-
-/* Define to the type of arg 1 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-
-/* Define to the type of arg 2 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG2 socklen_t
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG46 size_t
-
-/* Define to the type of arg 7 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG7 unsigned int
-
-/* Specifies the number of arguments to getservbyport_r */
-#define GETSERVBYPORT_R_ARGS 6
-
-/* Specifies the size of the buffer to pass to getservbyport_r */
-#define GETSERVBYPORT_R_BUFSIZE 4096
-
-/* Define to 1 if you have the alarm function. */
-#define HAVE_ALARM 1
-
-/* Define to 1 if you have the <alloca.h> header file. */
-#define HAVE_ALLOCA_H 1
-
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#define HAVE_ARPA_INET_H 1
-
-/* Define to 1 if you have the <arpa/tftp.h> header file. */
-/* #undef HAVE_ARPA_TFTP_H */
-
-/* Define to 1 if you have the <assert.h> header file. */
-#define HAVE_ASSERT_H 1
-
-/* Define to 1 if you have the `basename' function. */
-/* #undef HAVE_BASENAME */
-
-/* Define to 1 if bool is an available type. */
-#define HAVE_BOOL_T 1
-
-/* Define to 1 if you have the clock_gettime function and monotonic timer. */
-/* #undef HAVE_CLOCK_GETTIME_MONOTONIC */
-
-/* Define to 1 if you have the `closesocket' function. */
-/* #undef HAVE_CLOSESOCKET */
-
-/* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */
-#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
-
-/* Define to 1 if you have the <crypto.h> header file. */
-/* #undef HAVE_CRYPTO_H */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define to 1 if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H 1
-
-/* Define to 1 if you have the <err.h> header file. */
-/* #undef HAVE_ERR_H */
-
-/* Define to 1 if you have the fcntl function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
-#define HAVE_FCNTL_O_NONBLOCK 1
-
-/* Define to 1 if you have the `fork' function. */
-#define HAVE_FORK 1
-
-/* Define to 1 if you have the freeaddrinfo function. */
-#define HAVE_FREEADDRINFO 1
-
-/* Define to 1 if you have the freeifaddrs function. */
-#define HAVE_FREEIFADDRS 1
-
-/* Define to 1 if you have the ftruncate function. */
-#define HAVE_FTRUNCATE 1
-
-/* Define to 1 if you have a working getaddrinfo function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `geteuid' function. */
-/* #undef HAVE_GETEUID */
-
-/* Define to 1 if you have the gethostbyaddr function. */
-#define HAVE_GETHOSTBYADDR 1
-
-/* Define to 1 if you have the gethostbyaddr_r function. */
-#define HAVE_GETHOSTBYADDR_R 1
-
-/* gethostbyaddr_r() takes 5 args */
-/* #undef HAVE_GETHOSTBYADDR_R_5 */
-
-/* gethostbyaddr_r() takes 7 args */
-/* #undef HAVE_GETHOSTBYADDR_R_7 */
-
-/* gethostbyaddr_r() takes 8 args */
-#define HAVE_GETHOSTBYADDR_R_8 1
-
-/* Define to 1 if you have the gethostbyname function. */
-#define HAVE_GETHOSTBYNAME 1
-
-/* Define to 1 if you have the gethostbyname_r function. */
-/* #undef HAVE_GETHOSTBYNAME_R */
-
-/* gethostbyname_r() takes 3 args */
-/* #undef HAVE_GETHOSTBYNAME_R_3 */
-
-/* gethostbyname_r() takes 5 args */
-/* #undef HAVE_GETHOSTBYNAME_R_5 */
-
-/* gethostbyname_r() takes 6 args */
-/* #undef HAVE_GETHOSTBYNAME_R_6 */
-
-/* Define to 1 if you have the gethostname function. */
-#define HAVE_GETHOSTNAME 1
-
-/* Define to 1 if you have a working getifaddrs function. */
-/* #undef HAVE_GETIFADDRS */
-
-/* Define to 1 if you have the getnameinfo function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `getpass_r' function. */
-/* #undef HAVE_GETPASS_R */
-
-/* Define to 1 if you have the `getppid' function. */
-#define HAVE_GETPPID 1
-
-/* Define to 1 if you have the `getprotobyname' function. */
-#define HAVE_GETPROTOBYNAME 1
-
-/* Define to 1 if you have the `getpwuid' function. */
-/* #undef HAVE_GETPWUID */
-
-/* Define to 1 if you have the `getrlimit' function. */
-#define HAVE_GETRLIMIT 1
-
-/* Define to 1 if you have the getservbyport_r function. */
-/* #undef HAVE_GETSERVBYPORT_R */
-
-/* Define to 1 if you have the `gettimeofday' function. */
-/* #undef HAVE_GETTIMEOFDAY */
-
-/* Define to 1 if you have a working glibc-style strerror_r function. */
-/* #undef HAVE_GLIBC_STRERROR_R */
-
-/* Define to 1 if you have a working gmtime_r function. */
-#define HAVE_GMTIME_R 1
-
-/* if you have the gssapi libraries */
-/* #undef HAVE_GSSAPI */
-
-/* Define to 1 if you have the <gssapi/gssapi_generic.h> header file. */
-/* #undef HAVE_GSSAPI_GSSAPI_GENERIC_H */
-
-/* Define to 1 if you have the <gssapi/gssapi.h> header file. */
-/* #undef HAVE_GSSAPI_GSSAPI_H */
-
-/* Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. */
-/* #undef HAVE_GSSAPI_GSSAPI_KRB5_H */
-
-/* if you have the GNU gssapi libraries */
-/* #undef HAVE_GSSGNU */
-
-/* if you have the Heimdal gssapi libraries */
-/* #undef HAVE_GSSHEIMDAL */
-
-/* if you have the MIT gssapi libraries */
-/* #undef HAVE_GSSMIT */
-
-/* Define to 1 if you have the `idna_strerror' function. */
-/* #undef HAVE_IDNA_STRERROR */
-
-/* Define to 1 if you have the `idn_free' function. */
-/* #undef HAVE_IDN_FREE */
-
-/* Define to 1 if you have the <idn-free.h> header file. */
-/* #undef HAVE_IDN_FREE_H */
-
-/* Define to 1 if you have the <ifaddrs.h> header file. */
-/* #undef HAVE_IFADDRS_H */
-
-/* Define to 1 if you have the `inet_addr' function. */
-#define HAVE_INET_ADDR 1
-
-/* Define to 1 if you have the inet_ntoa_r function. */
-/* #undef HAVE_INET_NTOA_R */
-
-/* inet_ntoa_r() takes 2 args */
-/* #undef HAVE_INET_NTOA_R_2 */
-
-/* inet_ntoa_r() takes 3 args */
-/* #undef HAVE_INET_NTOA_R_3 */
-
-/* Define to 1 if you have a IPv6 capable working inet_ntop function. */
-/* #undef HAVE_INET_NTOP */
-
-/* Define to 1 if you have a IPv6 capable working inet_pton function. */
-/* #undef HAVE_INET_PTON */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the ioctl function. */
-#define HAVE_IOCTL 1
-
-/* Define to 1 if you have the ioctlsocket function. */
-/* #undef HAVE_IOCTLSOCKET */
-
-/* Define to 1 if you have the IoctlSocket camel case function. */
-/* #undef HAVE_IOCTLSOCKET_CAMEL */
-
-/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
- */
-/* #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO */
-
-/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
-/* #undef HAVE_IOCTLSOCKET_FIONBIO */
-
-/* Define to 1 if you have a working ioctl FIONBIO function. */
-#define HAVE_IOCTL_FIONBIO 1
-
-/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */
-#define HAVE_IOCTL_SIOCGIFADDR 1
-
-/* Define to 1 if you have the <io.h> header file. */
-#define HAVE_IO_H 1
-
-/* if you have the Kerberos4 libraries (including -ldes) */
-/* #undef HAVE_KRB4 */
-
-/* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */
-/* #undef HAVE_KRB_GET_OUR_IP_FOR_REALM */
-
-/* Define to 1 if you have the <krb.h> header file. */
-/* #undef HAVE_KRB_H */
-
-/* Define to 1 if you have the lber.h header file. */
-/* #undef HAVE_LBER_H */
-
-/* Define to 1 if you have the ldapssl.h header file. */
-/* #undef HAVE_LDAPSSL_H */
-
-/* Define to 1 if you have the ldap.h header file. */
-/* #undef HAVE_LDAP_H */
-
-/* Use LDAPS implementation */
-/* #undef HAVE_LDAP_SSL */
-
-/* Define to 1 if you have the ldap_ssl.h header file. */
-/* #undef HAVE_LDAP_SSL_H */
-
-/* Define to 1 if you have the `ldap_url_parse' function. */
-/* #undef HAVE_LDAP_URL_PARSE */
-
-/* Define to 1 if you have the <libgen.h> header file. */
-/* #undef HAVE_LIBGEN_H */
-
-/* Define to 1 if you have the `idn' library (-lidn). */
-/* #undef HAVE_LIBIDN */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `resolve' library (-lresolve). */
-/* #undef HAVE_LIBRESOLVE */
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the `ssh2' library (-lssh2). */
-/* #undef HAVE_LIBSSH2 */
-
-/* Define to 1 if you have the <libssh2.h> header file. */
-/* #undef HAVE_LIBSSH2_H */
-
-/* Define to 1 if you have the `libssh2_version' function. */
-/* #undef HAVE_LIBSSH2_VERSION */
-
-/* if zlib is available */
-#define HAVE_LIBZ 1
-
-/* if your compiler supports LL */
-#define HAVE_LL 1
-
-/* Define to 1 if you have the <locale.h> header file. */
-#define HAVE_LOCALE_H 1
-
-/* Define to 1 if you have a working localtime_r function. */
-#define HAVE_LOCALTIME_R 1
-
-/* Define to 1 if the compiler supports the 'long long' data type. */
-#define HAVE_LONGLONG 1
-
-/* Define to 1 if you have the malloc.h header file. */
-#define HAVE_MALLOC_H 1
-
-/* Define to 1 if you have the memory.h header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the MSG_NOSIGNAL flag. */
-/* #undef HAVE_MSG_NOSIGNAL */
-
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
-/* Define to 1 if you have the <netinet/in.h> header file. */
-#define HAVE_NETINET_IN_H 1
-
-/* Define to 1 if you have the <netinet/tcp.h> header file. */
-#define HAVE_NETINET_TCP_H 1
-
-/* Define to 1 if you have the <net/if.h> header file. */
-#define HAVE_NET_IF_H 1
-
-/* Define to 1 if NI_WITHSCOPEID exists and works. */
-/* #undef HAVE_NI_WITHSCOPEID */
-
-/* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE
- */
-/* #undef HAVE_OLD_GSSMIT */
-
-/* Define to 1 if you have the <openssl/crypto.h> header file. */
-#define HAVE_OPENSSL_CRYPTO_H 1
-
-/* Define to 1 if you have the <openssl/err.h> header file. */
-#define HAVE_OPENSSL_ERR_H 1
-
-/* Define to 1 if you have the <openssl/pem.h> header file. */
-#define HAVE_OPENSSL_PEM_H 1
-
-/* Define to 1 if you have the <openssl/pkcs12.h> header file. */
-#define HAVE_OPENSSL_PKCS12_H 1
-
-/* Define to 1 if you have the <openssl/rsa.h> header file. */
-#define HAVE_OPENSSL_RSA_H 1
-
-/* Define to 1 if you have the <openssl/ssl.h> header file. */
-#define HAVE_OPENSSL_SSL_H 1
-
-/* Define to 1 if you have the <openssl/x509.h> header file. */
-#define HAVE_OPENSSL_X509_H 1
-
-/* Define to 1 if you have the <pem.h> header file. */
-/* #undef HAVE_PEM_H */
-
-/* Define to 1 if you have the `perror' function. */
-#define HAVE_PERROR 1
-
-/* Define to 1 if you have the `pipe' function. */
-#define HAVE_PIPE 1
-
-/* Define to 1 if you have a working poll function. */
-/* #undef HAVE_POLL */
-
-/* If you have a fine poll */
-/* #undef HAVE_POLL_FINE */
-
-/* Define to 1 if you have the <poll.h> header file. */
-/* #undef HAVE_POLL_H */
-
-/* Define to 1 if you have a working POSIX-style strerror_r function. */
-/* #undef HAVE_POSIX_STRERROR_R */
-
-/* Define to 1 if you have the <pwd.h> header file. */
-/* #undef HAVE_PWD_H */
-
-/* Define to 1 if you have the `RAND_egd' function. */
-#define HAVE_RAND_EGD 1
-
-/* Define to 1 if you have the `RAND_screen' function. */
-/* #undef HAVE_RAND_SCREEN */
-
-/* Define to 1 if you have the `RAND_status' function. */
-#define HAVE_RAND_STATUS 1
-
-/* Define to 1 if you have the recv function. */
-#define HAVE_RECV 1
-
-/* Define to 1 if you have the recvfrom function. */
-#define HAVE_RECVFROM 1
-
-/* Define to 1 if you have the <rsa.h> header file. */
-/* #undef HAVE_RSA_H */
-
-/* Define to 1 if you have the select function. */
-#define HAVE_SELECT 1
-
-/* Define to 1 if you have the send function. */
-#define HAVE_SEND 1
-
-/* Define to 1 if you have the <setjmp.h> header file. */
-#define HAVE_SETJMP_H 1
-
-/* Define to 1 if you have the `setlocale' function. */
-#define HAVE_SETLOCALE 1
-
-/* Define to 1 if you have the `setmode' function. */
-#define HAVE_SETMODE 1
-
-/* Define to 1 if you have the `setrlimit' function. */
-#define HAVE_SETRLIMIT 1
-
-/* Define to 1 if you have the setsockopt function. */
-#define HAVE_SETSOCKOPT 1
-
-/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
-/* #undef HAVE_SETSOCKOPT_SO_NONBLOCK */
-
-/* Define to 1 if you have the <sgtty.h> header file. */
-/* #undef HAVE_SGTTY_H */
-
-/* Define to 1 if you have the sigaction function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the siginterrupt function. */
-#define HAVE_SIGINTERRUPT 1
-
-/* Define to 1 if you have the signal function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the sigsetjmp function or macro. */
-/* #undef HAVE_SIGSETJMP */
-
-/* Define to 1 if sig_atomic_t is an available typedef. */
-#define HAVE_SIG_ATOMIC_T 1
-
-/* Define to 1 if sig_atomic_t is already defined as volatile. */
-/* #undef HAVE_SIG_ATOMIC_T_VOLATILE */
-
-/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */
-#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
-
-/* Define to 1 if you have the `socket' function. */
-#define HAVE_SOCKET 1
-
-/* Define to 1 if you have the <ssl.h> header file. */
-/* #undef HAVE_SSL_H */
-
-/* Define to 1 if you have the <stdbool.h> header file. */
-#define HAVE_STDBOOL_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-/* #undef HAVE_STDINT_H */
-
-/* Define to 1 if you have the <stdio.h> header file. */
-#define HAVE_STDIO_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the strcasecmp function. */
-#define HAVE_STRCASECMP 1
-
-/* Define to 1 if you have the strcmpi function. */
-/* #undef HAVE_STRCMPI */
-
-/* Define to 1 if you have the strdup function. */
-#define HAVE_STRDUP 1
-
-/* Define to 1 if you have the strerror_r function. */
-#define HAVE_STRERROR_R 1
-
-/* Define to 1 if you have the stricmp function. */
-/* #undef HAVE_STRICMP */
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef HAVE_STRLCPY */
-
-/* Define to 1 if you have the strncasecmp function. */
-#define HAVE_STRNCASECMP 1
-
-/* Define to 1 if you have the strncmpi function. */
-/* #undef HAVE_STRNCMPI */
-
-/* Define to 1 if you have the strnicmp function. */
-/* #undef HAVE_STRNICMP */
-
-/* Define to 1 if you have the <stropts.h> header file. */
-/* #undef HAVE_STROPTS_H */
-
-/* Define to 1 if you have the strstr function. */
-#define HAVE_STRSTR 1
-
-/* Define to 1 if you have the strtok_r function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the strtoll function. */
-/* #undef HAVE_STRTOLL */
-
-/* if struct sockaddr_storage is defined */
-#define HAVE_STRUCT_SOCKADDR_STORAGE 1
-
-/* Define to 1 if you have the timeval struct. */
-#define HAVE_STRUCT_TIMEVAL 1
-
-/* Define to 1 if you have the <sys/filio.h> header file. */
-/* #undef HAVE_SYS_FILIO_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-/* #undef HAVE_SYS_PARAM_H */
-
-/* Define to 1 if you have the <sys/poll.h> header file. */
-/* #undef HAVE_SYS_POLL_H */
-
-/* Define to 1 if you have the <sys/resource.h> header file. */
-#define HAVE_SYS_RESOURCE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-/* #undef HAVE_SYS_SELECT_H */
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/sockio.h> header file. */
-/* #undef HAVE_SYS_SOCKIO_H */
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-/* #undef HAVE_SYS_TIME_H */
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <sys/uio.h> header file. */
-#define HAVE_SYS_UIO_H 1
-
-/* Define to 1 if you have the <sys/un.h> header file. */
-#define HAVE_SYS_UN_H 1
-
-/* Define to 1 if you have the <sys/utime.h> header file. */
-#define HAVE_SYS_UTIME_H 1
-
-/* Define to 1 if you have the <termios.h> header file. */
-#define HAVE_TERMIOS_H 1
-
-/* Define to 1 if you have the <termio.h> header file. */
-#define HAVE_TERMIO_H 1
-
-/* Define to 1 if you have the <time.h> header file. */
-#define HAVE_TIME_H 1
-
-/* Define to 1 if you have the <tld.h> header file. */
-/* #undef HAVE_TLD_H */
-
-/* Define to 1 if you have the `tld_strerror' function. */
-/* #undef HAVE_TLD_STRERROR */
-
-/* Define to 1 if you have the `uname' function. */
-#define HAVE_UNAME 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `utime' function. */
-#define HAVE_UTIME 1
-
-/* Define to 1 if you have the <utime.h> header file. */
-#define HAVE_UTIME_H 1
-
-/* Define to 1 if compiler supports C99 variadic macro style. */
-#define HAVE_VARIADIC_MACROS_C99 1
-
-/* Define to 1 if compiler supports old gcc variadic macro style. */
-#define HAVE_VARIADIC_MACROS_GCC 1
-
-/* Define to 1 if you have a working vxworks-style strerror_r function. */
-#define HAVE_VXWORKS_STRERROR_R 1
-
-/* Define to 1 if you have the winber.h header file. */
-/* #undef HAVE_WINBER_H */
-
-/* Define to 1 if you have the windows.h header file. */
-/* #undef HAVE_WINDOWS_H */
-
-/* Define to 1 if you have the winldap.h header file. */
-/* #undef HAVE_WINLDAP_H */
-
-/* Define to 1 if you have the winsock2.h header file. */
-/* #undef HAVE_WINSOCK2_H */
-
-/* Define to 1 if you have the winsock.h header file. */
-/* #undef HAVE_WINSOCK_H */
-
-/* Define this symbol if your OS supports changing the contents of argv */
-#define HAVE_WRITABLE_ARGV 1
-
-/* Define to 1 if you have the writev function. */
-#define HAVE_WRITEV 1
-
-/* Define to 1 if you have the ws2tcpip.h header file. */
-/* #undef HAVE_WS2TCPIP_H */
-
-/* Define to 1 if you have the <x509.h> header file. */
-/* #undef HAVE_X509_H */
-
-/* if you have the zlib.h header file */
-#define HAVE_ZLIB_H 1
-
-/* Define to 1 if you need the lber.h header file even with ldap.h */
-/* #undef NEED_LBER_H */
-
-/* Define to 1 if you need the malloc.h header file even with stdlib.h */
-/* #undef NEED_MALLOC_H */
-
-/* Define to 1 if you need the memory.h header file even with stdlib.h */
-/* #undef NEED_MEMORY_H */
-
-/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
-/* #undef NEED_REENTRANT */
-
-/* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */
-/* #undef NEED_THREAD_SAFE */
-
-/* Define to 1 if the open function requires three arguments. */
-#define OPEN_NEEDS_ARG3 1
-
-/* cpu-machine-OS */
-#define OS "unknown-unknown-vxworks"
-
-/* Name of package */
-#define PACKAGE "curl"
-
-/* a suitable file to read random data from */
-#define RANDOM_FILE "/dev/urandom"
-
-/* Define to the type of arg 1 for recvfrom. */
-#define RECVFROM_TYPE_ARG1 int
-
-/* Define to the type pointed by arg 2 for recvfrom. */
-#define RECVFROM_TYPE_ARG2 void
-
-/* Define to 1 if the type pointed by arg 2 for recvfrom is void. */
-#define RECVFROM_TYPE_ARG2_IS_VOID 1
-
-/* Define to the type of arg 3 for recvfrom. */
-#define RECVFROM_TYPE_ARG3 size_t
-
-/* Define to the type of arg 4 for recvfrom. */
-#define RECVFROM_TYPE_ARG4 int
-
-/* Define to the type pointed by arg 5 for recvfrom. */
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-
-/* Define to 1 if the type pointed by arg 5 for recvfrom is void. */
-/* #undef RECVFROM_TYPE_ARG5_IS_VOID */
-
-/* Define to the type pointed by arg 6 for recvfrom. */
-#define RECVFROM_TYPE_ARG6 socklen_t
-
-/* Define to 1 if the type pointed by arg 6 for recvfrom is void. */
-/* #undef RECVFROM_TYPE_ARG6_IS_VOID */
-
-/* Define to the function return type for recvfrom. */
-#define RECVFROM_TYPE_RETV int
-
-/* Define to the type of arg 1 for recv. */
-#define RECV_TYPE_ARG1 int
-
-/* Define to the type of arg 2 for recv. */
-#define RECV_TYPE_ARG2 void *
-
-/* Define to the type of arg 3 for recv. */
-#define RECV_TYPE_ARG3 size_t
-
-/* Define to the type of arg 4 for recv. */
-#define RECV_TYPE_ARG4 int
-
-/* Define to the function return type for recv. */
-#define RECV_TYPE_RETV int
-
-/* Define as the return type of signal handlers (`int' or `void'). */
-#define RETSIGTYPE void
-
-/* Define to the type qualifier of arg 5 for select. */
-#define SELECT_QUAL_ARG5
-
-/* Define to the type of arg 1 for select. */
-#define SELECT_TYPE_ARG1 int
-
-/* Define to the type of args 2, 3 and 4 for select. */
-#define SELECT_TYPE_ARG234 fd_set *
-
-/* Define to the type of arg 5 for select. */
-#define SELECT_TYPE_ARG5 struct timeval *
-
-/* Define to the function return type for select. */
-#define SELECT_TYPE_RETV int
-
-/* Define to the type qualifier of arg 2 for send. */
-#define SEND_QUAL_ARG2 const
-
-/* Define to the type of arg 1 for send. */
-#define SEND_TYPE_ARG1 int
-
-/* Define to the type of arg 2 for send. */
-#define SEND_TYPE_ARG2 void *
-
-/* Define to the type of arg 3 for send. */
-#define SEND_TYPE_ARG3 size_t
-
-/* Define to the type of arg 4 for send. */
-#define SEND_TYPE_ARG4 int
-
-/* Define to the function return type for send. */
-#define SEND_TYPE_RETV int
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 4
-
-/* The size of `off_t', as computed by sizeof. */
-#define SIZEOF_OFF_T 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* The size of `size_t', as computed by sizeof. */
-#define SIZEOF_SIZE_T 4
-
-/* The size of `time_t', as computed by sizeof. */
-#define SIZEOF_TIME_T 4
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to the type of arg 3 for strerror_r. */
-/* #undef STRERROR_R_TYPE_ARG3 */
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-/* #undef TIME_WITH_SYS_TIME */
-
-/* Define if you want to enable c-ares support */
-/* #undef USE_ARES */
-
-/* Define to disable non-blocking sockets. */
-/* #undef USE_BLOCKING_SOCKETS */
-
-/* if GnuTLS is enabled */
-/* #undef USE_GNUTLS */
-
-/* if libSSH2 is in use */
-/* #undef USE_LIBSSH2 */
-
-/* If you want to build curl with the built-in manual */
-#define USE_MANUAL 1
-
-/* if NSS is enabled */
-/* #undef USE_NSS */
-
-/* if OpenSSL is in use */
-#define USE_OPENSSL 1
-
-/* Define to 1 if you are building a Windows target without large file
- support. */
-/* #undef USE_WIN32_LARGE_FILES */
-
-/* to enable SSPI support */
-/* #undef USE_WINDOWS_SSPI */
-
-/* Define to 1 if using yaSSL in OpenSSL compatibility mode. */
-/* #undef USE_YASSLEMUL */
-
-/* Define to avoid automatic inclusion of winsock.h */
-/* #undef WIN32_LEAN_AND_MEAN */
-
-/* Define to 1 if OS is AIX. */
-#ifndef _ALL_SOURCE
-/* # undef _ALL_SOURCE */
-#endif
-
-/* Number of bits in a file offset, on hosts where this is settable. */
-/* #undef _FILE_OFFSET_BITS */
-
-/* Define for large files, on AIX-style hosts. */
-/* #undef _LARGE_FILES */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Type to use in place of in_addr_t when system does not provide it. */
-/* #undef in_addr_t */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
- calls it, or to nothing if 'inline' is not supported under any name. */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* the signed version of size_t */
-/* #undef ssize_t */
-
-#endif /* HEADER_CURL_CONFIG_VXWORKS_H */
+
+/* your Entropy Gathering Daemon socket pathname */
+/* #undef EGD_SOCKET */
+
+/* Define if you want to enable IPv6 support */
+#define ENABLE_IPV6 1
+
+/* Define to the type qualifier of arg 1 for getnameinfo. */
+#define GETNAMEINFO_QUAL_ARG1 const
+
+/* Define to the type of arg 1 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+
+/* Define to the type of arg 2 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG2 socklen_t
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG46 size_t
+
+/* Define to the type of arg 7 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG7 unsigned int
+
+/* Specifies the number of arguments to getservbyport_r */
+#define GETSERVBYPORT_R_ARGS 6
+
+/* Specifies the size of the buffer to pass to getservbyport_r */
+#define GETSERVBYPORT_R_BUFSIZE 4096
+
+/* Define to 1 if you have the alarm function. */
+#define HAVE_ALARM 1
+
+/* Define to 1 if you have the <alloca.h> header file. */
+#define HAVE_ALLOCA_H 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the <arpa/tftp.h> header file. */
+/* #undef HAVE_ARPA_TFTP_H */
+
+/* Define to 1 if you have the <assert.h> header file. */
+#define HAVE_ASSERT_H 1
+
+/* Define to 1 if you have the `basename' function. */
+/* #undef HAVE_BASENAME */
+
+/* Define to 1 if bool is an available type. */
+#define HAVE_BOOL_T 1
+
+/* Define to 1 if you have the clock_gettime function and monotonic timer. */
+/* #undef HAVE_CLOCK_GETTIME_MONOTONIC */
+
+/* Define to 1 if you have the `closesocket' function. */
+/* #undef HAVE_CLOSESOCKET */
+
+/* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */
+#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
+
+/* Define to 1 if you have the <crypto.h> header file. */
+/* #undef HAVE_CRYPTO_H */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the <err.h> header file. */
+/* #undef HAVE_ERR_H */
+
+/* Define to 1 if you have the fcntl function. */
+#define HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
+#define HAVE_FCNTL_O_NONBLOCK 1
+
+/* Define to 1 if you have the `fork' function. */
+#define HAVE_FORK 1
+
+/* Define to 1 if you have the freeaddrinfo function. */
+#define HAVE_FREEADDRINFO 1
+
+/* Define to 1 if you have the freeifaddrs function. */
+#define HAVE_FREEIFADDRS 1
+
+/* Define to 1 if you have the ftruncate function. */
+#define HAVE_FTRUNCATE 1
+
+/* Define to 1 if you have a working getaddrinfo function. */
+#define HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `geteuid' function. */
+/* #undef HAVE_GETEUID */
+
+/* Define to 1 if you have the gethostbyaddr function. */
+#define HAVE_GETHOSTBYADDR 1
+
+/* Define to 1 if you have the gethostbyaddr_r function. */
+#define HAVE_GETHOSTBYADDR_R 1
+
+/* gethostbyaddr_r() takes 5 args */
+/* #undef HAVE_GETHOSTBYADDR_R_5 */
+
+/* gethostbyaddr_r() takes 7 args */
+/* #undef HAVE_GETHOSTBYADDR_R_7 */
+
+/* gethostbyaddr_r() takes 8 args */
+#define HAVE_GETHOSTBYADDR_R_8 1
+
+/* Define to 1 if you have the gethostbyname function. */
+#define HAVE_GETHOSTBYNAME 1
+
+/* Define to 1 if you have the gethostbyname_r function. */
+/* #undef HAVE_GETHOSTBYNAME_R */
+
+/* gethostbyname_r() takes 3 args */
+/* #undef HAVE_GETHOSTBYNAME_R_3 */
+
+/* gethostbyname_r() takes 5 args */
+/* #undef HAVE_GETHOSTBYNAME_R_5 */
+
+/* gethostbyname_r() takes 6 args */
+/* #undef HAVE_GETHOSTBYNAME_R_6 */
+
+/* Define to 1 if you have the gethostname function. */
+#define HAVE_GETHOSTNAME 1
+
+/* Define to 1 if you have a working getifaddrs function. */
+/* #undef HAVE_GETIFADDRS */
+
+/* Define to 1 if you have the getnameinfo function. */
+#define HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getpass_r' function. */
+/* #undef HAVE_GETPASS_R */
+
+/* Define to 1 if you have the `getppid' function. */
+#define HAVE_GETPPID 1
+
+/* Define to 1 if you have the `getprotobyname' function. */
+#define HAVE_GETPROTOBYNAME 1
+
+/* Define to 1 if you have the `getpwuid' function. */
+/* #undef HAVE_GETPWUID */
+
+/* Define to 1 if you have the `getrlimit' function. */
+#define HAVE_GETRLIMIT 1
+
+/* Define to 1 if you have the getservbyport_r function. */
+/* #undef HAVE_GETSERVBYPORT_R */
+
+/* Define to 1 if you have the `gettimeofday' function. */
+/* #undef HAVE_GETTIMEOFDAY */
+
+/* Define to 1 if you have a working glibc-style strerror_r function. */
+/* #undef HAVE_GLIBC_STRERROR_R */
+
+/* Define to 1 if you have a working gmtime_r function. */
+#define HAVE_GMTIME_R 1
+
+/* if you have the gssapi libraries */
+/* #undef HAVE_GSSAPI */
+
+/* Define to 1 if you have the <gssapi/gssapi_generic.h> header file. */
+/* #undef HAVE_GSSAPI_GSSAPI_GENERIC_H */
+
+/* Define to 1 if you have the <gssapi/gssapi.h> header file. */
+/* #undef HAVE_GSSAPI_GSSAPI_H */
+
+/* Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. */
+/* #undef HAVE_GSSAPI_GSSAPI_KRB5_H */
+
+/* if you have the GNU gssapi libraries */
+/* #undef HAVE_GSSGNU */
+
+/* if you have the Heimdal gssapi libraries */
+/* #undef HAVE_GSSHEIMDAL */
+
+/* if you have the MIT gssapi libraries */
+/* #undef HAVE_GSSMIT */
+
+/* Define to 1 if you have the `idna_strerror' function. */
+/* #undef HAVE_IDNA_STRERROR */
+
+/* Define to 1 if you have the `idn_free' function. */
+/* #undef HAVE_IDN_FREE */
+
+/* Define to 1 if you have the <idn-free.h> header file. */
+/* #undef HAVE_IDN_FREE_H */
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+/* #undef HAVE_IFADDRS_H */
+
+/* Define to 1 if you have the `inet_addr' function. */
+#define HAVE_INET_ADDR 1
+
+/* Define to 1 if you have the inet_ntoa_r function. */
+/* #undef HAVE_INET_NTOA_R */
+
+/* inet_ntoa_r() takes 2 args */
+/* #undef HAVE_INET_NTOA_R_2 */
+
+/* inet_ntoa_r() takes 3 args */
+/* #undef HAVE_INET_NTOA_R_3 */
+
+/* Define to 1 if you have a IPv6 capable working inet_ntop function. */
+/* #undef HAVE_INET_NTOP */
+
+/* Define to 1 if you have a IPv6 capable working inet_pton function. */
+/* #undef HAVE_INET_PTON */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the ioctl function. */
+#define HAVE_IOCTL 1
+
+/* Define to 1 if you have the ioctlsocket function. */
+/* #undef HAVE_IOCTLSOCKET */
+
+/* Define to 1 if you have the IoctlSocket camel case function. */
+/* #undef HAVE_IOCTLSOCKET_CAMEL */
+
+/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
+ */
+/* #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO */
+
+/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
+/* #undef HAVE_IOCTLSOCKET_FIONBIO */
+
+/* Define to 1 if you have a working ioctl FIONBIO function. */
+#define HAVE_IOCTL_FIONBIO 1
+
+/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */
+#define HAVE_IOCTL_SIOCGIFADDR 1
+
+/* Define to 1 if you have the <io.h> header file. */
+#define HAVE_IO_H 1
+
+/* if you have the Kerberos4 libraries (including -ldes) */
+/* #undef HAVE_KRB4 */
+
+/* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */
+/* #undef HAVE_KRB_GET_OUR_IP_FOR_REALM */
+
+/* Define to 1 if you have the <krb.h> header file. */
+/* #undef HAVE_KRB_H */
+
+/* Define to 1 if you have the lber.h header file. */
+/* #undef HAVE_LBER_H */
+
+/* Define to 1 if you have the ldapssl.h header file. */
+/* #undef HAVE_LDAPSSL_H */
+
+/* Define to 1 if you have the ldap.h header file. */
+/* #undef HAVE_LDAP_H */
+
+/* Use LDAPS implementation */
+/* #undef HAVE_LDAP_SSL */
+
+/* Define to 1 if you have the ldap_ssl.h header file. */
+/* #undef HAVE_LDAP_SSL_H */
+
+/* Define to 1 if you have the `ldap_url_parse' function. */
+/* #undef HAVE_LDAP_URL_PARSE */
+
+/* Define to 1 if you have the <libgen.h> header file. */
+/* #undef HAVE_LIBGEN_H */
+
+/* Define to 1 if you have the `idn' library (-lidn). */
+/* #undef HAVE_LIBIDN */
+
+/* Define to 1 if you have the `resolv' library (-lresolv). */
+/* #undef HAVE_LIBRESOLV */
+
+/* Define to 1 if you have the `resolve' library (-lresolve). */
+/* #undef HAVE_LIBRESOLVE */
+
+/* Define to 1 if you have the `socket' library (-lsocket). */
+/* #undef HAVE_LIBSOCKET */
+
+/* Define to 1 if you have the `ssh2' library (-lssh2). */
+/* #undef HAVE_LIBSSH2 */
+
+/* Define to 1 if you have the <libssh2.h> header file. */
+/* #undef HAVE_LIBSSH2_H */
+
+/* Define to 1 if you have the `libssh2_version' function. */
+/* #undef HAVE_LIBSSH2_VERSION */
+
+/* if zlib is available */
+#define HAVE_LIBZ 1
+
+/* if your compiler supports LL */
+#define HAVE_LL 1
+
+/* Define to 1 if you have the <locale.h> header file. */
+#define HAVE_LOCALE_H 1
+
+/* Define to 1 if you have a working localtime_r function. */
+#define HAVE_LOCALTIME_R 1
+
+/* Define to 1 if the compiler supports the 'long long' data type. */
+#define HAVE_LONGLONG 1
+
+/* Define to 1 if you have the malloc.h header file. */
+#define HAVE_MALLOC_H 1
+
+/* Define to 1 if you have the memory.h header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the MSG_NOSIGNAL flag. */
+/* #undef HAVE_MSG_NOSIGNAL */
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define HAVE_NETINET_TCP_H 1
+
+/* Define to 1 if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H 1
+
+/* Define to 1 if NI_WITHSCOPEID exists and works. */
+/* #undef HAVE_NI_WITHSCOPEID */
+
+/* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE
+ */
+/* #undef HAVE_OLD_GSSMIT */
+
+/* Define to 1 if you have the <openssl/crypto.h> header file. */
+#define HAVE_OPENSSL_CRYPTO_H 1
+
+/* Define to 1 if you have the <openssl/err.h> header file. */
+#define HAVE_OPENSSL_ERR_H 1
+
+/* Define to 1 if you have the <openssl/pem.h> header file. */
+#define HAVE_OPENSSL_PEM_H 1
+
+/* Define to 1 if you have the <openssl/pkcs12.h> header file. */
+#define HAVE_OPENSSL_PKCS12_H 1
+
+/* Define to 1 if you have the <openssl/rsa.h> header file. */
+#define HAVE_OPENSSL_RSA_H 1
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+#define HAVE_OPENSSL_SSL_H 1
+
+/* Define to 1 if you have the <openssl/x509.h> header file. */
+#define HAVE_OPENSSL_X509_H 1
+
+/* Define to 1 if you have the <pem.h> header file. */
+/* #undef HAVE_PEM_H */
+
+/* Define to 1 if you have the `perror' function. */
+#define HAVE_PERROR 1
+
+/* Define to 1 if you have the `pipe' function. */
+#define HAVE_PIPE 1
+
+/* Define to 1 if you have a working poll function. */
+/* #undef HAVE_POLL */
+
+/* If you have a fine poll */
+/* #undef HAVE_POLL_FINE */
+
+/* Define to 1 if you have the <poll.h> header file. */
+/* #undef HAVE_POLL_H */
+
+/* Define to 1 if you have a working POSIX-style strerror_r function. */
+/* #undef HAVE_POSIX_STRERROR_R */
+
+/* Define to 1 if you have the <pwd.h> header file. */
+/* #undef HAVE_PWD_H */
+
+/* Define to 1 if you have the `RAND_egd' function. */
+#define HAVE_RAND_EGD 1
+
+/* Define to 1 if you have the `RAND_screen' function. */
+/* #undef HAVE_RAND_SCREEN */
+
+/* Define to 1 if you have the `RAND_status' function. */
+#define HAVE_RAND_STATUS 1
+
+/* Define to 1 if you have the recv function. */
+#define HAVE_RECV 1
+
+/* Define to 1 if you have the recvfrom function. */
+#define HAVE_RECVFROM 1
+
+/* Define to 1 if you have the <rsa.h> header file. */
+/* #undef HAVE_RSA_H */
+
+/* Define to 1 if you have the select function. */
+#define HAVE_SELECT 1
+
+/* Define to 1 if you have the send function. */
+#define HAVE_SEND 1
+
+/* Define to 1 if you have the <setjmp.h> header file. */
+#define HAVE_SETJMP_H 1
+
+/* Define to 1 if you have the `setlocale' function. */
+#define HAVE_SETLOCALE 1
+
+/* Define to 1 if you have the `setmode' function. */
+#define HAVE_SETMODE 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the setsockopt function. */
+#define HAVE_SETSOCKOPT 1
+
+/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
+/* #undef HAVE_SETSOCKOPT_SO_NONBLOCK */
+
+/* Define to 1 if you have the <sgtty.h> header file. */
+/* #undef HAVE_SGTTY_H */
+
+/* Define to 1 if you have the sigaction function. */
+#define HAVE_SIGACTION 1
+
+/* Define to 1 if you have the siginterrupt function. */
+#define HAVE_SIGINTERRUPT 1
+
+/* Define to 1 if you have the signal function. */
+#define HAVE_SIGNAL 1
+
+/* Define to 1 if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* Define to 1 if you have the sigsetjmp function or macro. */
+/* #undef HAVE_SIGSETJMP */
+
+/* Define to 1 if sig_atomic_t is an available typedef. */
+#define HAVE_SIG_ATOMIC_T 1
+
+/* Define to 1 if sig_atomic_t is already defined as volatile. */
+/* #undef HAVE_SIG_ATOMIC_T_VOLATILE */
+
+/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */
+#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
+
+/* Define to 1 if you have the `socket' function. */
+#define HAVE_SOCKET 1
+
+/* Define to 1 if you have the <ssl.h> header file. */
+/* #undef HAVE_SSL_H */
+
+/* Define to 1 if you have the <stdbool.h> header file. */
+#define HAVE_STDBOOL_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+/* #undef HAVE_STDINT_H */
+
+/* Define to 1 if you have the <stdio.h> header file. */
+#define HAVE_STDIO_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the strcasecmp function. */
+#define HAVE_STRCASECMP 1
+
+/* Define to 1 if you have the strcmpi function. */
+/* #undef HAVE_STRCMPI */
+
+/* Define to 1 if you have the strdup function. */
+#define HAVE_STRDUP 1
+
+/* Define to 1 if you have the strerror_r function. */
+#define HAVE_STRERROR_R 1
+
+/* Define to 1 if you have the stricmp function. */
+/* #undef HAVE_STRICMP */
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+/* #undef HAVE_STRLCPY */
+
+/* Define to 1 if you have the strncasecmp function. */
+#define HAVE_STRNCASECMP 1
+
+/* Define to 1 if you have the strncmpi function. */
+/* #undef HAVE_STRNCMPI */
+
+/* Define to 1 if you have the strnicmp function. */
+/* #undef HAVE_STRNICMP */
+
+/* Define to 1 if you have the <stropts.h> header file. */
+/* #undef HAVE_STROPTS_H */
+
+/* Define to 1 if you have the strstr function. */
+#define HAVE_STRSTR 1
+
+/* Define to 1 if you have the strtok_r function. */
+#define HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the strtoll function. */
+/* #undef HAVE_STRTOLL */
+
+/* if struct sockaddr_storage is defined */
+#define HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if you have the timeval struct. */
+#define HAVE_STRUCT_TIMEVAL 1
+
+/* Define to 1 if you have the <sys/filio.h> header file. */
+/* #undef HAVE_SYS_FILIO_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+/* #undef HAVE_SYS_PARAM_H */
+
+/* Define to 1 if you have the <sys/poll.h> header file. */
+/* #undef HAVE_SYS_POLL_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+/* #undef HAVE_SYS_SELECT_H */
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/sockio.h> header file. */
+/* #undef HAVE_SYS_SOCKIO_H */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+/* #undef HAVE_SYS_TIME_H */
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/utime.h> header file. */
+#define HAVE_SYS_UTIME_H 1
+
+/* Define to 1 if you have the <termios.h> header file. */
+#define HAVE_TERMIOS_H 1
+
+/* Define to 1 if you have the <termio.h> header file. */
+#define HAVE_TERMIO_H 1
+
+/* Define to 1 if you have the <time.h> header file. */
+#define HAVE_TIME_H 1
+
+/* Define to 1 if you have the <tld.h> header file. */
+/* #undef HAVE_TLD_H */
+
+/* Define to 1 if you have the `tld_strerror' function. */
+/* #undef HAVE_TLD_STRERROR */
+
+/* Define to 1 if you have the `uname' function. */
+#define HAVE_UNAME 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `utime' function. */
+#define HAVE_UTIME 1
+
+/* Define to 1 if you have the <utime.h> header file. */
+#define HAVE_UTIME_H 1
+
+/* Define to 1 if compiler supports C99 variadic macro style. */
+#define HAVE_VARIADIC_MACROS_C99 1
+
+/* Define to 1 if compiler supports old gcc variadic macro style. */
+#define HAVE_VARIADIC_MACROS_GCC 1
+
+/* Define to 1 if you have a working vxworks-style strerror_r function. */
+#define HAVE_VXWORKS_STRERROR_R 1
+
+/* Define to 1 if you have the winber.h header file. */
+/* #undef HAVE_WINBER_H */
+
+/* Define to 1 if you have the windows.h header file. */
+/* #undef HAVE_WINDOWS_H */
+
+/* Define to 1 if you have the winldap.h header file. */
+/* #undef HAVE_WINLDAP_H */
+
+/* Define to 1 if you have the winsock2.h header file. */
+/* #undef HAVE_WINSOCK2_H */
+
+/* Define to 1 if you have the winsock.h header file. */
+/* #undef HAVE_WINSOCK_H */
+
+/* Define this symbol if your OS supports changing the contents of argv */
+#define HAVE_WRITABLE_ARGV 1
+
+/* Define to 1 if you have the writev function. */
+#define HAVE_WRITEV 1
+
+/* Define to 1 if you have the ws2tcpip.h header file. */
+/* #undef HAVE_WS2TCPIP_H */
+
+/* Define to 1 if you have the <x509.h> header file. */
+/* #undef HAVE_X509_H */
+
+/* if you have the zlib.h header file */
+#define HAVE_ZLIB_H 1
+
+/* Define to 1 if you need the lber.h header file even with ldap.h */
+/* #undef NEED_LBER_H */
+
+/* Define to 1 if you need the malloc.h header file even with stdlib.h */
+/* #undef NEED_MALLOC_H */
+
+/* Define to 1 if you need the memory.h header file even with stdlib.h */
+/* #undef NEED_MEMORY_H */
+
+/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
+/* #undef NEED_REENTRANT */
+
+/* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */
+/* #undef NEED_THREAD_SAFE */
+
+/* Define to 1 if the open function requires three arguments. */
+#define OPEN_NEEDS_ARG3 1
+
+/* cpu-machine-OS */
+#define OS "unknown-unknown-vxworks"
+
+/* Name of package */
+#define PACKAGE "curl"
+
+/* a suitable file to read random data from */
+#define RANDOM_FILE "/dev/urandom"
+
+/* Define to the type of arg 1 for recvfrom. */
+#define RECVFROM_TYPE_ARG1 int
+
+/* Define to the type pointed by arg 2 for recvfrom. */
+#define RECVFROM_TYPE_ARG2 void
+
+/* Define to 1 if the type pointed by arg 2 for recvfrom is void. */
+#define RECVFROM_TYPE_ARG2_IS_VOID 1
+
+/* Define to the type of arg 3 for recvfrom. */
+#define RECVFROM_TYPE_ARG3 size_t
+
+/* Define to the type of arg 4 for recvfrom. */
+#define RECVFROM_TYPE_ARG4 int
+
+/* Define to the type pointed by arg 5 for recvfrom. */
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+
+/* Define to 1 if the type pointed by arg 5 for recvfrom is void. */
+/* #undef RECVFROM_TYPE_ARG5_IS_VOID */
+
+/* Define to the type pointed by arg 6 for recvfrom. */
+#define RECVFROM_TYPE_ARG6 socklen_t
+
+/* Define to 1 if the type pointed by arg 6 for recvfrom is void. */
+/* #undef RECVFROM_TYPE_ARG6_IS_VOID */
+
+/* Define to the function return type for recvfrom. */
+#define RECVFROM_TYPE_RETV int
+
+/* Define to the type of arg 1 for recv. */
+#define RECV_TYPE_ARG1 int
+
+/* Define to the type of arg 2 for recv. */
+#define RECV_TYPE_ARG2 void *
+
+/* Define to the type of arg 3 for recv. */
+#define RECV_TYPE_ARG3 size_t
+
+/* Define to the type of arg 4 for recv. */
+#define RECV_TYPE_ARG4 int
+
+/* Define to the function return type for recv. */
+#define RECV_TYPE_RETV int
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#define RETSIGTYPE void
+
+/* Define to the type qualifier of arg 5 for select. */
+#define SELECT_QUAL_ARG5
+
+/* Define to the type of arg 1 for select. */
+#define SELECT_TYPE_ARG1 int
+
+/* Define to the type of args 2, 3 and 4 for select. */
+#define SELECT_TYPE_ARG234 fd_set *
+
+/* Define to the type of arg 5 for select. */
+#define SELECT_TYPE_ARG5 struct timeval *
+
+/* Define to the function return type for select. */
+#define SELECT_TYPE_RETV int
+
+/* Define to the type qualifier of arg 2 for send. */
+#define SEND_QUAL_ARG2 const
+
+/* Define to the type of arg 1 for send. */
+#define SEND_TYPE_ARG1 int
+
+/* Define to the type of arg 2 for send. */
+#define SEND_TYPE_ARG2 void *
+
+/* Define to the type of arg 3 for send. */
+#define SEND_TYPE_ARG3 size_t
+
+/* Define to the type of arg 4 for send. */
+#define SEND_TYPE_ARG4 int
+
+/* Define to the function return type for send. */
+#define SEND_TYPE_RETV int
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#define SIZEOF_LONG 4
+
+/* The size of `off_t', as computed by sizeof. */
+#define SIZEOF_OFF_T 8
+
+/* The size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 4
+
+/* The size of `time_t', as computed by sizeof. */
+#define SIZEOF_TIME_T 4
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to the type of arg 3 for strerror_r. */
+/* #undef STRERROR_R_TYPE_ARG3 */
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+/* #undef TIME_WITH_SYS_TIME */
+
+/* Define if you want to enable c-ares support */
+/* #undef USE_ARES */
+
+/* Define to disable non-blocking sockets. */
+/* #undef USE_BLOCKING_SOCKETS */
+
+/* if GnuTLS is enabled */
+/* #undef USE_GNUTLS */
+
+/* if libSSH2 is in use */
+/* #undef USE_LIBSSH2 */
+
+/* If you want to build curl with the built-in manual */
+#define USE_MANUAL 1
+
+/* if NSS is enabled */
+/* #undef USE_NSS */
+
+/* if OpenSSL is in use */
+#define USE_OPENSSL 1
+
+/* Define to 1 if you are building a Windows target without large file
+ support. */
+/* #undef USE_WIN32_LARGE_FILES */
+
+/* to enable SSPI support */
+/* #undef USE_WINDOWS_SSPI */
+
+/* Define to 1 if using yaSSL in OpenSSL compatibility mode. */
+/* #undef USE_YASSLEMUL */
+
+/* Define to avoid automatic inclusion of winsock.h */
+/* #undef WIN32_LEAN_AND_MEAN */
+
+/* Define to 1 if OS is AIX. */
+#ifndef _ALL_SOURCE
+/* # undef _ALL_SOURCE */
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Type to use in place of in_addr_t when system does not provide it. */
+/* #undef in_addr_t */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* the signed version of size_t */
+/* #undef ssize_t */
+
+#endif /* HEADER_CURL_CONFIG_VXWORKS_H */
diff --git a/contrib/libs/curl/lib/config-win32.h b/contrib/libs/curl/lib/config-win32.h
index 35050dbf07..e3095576f8 100644
--- a/contrib/libs/curl/lib/config-win32.h
+++ b/contrib/libs/curl/lib/config-win32.h
@@ -1,517 +1,517 @@
-#ifndef HEADER_CURL_CONFIG_WIN32_H
-#define HEADER_CURL_CONFIG_WIN32_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_WIN32_H
+#define HEADER_CURL_CONFIG_WIN32_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* Hand crafted config file for Windows */
-/* ================================================================ */
-
-/* ---------------------------------------------------------------- */
-/* HEADER FILES */
-/* ---------------------------------------------------------------- */
-
-/* Define if you have the <arpa/inet.h> header file. */
-/* #define HAVE_ARPA_INET_H 1 */
-
-/* Define if you have the <assert.h> header file. */
-#define HAVE_ASSERT_H 1
-
-/* Define if you have the <crypto.h> header file. */
-/* #define HAVE_CRYPTO_H 1 */
-
-/* Define if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H 1
-
-/* Define if you have the <err.h> header file. */
-/* #define HAVE_ERR_H 1 */
-
-/* Define if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define if you have the <getopt.h> header file. */
-#if defined(__MINGW32__) || defined(__POCC__)
-#define HAVE_GETOPT_H 1
-#endif
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* ================================================================ */
+/* Hand crafted config file for Windows */
+/* ================================================================ */
+
+/* ---------------------------------------------------------------- */
+/* HEADER FILES */
+/* ---------------------------------------------------------------- */
+
+/* Define if you have the <arpa/inet.h> header file. */
+/* #define HAVE_ARPA_INET_H 1 */
+
+/* Define if you have the <assert.h> header file. */
+#define HAVE_ASSERT_H 1
+
+/* Define if you have the <crypto.h> header file. */
+/* #define HAVE_CRYPTO_H 1 */
+
+/* Define if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H 1
+
+/* Define if you have the <err.h> header file. */
+/* #define HAVE_ERR_H 1 */
+
+/* Define if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define if you have the <getopt.h> header file. */
+#if defined(__MINGW32__) || defined(__POCC__)
+#define HAVE_GETOPT_H 1
+#endif
+
/* Define to 1 if you have the <inttypes.h> header file. */
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
#define HAVE_INTTYPES_H 1
#endif
-/* Define if you have the <io.h> header file. */
-#define HAVE_IO_H 1
-
-/* Define if you have the <locale.h> header file. */
-#define HAVE_LOCALE_H 1
-
-/* Define if you need <malloc.h> header even with <stdlib.h> header file. */
-#if !defined(__SALFORDC__) && !defined(__POCC__)
-#define NEED_MALLOC_H 1
-#endif
-
-/* Define if you have the <netdb.h> header file. */
-/* #define HAVE_NETDB_H 1 */
-
-/* Define if you have the <netinet/in.h> header file. */
-/* #define HAVE_NETINET_IN_H 1 */
-
-/* Define if you have the <process.h> header file. */
-#ifndef __SALFORDC__
-#define HAVE_PROCESS_H 1
-#endif
-
-/* Define if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define if you have the <sgtty.h> header file. */
-/* #define HAVE_SGTTY_H 1 */
-
-/* Define if you have the <ssl.h> header file. */
-/* #define HAVE_SSL_H 1 */
-
+/* Define if you have the <io.h> header file. */
+#define HAVE_IO_H 1
+
+/* Define if you have the <locale.h> header file. */
+#define HAVE_LOCALE_H 1
+
+/* Define if you need <malloc.h> header even with <stdlib.h> header file. */
+#if !defined(__SALFORDC__) && !defined(__POCC__)
+#define NEED_MALLOC_H 1
+#endif
+
+/* Define if you have the <netdb.h> header file. */
+/* #define HAVE_NETDB_H 1 */
+
+/* Define if you have the <netinet/in.h> header file. */
+/* #define HAVE_NETINET_IN_H 1 */
+
+/* Define if you have the <process.h> header file. */
+#ifndef __SALFORDC__
+#define HAVE_PROCESS_H 1
+#endif
+
+/* Define if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* Define if you have the <sgtty.h> header file. */
+/* #define HAVE_SGTTY_H 1 */
+
+/* Define if you have the <ssl.h> header file. */
+/* #define HAVE_SSL_H 1 */
+
/* Define to 1 if you have the <stdbool.h> header file. */
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
#define HAVE_STDBOOL_H 1
#endif
-/* Define if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define if you have the <sys/param.h> header file. */
-/* #define HAVE_SYS_PARAM_H 1 */
-
-/* Define if you have the <sys/select.h> header file. */
-/* #define HAVE_SYS_SELECT_H 1 */
-
-/* Define if you have the <sys/socket.h> header file. */
-/* #define HAVE_SYS_SOCKET_H 1 */
-
-/* Define if you have the <sys/sockio.h> header file. */
-/* #define HAVE_SYS_SOCKIO_H 1 */
-
-/* Define if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define if you have the <sys/time.h> header file. */
-/* #define HAVE_SYS_TIME_H 1 */
-
-/* Define if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if you have the <sys/utime.h> header file. */
-#ifndef __BORLANDC__
-#define HAVE_SYS_UTIME_H 1
-#endif
-
-/* Define if you have the <termio.h> header file. */
-/* #define HAVE_TERMIO_H 1 */
-
-/* Define if you have the <termios.h> header file. */
-/* #define HAVE_TERMIOS_H 1 */
-
-/* Define if you have the <time.h> header file. */
-#define HAVE_TIME_H 1
-
-/* Define if you have the <unistd.h> header file. */
-#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \
- defined(__POCC__)
-#define HAVE_UNISTD_H 1
-#endif
-
-/* Define if you have the <windows.h> header file. */
-#define HAVE_WINDOWS_H 1
-
-/* Define if you have the <winsock.h> header file. */
-#define HAVE_WINSOCK_H 1
-
-/* Define if you have the <winsock2.h> header file. */
-#ifndef __SALFORDC__
-#define HAVE_WINSOCK2_H 1
-#endif
-
-/* Define if you have the <ws2tcpip.h> header file. */
-#ifndef __SALFORDC__
-#define HAVE_WS2TCPIP_H 1
-#endif
-
-/* ---------------------------------------------------------------- */
-/* OTHER HEADER INFO */
-/* ---------------------------------------------------------------- */
-
-/* Define if sig_atomic_t is an available typedef. */
-#define HAVE_SIG_ATOMIC_T 1
-
-/* Define if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if you can safely include both <sys/time.h> and <time.h>. */
-/* #define TIME_WITH_SYS_TIME 1 */
-
+/* Define if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define if you have the <sys/param.h> header file. */
+/* #define HAVE_SYS_PARAM_H 1 */
+
+/* Define if you have the <sys/select.h> header file. */
+/* #define HAVE_SYS_SELECT_H 1 */
+
+/* Define if you have the <sys/socket.h> header file. */
+/* #define HAVE_SYS_SOCKET_H 1 */
+
+/* Define if you have the <sys/sockio.h> header file. */
+/* #define HAVE_SYS_SOCKIO_H 1 */
+
+/* Define if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define if you have the <sys/time.h> header file. */
+/* #define HAVE_SYS_TIME_H 1 */
+
+/* Define if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define if you have the <sys/utime.h> header file. */
+#ifndef __BORLANDC__
+#define HAVE_SYS_UTIME_H 1
+#endif
+
+/* Define if you have the <termio.h> header file. */
+/* #define HAVE_TERMIO_H 1 */
+
+/* Define if you have the <termios.h> header file. */
+/* #define HAVE_TERMIOS_H 1 */
+
+/* Define if you have the <time.h> header file. */
+#define HAVE_TIME_H 1
+
+/* Define if you have the <unistd.h> header file. */
+#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \
+ defined(__POCC__)
+#define HAVE_UNISTD_H 1
+#endif
+
+/* Define if you have the <windows.h> header file. */
+#define HAVE_WINDOWS_H 1
+
+/* Define if you have the <winsock.h> header file. */
+#define HAVE_WINSOCK_H 1
+
+/* Define if you have the <winsock2.h> header file. */
+#ifndef __SALFORDC__
+#define HAVE_WINSOCK2_H 1
+#endif
+
+/* Define if you have the <ws2tcpip.h> header file. */
+#ifndef __SALFORDC__
+#define HAVE_WS2TCPIP_H 1
+#endif
+
+/* ---------------------------------------------------------------- */
+/* OTHER HEADER INFO */
+/* ---------------------------------------------------------------- */
+
+/* Define if sig_atomic_t is an available typedef. */
+#define HAVE_SIG_ATOMIC_T 1
+
+/* Define if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if you can safely include both <sys/time.h> and <time.h>. */
+/* #define TIME_WITH_SYS_TIME 1 */
+
/* Define to 1 if bool is an available type. */
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
#define HAVE_BOOL_T 1
#endif
-/* ---------------------------------------------------------------- */
-/* FUNCTIONS */
-/* ---------------------------------------------------------------- */
-
-/* Define if you have the closesocket function. */
-#define HAVE_CLOSESOCKET 1
-
-/* Define if you don't have vprintf but do have _doprnt. */
-/* #define HAVE_DOPRNT 1 */
-
-/* Define if you have the ftruncate function. */
+/* ---------------------------------------------------------------- */
+/* FUNCTIONS */
+/* ---------------------------------------------------------------- */
+
+/* Define if you have the closesocket function. */
+#define HAVE_CLOSESOCKET 1
+
+/* Define if you don't have vprintf but do have _doprnt. */
+/* #define HAVE_DOPRNT 1 */
+
+/* Define if you have the ftruncate function. */
/* #define HAVE_FTRUNCATE 1 */
-
+
/* Define to 1 if you have the `getpeername' function. */
#define HAVE_GETPEERNAME 1
/* Define to 1 if you have the getsockname function. */
#define HAVE_GETSOCKNAME 1
-/* Define if you have the gethostbyaddr function. */
-#define HAVE_GETHOSTBYADDR 1
-
-/* Define if you have the gethostname function. */
-#define HAVE_GETHOSTNAME 1
-
-/* Define if you have the getpass function. */
-/* #define HAVE_GETPASS 1 */
-
-/* Define if you have the getservbyname function. */
-#define HAVE_GETSERVBYNAME 1
-
-/* Define if you have the getprotobyname function. */
-#define HAVE_GETPROTOBYNAME
-
-/* Define if you have the gettimeofday function. */
-/* #define HAVE_GETTIMEOFDAY 1 */
-
-/* Define if you have the inet_addr function. */
-#define HAVE_INET_ADDR 1
-
-/* Define if you have the ioctlsocket function. */
-#define HAVE_IOCTLSOCKET 1
-
-/* Define if you have a working ioctlsocket FIONBIO function. */
-#define HAVE_IOCTLSOCKET_FIONBIO 1
-
-/* Define if you have the perror function. */
-#define HAVE_PERROR 1
-
-/* Define if you have the RAND_screen function when using SSL. */
-#define HAVE_RAND_SCREEN 1
-
-/* Define if you have the `RAND_status' function when using SSL. */
-#define HAVE_RAND_STATUS 1
-
-/* Define if you have the `CRYPTO_cleanup_all_ex_data' function.
- This is present in OpenSSL versions after 0.9.6b */
-#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
-
-/* Define if you have the select function. */
-#define HAVE_SELECT 1
-
-/* Define if you have the setlocale function. */
-#define HAVE_SETLOCALE 1
-
-/* Define if you have the setmode function. */
-#define HAVE_SETMODE 1
-
-/* Define if you have the setvbuf function. */
-#define HAVE_SETVBUF 1
-
-/* Define if you have the socket function. */
-#define HAVE_SOCKET 1
-
-/* Define if you have the strcasecmp function. */
-/* #define HAVE_STRCASECMP 1 */
-
-/* Define if you have the strdup function. */
-#define HAVE_STRDUP 1
-
-/* Define if you have the strftime function. */
-#define HAVE_STRFTIME 1
-
-/* Define if you have the stricmp function. */
-#define HAVE_STRICMP 1
-
-/* Define if you have the strncasecmp function. */
-/* #define HAVE_STRNCASECMP 1 */
-
-/* Define if you have the strnicmp function. */
-#define HAVE_STRNICMP 1
-
-/* Define if you have the strstr function. */
-#define HAVE_STRSTR 1
-
-/* Define if you have the strtoll function. */
+/* Define if you have the gethostbyaddr function. */
+#define HAVE_GETHOSTBYADDR 1
+
+/* Define if you have the gethostname function. */
+#define HAVE_GETHOSTNAME 1
+
+/* Define if you have the getpass function. */
+/* #define HAVE_GETPASS 1 */
+
+/* Define if you have the getservbyname function. */
+#define HAVE_GETSERVBYNAME 1
+
+/* Define if you have the getprotobyname function. */
+#define HAVE_GETPROTOBYNAME
+
+/* Define if you have the gettimeofday function. */
+/* #define HAVE_GETTIMEOFDAY 1 */
+
+/* Define if you have the inet_addr function. */
+#define HAVE_INET_ADDR 1
+
+/* Define if you have the ioctlsocket function. */
+#define HAVE_IOCTLSOCKET 1
+
+/* Define if you have a working ioctlsocket FIONBIO function. */
+#define HAVE_IOCTLSOCKET_FIONBIO 1
+
+/* Define if you have the perror function. */
+#define HAVE_PERROR 1
+
+/* Define if you have the RAND_screen function when using SSL. */
+#define HAVE_RAND_SCREEN 1
+
+/* Define if you have the `RAND_status' function when using SSL. */
+#define HAVE_RAND_STATUS 1
+
+/* Define if you have the `CRYPTO_cleanup_all_ex_data' function.
+ This is present in OpenSSL versions after 0.9.6b */
+#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
+
+/* Define if you have the select function. */
+#define HAVE_SELECT 1
+
+/* Define if you have the setlocale function. */
+#define HAVE_SETLOCALE 1
+
+/* Define if you have the setmode function. */
+#define HAVE_SETMODE 1
+
+/* Define if you have the setvbuf function. */
+#define HAVE_SETVBUF 1
+
+/* Define if you have the socket function. */
+#define HAVE_SOCKET 1
+
+/* Define if you have the strcasecmp function. */
+/* #define HAVE_STRCASECMP 1 */
+
+/* Define if you have the strdup function. */
+#define HAVE_STRDUP 1
+
+/* Define if you have the strftime function. */
+#define HAVE_STRFTIME 1
+
+/* Define if you have the stricmp function. */
+#define HAVE_STRICMP 1
+
+/* Define if you have the strncasecmp function. */
+/* #define HAVE_STRNCASECMP 1 */
+
+/* Define if you have the strnicmp function. */
+#define HAVE_STRNICMP 1
+
+/* Define if you have the strstr function. */
+#define HAVE_STRSTR 1
+
+/* Define if you have the strtoll function. */
#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__POCC__) || \
(defined(_MSC_VER) && (_MSC_VER >= 1800))
-#define HAVE_STRTOLL 1
-#endif
-
-/* Define if you have the tcgetattr function. */
-/* #define HAVE_TCGETATTR 1 */
-
-/* Define if you have the tcsetattr function. */
-/* #define HAVE_TCSETATTR 1 */
-
-/* Define if you have the utime function. */
-#ifndef __BORLANDC__
-#define HAVE_UTIME 1
-#endif
-
-/* Define to the type qualifier of arg 1 for getnameinfo. */
-#define GETNAMEINFO_QUAL_ARG1 const
-
-/* Define to the type of arg 1 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-
-/* Define to the type of arg 2 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG2 socklen_t
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG46 DWORD
-
-/* Define to the type of arg 7 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG7 int
-
-/* Define if you have the recv function. */
-#define HAVE_RECV 1
-
-/* Define to the type of arg 1 for recv. */
-#define RECV_TYPE_ARG1 SOCKET
-
-/* Define to the type of arg 2 for recv. */
-#define RECV_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for recv. */
-#define RECV_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recv. */
-#define RECV_TYPE_ARG4 int
-
-/* Define to the function return type for recv. */
-#define RECV_TYPE_RETV int
-
-/* Define if you have the recvfrom function. */
-#define HAVE_RECVFROM 1
-
-/* Define to the type of arg 1 for recvfrom. */
-#define RECVFROM_TYPE_ARG1 SOCKET
-
-/* Define to the type pointed by arg 2 for recvfrom. */
-#define RECVFROM_TYPE_ARG2 char
-
-/* Define to the type of arg 3 for recvfrom. */
-#define RECVFROM_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recvfrom. */
-#define RECVFROM_TYPE_ARG4 int
-
-/* Define to the type pointed by arg 5 for recvfrom. */
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-
-/* Define to the type pointed by arg 6 for recvfrom. */
-#define RECVFROM_TYPE_ARG6 int
-
-/* Define to the function return type for recvfrom. */
-#define RECVFROM_TYPE_RETV int
-
-/* Define if you have the send function. */
-#define HAVE_SEND 1
-
-/* Define to the type of arg 1 for send. */
-#define SEND_TYPE_ARG1 SOCKET
-
-/* Define to the type qualifier of arg 2 for send. */
-#define SEND_QUAL_ARG2 const
-
-/* Define to the type of arg 2 for send. */
-#define SEND_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for send. */
-#define SEND_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for send. */
-#define SEND_TYPE_ARG4 int
-
-/* Define to the function return type for send. */
-#define SEND_TYPE_RETV int
-
-/* ---------------------------------------------------------------- */
-/* TYPEDEF REPLACEMENTS */
-/* ---------------------------------------------------------------- */
-
-/* Define if in_addr_t is not an available 'typedefed' type. */
-#define in_addr_t unsigned long
-
-/* Define to the return type of signal handlers (int or void). */
-#define RETSIGTYPE void
-
-/* Define if ssize_t is not an available 'typedefed' type. */
-#ifndef _SSIZE_T_DEFINED
-# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \
- defined(__POCC__) || \
- defined(__MINGW32__)
-# elif defined(_WIN64)
-# define _SSIZE_T_DEFINED
-# define ssize_t __int64
-# else
-# define _SSIZE_T_DEFINED
-# define ssize_t int
-# endif
-#endif
-
-/* ---------------------------------------------------------------- */
-/* TYPE SIZES */
-/* ---------------------------------------------------------------- */
-
-/* Define to the size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* Define to the size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* Define to the size of `long long', as computed by sizeof. */
-/* #define SIZEOF_LONG_LONG 8 */
-
-/* Define to the size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
+#define HAVE_STRTOLL 1
+#endif
+
+/* Define if you have the tcgetattr function. */
+/* #define HAVE_TCGETATTR 1 */
+
+/* Define if you have the tcsetattr function. */
+/* #define HAVE_TCSETATTR 1 */
+
+/* Define if you have the utime function. */
+#ifndef __BORLANDC__
+#define HAVE_UTIME 1
+#endif
+
+/* Define to the type qualifier of arg 1 for getnameinfo. */
+#define GETNAMEINFO_QUAL_ARG1 const
+
+/* Define to the type of arg 1 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+
+/* Define to the type of arg 2 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG2 socklen_t
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG46 DWORD
+
+/* Define to the type of arg 7 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG7 int
+
+/* Define if you have the recv function. */
+#define HAVE_RECV 1
+
+/* Define to the type of arg 1 for recv. */
+#define RECV_TYPE_ARG1 SOCKET
+
+/* Define to the type of arg 2 for recv. */
+#define RECV_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for recv. */
+#define RECV_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recv. */
+#define RECV_TYPE_ARG4 int
+
+/* Define to the function return type for recv. */
+#define RECV_TYPE_RETV int
+
+/* Define if you have the recvfrom function. */
+#define HAVE_RECVFROM 1
+
+/* Define to the type of arg 1 for recvfrom. */
+#define RECVFROM_TYPE_ARG1 SOCKET
+
+/* Define to the type pointed by arg 2 for recvfrom. */
+#define RECVFROM_TYPE_ARG2 char
+
+/* Define to the type of arg 3 for recvfrom. */
+#define RECVFROM_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recvfrom. */
+#define RECVFROM_TYPE_ARG4 int
+
+/* Define to the type pointed by arg 5 for recvfrom. */
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+
+/* Define to the type pointed by arg 6 for recvfrom. */
+#define RECVFROM_TYPE_ARG6 int
+
+/* Define to the function return type for recvfrom. */
+#define RECVFROM_TYPE_RETV int
+
+/* Define if you have the send function. */
+#define HAVE_SEND 1
+
+/* Define to the type of arg 1 for send. */
+#define SEND_TYPE_ARG1 SOCKET
+
+/* Define to the type qualifier of arg 2 for send. */
+#define SEND_QUAL_ARG2 const
+
+/* Define to the type of arg 2 for send. */
+#define SEND_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for send. */
+#define SEND_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for send. */
+#define SEND_TYPE_ARG4 int
+
+/* Define to the function return type for send. */
+#define SEND_TYPE_RETV int
+
+/* ---------------------------------------------------------------- */
+/* TYPEDEF REPLACEMENTS */
+/* ---------------------------------------------------------------- */
+
+/* Define if in_addr_t is not an available 'typedefed' type. */
+#define in_addr_t unsigned long
+
+/* Define to the return type of signal handlers (int or void). */
+#define RETSIGTYPE void
+
+/* Define if ssize_t is not an available 'typedefed' type. */
+#ifndef _SSIZE_T_DEFINED
+# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \
+ defined(__POCC__) || \
+ defined(__MINGW32__)
+# elif defined(_WIN64)
+# define _SSIZE_T_DEFINED
+# define ssize_t __int64
+# else
+# define _SSIZE_T_DEFINED
+# define ssize_t int
+# endif
+#endif
+
+/* ---------------------------------------------------------------- */
+/* TYPE SIZES */
+/* ---------------------------------------------------------------- */
+
+/* Define to the size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* Define to the size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* Define to the size of `long long', as computed by sizeof. */
+/* #define SIZEOF_LONG_LONG 8 */
+
+/* Define to the size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
/* Define to the size of `long', as computed by sizeof. */
#define SIZEOF_LONG 4
-/* Define to the size of `size_t', as computed by sizeof. */
-#if defined(_WIN64)
-# define SIZEOF_SIZE_T 8
-#else
-# define SIZEOF_SIZE_T 4
-#endif
-
+/* Define to the size of `size_t', as computed by sizeof. */
+#if defined(_WIN64)
+# define SIZEOF_SIZE_T 8
+#else
+# define SIZEOF_SIZE_T 4
+#endif
+
/* Define to the size of `curl_off_t', as computed by sizeof. */
#define SIZEOF_CURL_OFF_T 8
-/* ---------------------------------------------------------------- */
-/* BSD-style lwIP TCP/IP stack SPECIFIC */
-/* ---------------------------------------------------------------- */
-
-/* Define to use BSD-style lwIP TCP/IP stack. */
-/* #define USE_LWIPSOCK 1 */
-
-#ifdef USE_LWIPSOCK
-# undef USE_WINSOCK
-# undef HAVE_WINSOCK_H
-# undef HAVE_WINSOCK2_H
-# undef HAVE_WS2TCPIP_H
-# undef HAVE_ERRNO_H
-# undef HAVE_GETHOSTNAME
-# undef HAVE_GETNAMEINFO
-# undef LWIP_POSIX_SOCKETS_IO_NAMES
-# undef RECV_TYPE_ARG1
-# undef RECV_TYPE_ARG3
-# undef SEND_TYPE_ARG1
-# undef SEND_TYPE_ARG3
-# define HAVE_FREEADDRINFO
-# define HAVE_GETADDRINFO
-# define HAVE_GETHOSTBYNAME
-# define HAVE_GETHOSTBYNAME_R
-# define HAVE_GETHOSTBYNAME_R_6
-# define LWIP_POSIX_SOCKETS_IO_NAMES 0
-# define RECV_TYPE_ARG1 int
-# define RECV_TYPE_ARG3 size_t
-# define SEND_TYPE_ARG1 int
-# define SEND_TYPE_ARG3 size_t
-#endif
-
-/* ---------------------------------------------------------------- */
-/* Watt-32 tcp/ip SPECIFIC */
-/* ---------------------------------------------------------------- */
-
-#ifdef USE_WATT32
- #include <tcp.h>
- #undef byte
- #undef word
- #undef USE_WINSOCK
- #undef HAVE_WINSOCK_H
- #undef HAVE_WINSOCK2_H
- #undef HAVE_WS2TCPIP_H
- #define HAVE_GETADDRINFO
- #define HAVE_GETNAMEINFO
- #define HAVE_SYS_IOCTL_H
- #define HAVE_SYS_SOCKET_H
- #define HAVE_NETINET_IN_H
- #define HAVE_NETDB_H
- #define HAVE_ARPA_INET_H
- #define HAVE_FREEADDRINFO
- #define SOCKET int
-#endif
-
-
-/* ---------------------------------------------------------------- */
-/* COMPILER SPECIFIC */
-/* ---------------------------------------------------------------- */
-
-/* Define to nothing if compiler does not support 'const' qualifier. */
-/* #define const */
-
-/* Define to nothing if compiler does not support 'volatile' qualifier. */
-/* #define volatile */
-
-/* Windows should not have HAVE_GMTIME_R defined */
-/* #undef HAVE_GMTIME_R */
-
-/* Define if the compiler supports C99 variadic macro style. */
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
-#define HAVE_VARIADIC_MACROS_C99 1
-#endif
-
-/* Define if the compiler supports the 'long long' data type. */
+/* ---------------------------------------------------------------- */
+/* BSD-style lwIP TCP/IP stack SPECIFIC */
+/* ---------------------------------------------------------------- */
+
+/* Define to use BSD-style lwIP TCP/IP stack. */
+/* #define USE_LWIPSOCK 1 */
+
+#ifdef USE_LWIPSOCK
+# undef USE_WINSOCK
+# undef HAVE_WINSOCK_H
+# undef HAVE_WINSOCK2_H
+# undef HAVE_WS2TCPIP_H
+# undef HAVE_ERRNO_H
+# undef HAVE_GETHOSTNAME
+# undef HAVE_GETNAMEINFO
+# undef LWIP_POSIX_SOCKETS_IO_NAMES
+# undef RECV_TYPE_ARG1
+# undef RECV_TYPE_ARG3
+# undef SEND_TYPE_ARG1
+# undef SEND_TYPE_ARG3
+# define HAVE_FREEADDRINFO
+# define HAVE_GETADDRINFO
+# define HAVE_GETHOSTBYNAME
+# define HAVE_GETHOSTBYNAME_R
+# define HAVE_GETHOSTBYNAME_R_6
+# define LWIP_POSIX_SOCKETS_IO_NAMES 0
+# define RECV_TYPE_ARG1 int
+# define RECV_TYPE_ARG3 size_t
+# define SEND_TYPE_ARG1 int
+# define SEND_TYPE_ARG3 size_t
+#endif
+
+/* ---------------------------------------------------------------- */
+/* Watt-32 tcp/ip SPECIFIC */
+/* ---------------------------------------------------------------- */
+
+#ifdef USE_WATT32
+ #include <tcp.h>
+ #undef byte
+ #undef word
+ #undef USE_WINSOCK
+ #undef HAVE_WINSOCK_H
+ #undef HAVE_WINSOCK2_H
+ #undef HAVE_WS2TCPIP_H
+ #define HAVE_GETADDRINFO
+ #define HAVE_GETNAMEINFO
+ #define HAVE_SYS_IOCTL_H
+ #define HAVE_SYS_SOCKET_H
+ #define HAVE_NETINET_IN_H
+ #define HAVE_NETDB_H
+ #define HAVE_ARPA_INET_H
+ #define HAVE_FREEADDRINFO
+ #define SOCKET int
+#endif
+
+
+/* ---------------------------------------------------------------- */
+/* COMPILER SPECIFIC */
+/* ---------------------------------------------------------------- */
+
+/* Define to nothing if compiler does not support 'const' qualifier. */
+/* #define const */
+
+/* Define to nothing if compiler does not support 'volatile' qualifier. */
+/* #define volatile */
+
+/* Windows should not have HAVE_GMTIME_R defined */
+/* #undef HAVE_GMTIME_R */
+
+/* Define if the compiler supports C99 variadic macro style. */
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+#define HAVE_VARIADIC_MACROS_C99 1
+#endif
+
+/* Define if the compiler supports the 'long long' data type. */
#if defined(__MINGW32__) || defined(__WATCOMC__) || \
(defined(_MSC_VER) && (_MSC_VER >= 1310)) || \
(defined(__BORLANDC__) && (__BORLANDC__ >= 0x561))
-#define HAVE_LONGLONG 1
-#endif
-
-/* Define to avoid VS2005 complaining about portable C functions. */
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
-#define _CRT_SECURE_NO_DEPRECATE 1
-#define _CRT_NONSTDC_NO_DEPRECATE 1
-#endif
-
+#define HAVE_LONGLONG 1
+#endif
+
+/* Define to avoid VS2005 complaining about portable C functions. */
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+#define _CRT_SECURE_NO_DEPRECATE 1
+#define _CRT_NONSTDC_NO_DEPRECATE 1
+#endif
+
/* VS2005 and later default size for time_t is 64-bit, unless
- _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
-# ifndef _USE_32BIT_TIME_T
-# define SIZEOF_TIME_T 8
-# else
-# define SIZEOF_TIME_T 4
-# endif
-#endif
-
+ _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+# ifndef _USE_32BIT_TIME_T
+# define SIZEOF_TIME_T 8
+# else
+# define SIZEOF_TIME_T 4
+# endif
+#endif
+
/* Define some minimum and default build targets for Visual Studio */
#if defined(_MSC_VER)
/* Officially, Microsoft's Windows SDK versions 6.X does not support Windows
@@ -520,8 +520,8 @@
valid build target for VS2008. Popular belief is that binaries built with
VS2008 using Windows SDK versions v6.X and Windows 2000 as a build target
are functional. */
-# define VS2008_MIN_TARGET 0x0500
-
+# define VS2008_MIN_TARGET 0x0500
+
/* The minimum build target for VS2012 is Vista unless Update 1 is installed
and the v110_xp toolset is chosen. */
# if defined(_USING_V110_SDK71_)
@@ -541,21 +541,21 @@
# else
# define VS2012_DEF_TARGET 0x0600
# endif
-#endif
-
-/* VS2008 default target settings and minimum build target check. */
+#endif
+
+/* VS2008 default target settings and minimum build target check. */
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_MSC_VER <= 1600)
-# ifndef _WIN32_WINNT
-# define _WIN32_WINNT VS2008_DEF_TARGET
-# endif
-# ifndef WINVER
-# define WINVER VS2008_DEF_TARGET
-# endif
-# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET)
-# error VS2008 does not support Windows build targets prior to Windows 2000
-# endif
-#endif
-
+# ifndef _WIN32_WINNT
+# define _WIN32_WINNT VS2008_DEF_TARGET
+# endif
+# ifndef WINVER
+# define WINVER VS2008_DEF_TARGET
+# endif
+# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET)
+# error VS2008 does not support Windows build targets prior to Windows 2000
+# endif
+#endif
+
/* VS2012 default target settings and minimum build target check. */
#if defined(_MSC_VER) && (_MSC_VER >= 1700)
# ifndef _WIN32_WINNT
@@ -574,145 +574,145 @@ Vista
# endif
#endif
-/* When no build target is specified Pelles C 5.00 and later default build
- target is Windows Vista. We override default target to be Windows 2000. */
-#if defined(__POCC__) && (__POCC__ >= 500)
-# ifndef _WIN32_WINNT
-# define _WIN32_WINNT 0x0500
-# endif
-# ifndef WINVER
-# define WINVER 0x0500
-# endif
-#endif
-
+/* When no build target is specified Pelles C 5.00 and later default build
+ target is Windows Vista. We override default target to be Windows 2000. */
+#if defined(__POCC__) && (__POCC__ >= 500)
+# ifndef _WIN32_WINNT
+# define _WIN32_WINNT 0x0500
+# endif
+# ifndef WINVER
+# define WINVER 0x0500
+# endif
+#endif
+
/* Availability of freeaddrinfo, getaddrinfo, getnameinfo and if_nametoindex
functions is quite convoluted, compiler dependent and even build target
dependent. */
-#if defined(HAVE_WS2TCPIP_H)
-# if defined(__POCC__)
-# define HAVE_FREEADDRINFO 1
-# define HAVE_GETADDRINFO 1
-# define HAVE_GETADDRINFO_THREADSAFE 1
-# define HAVE_GETNAMEINFO 1
-# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501)
-# define HAVE_FREEADDRINFO 1
-# define HAVE_GETADDRINFO 1
-# define HAVE_GETADDRINFO_THREADSAFE 1
-# define HAVE_GETNAMEINFO 1
-# elif defined(_MSC_VER) && (_MSC_VER >= 1200)
-# define HAVE_FREEADDRINFO 1
-# define HAVE_GETADDRINFO 1
-# define HAVE_GETADDRINFO_THREADSAFE 1
-# define HAVE_GETNAMEINFO 1
-# endif
-#endif
-
-#if defined(__POCC__)
-# ifndef _MSC_VER
-# error Microsoft extensions /Ze compiler option is required
-# endif
-# ifndef __POCC__OLDNAMES
-# error Compatibility names /Go compiler option is required
-# endif
-#endif
-
-/* ---------------------------------------------------------------- */
-/* STRUCT RELATED */
-/* ---------------------------------------------------------------- */
-
-/* Define if you have struct sockaddr_storage. */
-#if !defined(__SALFORDC__) && !defined(__BORLANDC__)
-#define HAVE_STRUCT_SOCKADDR_STORAGE 1
-#endif
-
-/* Define if you have struct timeval. */
-#define HAVE_STRUCT_TIMEVAL 1
-
-/* Define if struct sockaddr_in6 has the sin6_scope_id member. */
-#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
-
+#if defined(HAVE_WS2TCPIP_H)
+# if defined(__POCC__)
+# define HAVE_FREEADDRINFO 1
+# define HAVE_GETADDRINFO 1
+# define HAVE_GETADDRINFO_THREADSAFE 1
+# define HAVE_GETNAMEINFO 1
+# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501)
+# define HAVE_FREEADDRINFO 1
+# define HAVE_GETADDRINFO 1
+# define HAVE_GETADDRINFO_THREADSAFE 1
+# define HAVE_GETNAMEINFO 1
+# elif defined(_MSC_VER) && (_MSC_VER >= 1200)
+# define HAVE_FREEADDRINFO 1
+# define HAVE_GETADDRINFO 1
+# define HAVE_GETADDRINFO_THREADSAFE 1
+# define HAVE_GETNAMEINFO 1
+# endif
+#endif
+
+#if defined(__POCC__)
+# ifndef _MSC_VER
+# error Microsoft extensions /Ze compiler option is required
+# endif
+# ifndef __POCC__OLDNAMES
+# error Compatibility names /Go compiler option is required
+# endif
+#endif
+
+/* ---------------------------------------------------------------- */
+/* STRUCT RELATED */
+/* ---------------------------------------------------------------- */
+
+/* Define if you have struct sockaddr_storage. */
+#if !defined(__SALFORDC__) && !defined(__BORLANDC__)
+#define HAVE_STRUCT_SOCKADDR_STORAGE 1
+#endif
+
+/* Define if you have struct timeval. */
+#define HAVE_STRUCT_TIMEVAL 1
+
+/* Define if struct sockaddr_in6 has the sin6_scope_id member. */
+#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
+
#if defined(HAVE_WINSOCK2_H) && defined(_WIN32_WINNT) && \
(_WIN32_WINNT >= 0x0600)
-#define HAVE_STRUCT_POLLFD 1
-#endif
-
-/* ---------------------------------------------------------------- */
-/* LARGE FILE SUPPORT */
-/* ---------------------------------------------------------------- */
-
-#if defined(_MSC_VER) && !defined(_WIN32_WCE)
-# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
-# define USE_WIN32_LARGE_FILES
-# else
-# define USE_WIN32_SMALL_FILES
-# endif
-#endif
-
-#if defined(__MINGW32__) && !defined(USE_WIN32_LARGE_FILES)
-# define USE_WIN32_LARGE_FILES
-#endif
-
-#if defined(__WATCOMC__) && !defined(USE_WIN32_LARGE_FILES)
-# define USE_WIN32_LARGE_FILES
-#endif
-
-#if defined(__POCC__)
-# undef USE_WIN32_LARGE_FILES
-#endif
-
-#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES)
-# define USE_WIN32_SMALL_FILES
-#endif
-
-/* ---------------------------------------------------------------- */
-/* DNS RESOLVER SPECIALTY */
-/* ---------------------------------------------------------------- */
-
-/*
- * Undefine both USE_ARES and USE_THREADS_WIN32 for synchronous DNS.
- */
-
-/* Define to enable c-ares asynchronous DNS lookups. */
+#define HAVE_STRUCT_POLLFD 1
+#endif
+
+/* ---------------------------------------------------------------- */
+/* LARGE FILE SUPPORT */
+/* ---------------------------------------------------------------- */
+
+#if defined(_MSC_VER) && !defined(_WIN32_WCE)
+# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
+# define USE_WIN32_LARGE_FILES
+# else
+# define USE_WIN32_SMALL_FILES
+# endif
+#endif
+
+#if defined(__MINGW32__) && !defined(USE_WIN32_LARGE_FILES)
+# define USE_WIN32_LARGE_FILES
+#endif
+
+#if defined(__WATCOMC__) && !defined(USE_WIN32_LARGE_FILES)
+# define USE_WIN32_LARGE_FILES
+#endif
+
+#if defined(__POCC__)
+# undef USE_WIN32_LARGE_FILES
+#endif
+
+#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES)
+# define USE_WIN32_SMALL_FILES
+#endif
+
+/* ---------------------------------------------------------------- */
+/* DNS RESOLVER SPECIALTY */
+/* ---------------------------------------------------------------- */
+
+/*
+ * Undefine both USE_ARES and USE_THREADS_WIN32 for synchronous DNS.
+ */
+
+/* Define to enable c-ares asynchronous DNS lookups. */
/* #define USE_ARES 1 */
-
-/* Default define to enable threaded asynchronous DNS lookups. */
-#if !defined(USE_SYNC_DNS) && !defined(USE_ARES) && \
- !defined(USE_THREADS_WIN32)
-# define USE_THREADS_WIN32 1
-#endif
-
-#if defined(USE_ARES) && defined(USE_THREADS_WIN32)
-# error "Only one DNS lookup specialty may be defined at most"
-#endif
-
-/* ---------------------------------------------------------------- */
-/* LDAP SUPPORT */
-/* ---------------------------------------------------------------- */
-
-#if defined(CURL_HAS_NOVELL_LDAPSDK) || defined(CURL_HAS_MOZILLA_LDAPSDK)
+
+/* Default define to enable threaded asynchronous DNS lookups. */
+#if !defined(USE_SYNC_DNS) && !defined(USE_ARES) && \
+ !defined(USE_THREADS_WIN32)
+# define USE_THREADS_WIN32 1
+#endif
+
+#if defined(USE_ARES) && defined(USE_THREADS_WIN32)
+# error "Only one DNS lookup specialty may be defined at most"
+#endif
+
+/* ---------------------------------------------------------------- */
+/* LDAP SUPPORT */
+/* ---------------------------------------------------------------- */
+
+#if defined(CURL_HAS_NOVELL_LDAPSDK) || defined(CURL_HAS_MOZILLA_LDAPSDK)
#undef USE_WIN32_LDAP
-#define HAVE_LDAP_SSL_H 1
-#define HAVE_LDAP_URL_PARSE 1
-#elif defined(CURL_HAS_OPENLDAP_LDAPSDK)
+#define HAVE_LDAP_SSL_H 1
+#define HAVE_LDAP_URL_PARSE 1
+#elif defined(CURL_HAS_OPENLDAP_LDAPSDK)
#undef USE_WIN32_LDAP
-#define HAVE_LDAP_URL_PARSE 1
-#else
-#undef HAVE_LDAP_URL_PARSE
+#define HAVE_LDAP_URL_PARSE 1
+#else
+#undef HAVE_LDAP_URL_PARSE
#define HAVE_LDAP_SSL 1
#define USE_WIN32_LDAP 1
-#endif
-
+#endif
+
#if defined(__WATCOMC__) && defined(USE_WIN32_LDAP)
-#if __WATCOMC__ < 1280
-#define WINBERAPI __declspec(cdecl)
-#define WINLDAPAPI __declspec(cdecl)
-#endif
-#endif
-
+#if __WATCOMC__ < 1280
+#define WINBERAPI __declspec(cdecl)
+#define WINLDAPAPI __declspec(cdecl)
+#endif
+#endif
+
#if defined(__POCC__) && defined(USE_WIN32_LDAP)
-# define CURL_DISABLE_LDAP 1
-#endif
-
+# define CURL_DISABLE_LDAP 1
+#endif
+
/* Define to use the Windows crypto library. */
#if !defined(CURL_WINDOWS_APP)
#define USE_WIN32_CRYPTO
@@ -735,34 +735,34 @@ Vista
#endif
#endif
-/* ---------------------------------------------------------------- */
-/* ADDITIONAL DEFINITIONS */
-/* ---------------------------------------------------------------- */
-
-/* Define cpu-machine-OS */
-#undef OS
-#if defined(_M_IX86) || defined(__i386__) /* x86 (MSVC or gcc) */
-#define OS "i386-pc-win32"
-#elif defined(_M_X64) || defined(__x86_64__) /* x86_64 (MSVC >=2005 or gcc) */
-#define OS "x86_64-pc-win32"
+/* ---------------------------------------------------------------- */
+/* ADDITIONAL DEFINITIONS */
+/* ---------------------------------------------------------------- */
+
+/* Define cpu-machine-OS */
+#undef OS
+#if defined(_M_IX86) || defined(__i386__) /* x86 (MSVC or gcc) */
+#define OS "i386-pc-win32"
+#elif defined(_M_X64) || defined(__x86_64__) /* x86_64 (MSVC >=2005 or gcc) */
+#define OS "x86_64-pc-win32"
#elif defined(_M_IA64) || defined(__ia64__) /* Itanium */
-#define OS "ia64-pc-win32"
+#define OS "ia64-pc-win32"
#elif defined(_M_ARM_NT) || defined(__arm__) /* ARMv7-Thumb2 (Windows RT) */
#define OS "thumbv7a-pc-win32"
#elif defined(_M_ARM64) || defined(__aarch64__) /* ARM64 (Windows 10) */
#define OS "aarch64-pc-win32"
-#else
-#define OS "unknown-pc-win32"
-#endif
-
-/* Name of package */
-#define PACKAGE "curl"
-
-/* If you want to build curl with the built-in manual */
-#define USE_MANUAL 1
-
+#else
+#define OS "unknown-pc-win32"
+#endif
+
+/* Name of package */
+#define PACKAGE "curl"
+
+/* If you want to build curl with the built-in manual */
+#define USE_MANUAL 1
+
#if defined(__POCC__) || defined(USE_IPV6)
-# define ENABLE_IPV6 1
-#endif
-
-#endif /* HEADER_CURL_CONFIG_WIN32_H */
+# define ENABLE_IPV6 1
+#endif
+
+#endif /* HEADER_CURL_CONFIG_WIN32_H */
diff --git a/contrib/libs/curl/lib/config-win32ce.h b/contrib/libs/curl/lib/config-win32ce.h
index 271c22116a..9060836944 100644
--- a/contrib/libs/curl/lib/config-win32ce.h
+++ b/contrib/libs/curl/lib/config-win32ce.h
@@ -1,448 +1,448 @@
-#ifndef HEADER_CURL_CONFIG_WIN32CE_H
-#define HEADER_CURL_CONFIG_WIN32CE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONFIG_WIN32CE_H
+#define HEADER_CURL_CONFIG_WIN32CE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* lib/config-win32ce.h - Hand crafted config file for windows ce */
-/* ================================================================ */
-
-/* ---------------------------------------------------------------- */
-/* HEADER FILES */
-/* ---------------------------------------------------------------- */
-
-/* Define if you have the <arpa/inet.h> header file. */
-/* #define HAVE_ARPA_INET_H 1 */
-
-/* Define if you have the <assert.h> header file. */
-/* #define HAVE_ASSERT_H 1 */
-
-/* Define if you have the <crypto.h> header file. */
-/* #define HAVE_CRYPTO_H 1 */
-
-/* Define if you have the <errno.h> header file. */
-/* #define HAVE_ERRNO_H 1 */
-
-/* Define if you have the <err.h> header file. */
-/* #define HAVE_ERR_H 1 */
-
-/* Define if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define if you have the <getopt.h> header file. */
-/* #define HAVE_GETOPT_H 1 */
-
-/* Define if you have the <io.h> header file. */
-#define HAVE_IO_H 1
-
-/* Define if you need the malloc.h header header file even with stdlib.h */
-#define NEED_MALLOC_H 1
-
-/* Define if you have the <netdb.h> header file. */
-/* #define HAVE_NETDB_H 1 */
-
-/* Define if you have the <netinet/in.h> header file. */
-/* #define HAVE_NETINET_IN_H 1 */
-
-/* Define if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define if you have the <sgtty.h> header file. */
-/* #define HAVE_SGTTY_H 1 */
-
-/* Define if you have the <ssl.h> header file. */
-/* #define HAVE_SSL_H 1 */
-
-/* Define if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define if you have the <process.h> header file. */
-/* #define HAVE_PROCESS_H 1 */
-
-/* Define if you have the <sys/param.h> header file. */
-/* #define HAVE_SYS_PARAM_H 1 */
-
-/* Define if you have the <sys/select.h> header file. */
-/* #define HAVE_SYS_SELECT_H 1 */
-
-/* Define if you have the <sys/socket.h> header file. */
-/* #define HAVE_SYS_SOCKET_H 1 */
-
-/* Define if you have the <sys/sockio.h> header file. */
-/* #define HAVE_SYS_SOCKIO_H 1 */
-
-/* Define if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define if you have the <sys/time.h> header file */
-/* #define HAVE_SYS_TIME_H 1 */
-
-/* Define if you have the <sys/types.h> header file. */
-/* #define HAVE_SYS_TYPES_H 1 */
-
-/* Define if you have the <sys/utime.h> header file */
-#define HAVE_SYS_UTIME_H 1
-
-/* Define if you have the <termio.h> header file. */
-/* #define HAVE_TERMIO_H 1 */
-
-/* Define if you have the <termios.h> header file. */
-/* #define HAVE_TERMIOS_H 1 */
-
-/* Define if you have the <time.h> header file. */
-#define HAVE_TIME_H 1
-
-/* Define if you have the <unistd.h> header file. */
-#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__)
-#define HAVE_UNISTD_H 1
-#endif
-
-/* Define if you have the <windows.h> header file. */
-#define HAVE_WINDOWS_H 1
-
-/* Define if you have the <winsock.h> header file. */
-#define HAVE_WINSOCK_H 1
-
-/* Define if you have the <winsock2.h> header file. */
-/* #define HAVE_WINSOCK2_H 1 */
-
-/* Define if you have the <ws2tcpip.h> header file. */
-/* #define HAVE_WS2TCPIP_H 1 */
-
-/* ---------------------------------------------------------------- */
-/* OTHER HEADER INFO */
-/* ---------------------------------------------------------------- */
-
-/* Define if sig_atomic_t is an available typedef. */
-#define HAVE_SIG_ATOMIC_T 1
-
-/* Define if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define if you can safely include both <sys/time.h> and <time.h>. */
-/* #define TIME_WITH_SYS_TIME 1 */
-
-/* ---------------------------------------------------------------- */
-/* FUNCTIONS */
-/* ---------------------------------------------------------------- */
-
-/* Define if you have the closesocket function. */
-#define HAVE_CLOSESOCKET 1
-
-/* Define if you don't have vprintf but do have _doprnt. */
-/* #define HAVE_DOPRNT 1 */
-
-/* Define if you have the gethostbyaddr function. */
-#define HAVE_GETHOSTBYADDR 1
-
-/* Define if you have the gethostname function. */
-#define HAVE_GETHOSTNAME 1
-
-/* Define if you have the getpass function. */
-/* #define HAVE_GETPASS 1 */
-
-/* Define if you have the getservbyname function. */
-#define HAVE_GETSERVBYNAME 1
-
-/* Define if you have the gettimeofday function. */
-/* #define HAVE_GETTIMEOFDAY 1 */
-
-/* Define if you have the inet_addr function. */
-#define HAVE_INET_ADDR 1
-
-/* Define if you have the ioctlsocket function. */
-#define HAVE_IOCTLSOCKET 1
-
-/* Define if you have a working ioctlsocket FIONBIO function. */
-#define HAVE_IOCTLSOCKET_FIONBIO 1
-
-/* Define if you have the perror function. */
-#define HAVE_PERROR 1
-
-/* Define if you have the RAND_screen function when using SSL */
-#define HAVE_RAND_SCREEN 1
-
-/* Define if you have the `RAND_status' function when using SSL. */
-#define HAVE_RAND_STATUS 1
-
-/* Define if you have the select function. */
-#define HAVE_SELECT 1
-
-/* Define if you have the setvbuf function. */
-#define HAVE_SETVBUF 1
-
-/* Define if you have the socket function. */
-#define HAVE_SOCKET 1
-
-/* Define if you have the strcasecmp function. */
-/* #define HAVE_STRCASECMP 1 */
-
-/* Define if you have the strdup function. */
-/* #define HAVE_STRDUP 1 */
-
-/* Define if you have the strftime function. */
-/* #define HAVE_STRFTIME 1 */
-
-/* Define if you have the stricmp function. */
-/* #define HAVE_STRICMP 1 */
-
-/* Define if you have the strncasecmp function. */
-/* #define HAVE_STRNCASECMP 1 */
-
-/* Define if you have the strnicmp function. */
-/* #define HAVE_STRNICMP 1 */
-
-/* Define if you have the strstr function. */
-#define HAVE_STRSTR 1
-
-/* Define if you have the strtoll function. */
-#if defined(__MINGW32__) || defined(__WATCOMC__)
-#define HAVE_STRTOLL 1
-#endif
-
-/* Define if you have the tcgetattr function. */
-/* #define HAVE_TCGETATTR 1 */
-
-/* Define if you have the tcsetattr function. */
-/* #define HAVE_TCSETATTR 1 */
-
-/* Define if you have the utime function */
-#define HAVE_UTIME 1
-
-/* Define if you have the getnameinfo function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to the type qualifier of arg 1 for getnameinfo. */
-#define GETNAMEINFO_QUAL_ARG1 const
-
-/* Define to the type of arg 1 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
-
-/* Define to the type of arg 2 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG2 socklen_t
-
-/* Define to the type of args 4 and 6 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG46 DWORD
-
-/* Define to the type of arg 7 for getnameinfo. */
-#define GETNAMEINFO_TYPE_ARG7 int
-
-/* Define if you have the recv function. */
-#define HAVE_RECV 1
-
-/* Define to the type of arg 1 for recv. */
-#define RECV_TYPE_ARG1 SOCKET
-
-/* Define to the type of arg 2 for recv. */
-#define RECV_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for recv. */
-#define RECV_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recv. */
-#define RECV_TYPE_ARG4 int
-
-/* Define to the function return type for recv. */
-#define RECV_TYPE_RETV int
-
-/* Define if you have the recvfrom function. */
-#define HAVE_RECVFROM 1
-
-/* Define to the type of arg 1 for recvfrom. */
-#define RECVFROM_TYPE_ARG1 SOCKET
-
-/* Define to the type pointed by arg 2 for recvfrom. */
-#define RECVFROM_TYPE_ARG2 char
-
-/* Define to the type of arg 3 for recvfrom. */
-#define RECVFROM_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for recvfrom. */
-#define RECVFROM_TYPE_ARG4 int
-
-/* Define to the type pointed by arg 5 for recvfrom. */
-#define RECVFROM_TYPE_ARG5 struct sockaddr
-
-/* Define to the type pointed by arg 6 for recvfrom. */
-#define RECVFROM_TYPE_ARG6 int
-
-/* Define to the function return type for recvfrom. */
-#define RECVFROM_TYPE_RETV int
-
-/* Define if you have the send function. */
-#define HAVE_SEND 1
-
-/* Define to the type of arg 1 for send. */
-#define SEND_TYPE_ARG1 SOCKET
-
-/* Define to the type qualifier of arg 2 for send. */
-#define SEND_QUAL_ARG2 const
-
-/* Define to the type of arg 2 for send. */
-#define SEND_TYPE_ARG2 char *
-
-/* Define to the type of arg 3 for send. */
-#define SEND_TYPE_ARG3 int
-
-/* Define to the type of arg 4 for send. */
-#define SEND_TYPE_ARG4 int
-
-/* Define to the function return type for send. */
-#define SEND_TYPE_RETV int
-
-/* ---------------------------------------------------------------- */
-/* TYPEDEF REPLACEMENTS */
-/* ---------------------------------------------------------------- */
-
-/* Define this if in_addr_t is not an available 'typedefed' type */
-#define in_addr_t unsigned long
-
-/* Define as the return type of signal handlers (int or void). */
-#define RETSIGTYPE void
-
-/* Define ssize_t if it is not an available 'typedefed' type */
-#if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || defined(__POCC__)
-#elif defined(_WIN64)
-#define ssize_t __int64
-#else
-#define ssize_t int
-#endif
-
-/* ---------------------------------------------------------------- */
-/* TYPE SIZES */
-/* ---------------------------------------------------------------- */
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long double', as computed by sizeof. */
-#define SIZEOF_LONG_DOUBLE 16
-
-/* The size of `long long', as computed by sizeof. */
-/* #define SIZEOF_LONG_LONG 8 */
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* ================================================================ */
+/* lib/config-win32ce.h - Hand crafted config file for windows ce */
+/* ================================================================ */
+
+/* ---------------------------------------------------------------- */
+/* HEADER FILES */
+/* ---------------------------------------------------------------- */
+
+/* Define if you have the <arpa/inet.h> header file. */
+/* #define HAVE_ARPA_INET_H 1 */
+
+/* Define if you have the <assert.h> header file. */
+/* #define HAVE_ASSERT_H 1 */
+
+/* Define if you have the <crypto.h> header file. */
+/* #define HAVE_CRYPTO_H 1 */
+
+/* Define if you have the <errno.h> header file. */
+/* #define HAVE_ERRNO_H 1 */
+
+/* Define if you have the <err.h> header file. */
+/* #define HAVE_ERR_H 1 */
+
+/* Define if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define if you have the <getopt.h> header file. */
+/* #define HAVE_GETOPT_H 1 */
+
+/* Define if you have the <io.h> header file. */
+#define HAVE_IO_H 1
+
+/* Define if you need the malloc.h header header file even with stdlib.h */
+#define NEED_MALLOC_H 1
+
+/* Define if you have the <netdb.h> header file. */
+/* #define HAVE_NETDB_H 1 */
+
+/* Define if you have the <netinet/in.h> header file. */
+/* #define HAVE_NETINET_IN_H 1 */
+
+/* Define if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* Define if you have the <sgtty.h> header file. */
+/* #define HAVE_SGTTY_H 1 */
+
+/* Define if you have the <ssl.h> header file. */
+/* #define HAVE_SSL_H 1 */
+
+/* Define if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define if you have the <process.h> header file. */
+/* #define HAVE_PROCESS_H 1 */
+
+/* Define if you have the <sys/param.h> header file. */
+/* #define HAVE_SYS_PARAM_H 1 */
+
+/* Define if you have the <sys/select.h> header file. */
+/* #define HAVE_SYS_SELECT_H 1 */
+
+/* Define if you have the <sys/socket.h> header file. */
+/* #define HAVE_SYS_SOCKET_H 1 */
+
+/* Define if you have the <sys/sockio.h> header file. */
+/* #define HAVE_SYS_SOCKIO_H 1 */
+
+/* Define if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define if you have the <sys/time.h> header file */
+/* #define HAVE_SYS_TIME_H 1 */
+
+/* Define if you have the <sys/types.h> header file. */
+/* #define HAVE_SYS_TYPES_H 1 */
+
+/* Define if you have the <sys/utime.h> header file */
+#define HAVE_SYS_UTIME_H 1
+
+/* Define if you have the <termio.h> header file. */
+/* #define HAVE_TERMIO_H 1 */
+
+/* Define if you have the <termios.h> header file. */
+/* #define HAVE_TERMIOS_H 1 */
+
+/* Define if you have the <time.h> header file. */
+#define HAVE_TIME_H 1
+
+/* Define if you have the <unistd.h> header file. */
+#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__)
+#define HAVE_UNISTD_H 1
+#endif
+
+/* Define if you have the <windows.h> header file. */
+#define HAVE_WINDOWS_H 1
+
+/* Define if you have the <winsock.h> header file. */
+#define HAVE_WINSOCK_H 1
+
+/* Define if you have the <winsock2.h> header file. */
+/* #define HAVE_WINSOCK2_H 1 */
+
+/* Define if you have the <ws2tcpip.h> header file. */
+/* #define HAVE_WS2TCPIP_H 1 */
+
+/* ---------------------------------------------------------------- */
+/* OTHER HEADER INFO */
+/* ---------------------------------------------------------------- */
+
+/* Define if sig_atomic_t is an available typedef. */
+#define HAVE_SIG_ATOMIC_T 1
+
+/* Define if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define if you can safely include both <sys/time.h> and <time.h>. */
+/* #define TIME_WITH_SYS_TIME 1 */
+
+/* ---------------------------------------------------------------- */
+/* FUNCTIONS */
+/* ---------------------------------------------------------------- */
+
+/* Define if you have the closesocket function. */
+#define HAVE_CLOSESOCKET 1
+
+/* Define if you don't have vprintf but do have _doprnt. */
+/* #define HAVE_DOPRNT 1 */
+
+/* Define if you have the gethostbyaddr function. */
+#define HAVE_GETHOSTBYADDR 1
+
+/* Define if you have the gethostname function. */
+#define HAVE_GETHOSTNAME 1
+
+/* Define if you have the getpass function. */
+/* #define HAVE_GETPASS 1 */
+
+/* Define if you have the getservbyname function. */
+#define HAVE_GETSERVBYNAME 1
+
+/* Define if you have the gettimeofday function. */
+/* #define HAVE_GETTIMEOFDAY 1 */
+
+/* Define if you have the inet_addr function. */
+#define HAVE_INET_ADDR 1
+
+/* Define if you have the ioctlsocket function. */
+#define HAVE_IOCTLSOCKET 1
+
+/* Define if you have a working ioctlsocket FIONBIO function. */
+#define HAVE_IOCTLSOCKET_FIONBIO 1
+
+/* Define if you have the perror function. */
+#define HAVE_PERROR 1
+
+/* Define if you have the RAND_screen function when using SSL */
+#define HAVE_RAND_SCREEN 1
+
+/* Define if you have the `RAND_status' function when using SSL. */
+#define HAVE_RAND_STATUS 1
+
+/* Define if you have the select function. */
+#define HAVE_SELECT 1
+
+/* Define if you have the setvbuf function. */
+#define HAVE_SETVBUF 1
+
+/* Define if you have the socket function. */
+#define HAVE_SOCKET 1
+
+/* Define if you have the strcasecmp function. */
+/* #define HAVE_STRCASECMP 1 */
+
+/* Define if you have the strdup function. */
+/* #define HAVE_STRDUP 1 */
+
+/* Define if you have the strftime function. */
+/* #define HAVE_STRFTIME 1 */
+
+/* Define if you have the stricmp function. */
+/* #define HAVE_STRICMP 1 */
+
+/* Define if you have the strncasecmp function. */
+/* #define HAVE_STRNCASECMP 1 */
+
+/* Define if you have the strnicmp function. */
+/* #define HAVE_STRNICMP 1 */
+
+/* Define if you have the strstr function. */
+#define HAVE_STRSTR 1
+
+/* Define if you have the strtoll function. */
+#if defined(__MINGW32__) || defined(__WATCOMC__)
+#define HAVE_STRTOLL 1
+#endif
+
+/* Define if you have the tcgetattr function. */
+/* #define HAVE_TCGETATTR 1 */
+
+/* Define if you have the tcsetattr function. */
+/* #define HAVE_TCSETATTR 1 */
+
+/* Define if you have the utime function */
+#define HAVE_UTIME 1
+
+/* Define if you have the getnameinfo function. */
+#define HAVE_GETNAMEINFO 1
+
+/* Define to the type qualifier of arg 1 for getnameinfo. */
+#define GETNAMEINFO_QUAL_ARG1 const
+
+/* Define to the type of arg 1 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
+
+/* Define to the type of arg 2 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG2 socklen_t
+
+/* Define to the type of args 4 and 6 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG46 DWORD
+
+/* Define to the type of arg 7 for getnameinfo. */
+#define GETNAMEINFO_TYPE_ARG7 int
+
+/* Define if you have the recv function. */
+#define HAVE_RECV 1
+
+/* Define to the type of arg 1 for recv. */
+#define RECV_TYPE_ARG1 SOCKET
+
+/* Define to the type of arg 2 for recv. */
+#define RECV_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for recv. */
+#define RECV_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recv. */
+#define RECV_TYPE_ARG4 int
+
+/* Define to the function return type for recv. */
+#define RECV_TYPE_RETV int
+
+/* Define if you have the recvfrom function. */
+#define HAVE_RECVFROM 1
+
+/* Define to the type of arg 1 for recvfrom. */
+#define RECVFROM_TYPE_ARG1 SOCKET
+
+/* Define to the type pointed by arg 2 for recvfrom. */
+#define RECVFROM_TYPE_ARG2 char
+
+/* Define to the type of arg 3 for recvfrom. */
+#define RECVFROM_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for recvfrom. */
+#define RECVFROM_TYPE_ARG4 int
+
+/* Define to the type pointed by arg 5 for recvfrom. */
+#define RECVFROM_TYPE_ARG5 struct sockaddr
+
+/* Define to the type pointed by arg 6 for recvfrom. */
+#define RECVFROM_TYPE_ARG6 int
+
+/* Define to the function return type for recvfrom. */
+#define RECVFROM_TYPE_RETV int
+
+/* Define if you have the send function. */
+#define HAVE_SEND 1
+
+/* Define to the type of arg 1 for send. */
+#define SEND_TYPE_ARG1 SOCKET
+
+/* Define to the type qualifier of arg 2 for send. */
+#define SEND_QUAL_ARG2 const
+
+/* Define to the type of arg 2 for send. */
+#define SEND_TYPE_ARG2 char *
+
+/* Define to the type of arg 3 for send. */
+#define SEND_TYPE_ARG3 int
+
+/* Define to the type of arg 4 for send. */
+#define SEND_TYPE_ARG4 int
+
+/* Define to the function return type for send. */
+#define SEND_TYPE_RETV int
+
+/* ---------------------------------------------------------------- */
+/* TYPEDEF REPLACEMENTS */
+/* ---------------------------------------------------------------- */
+
+/* Define this if in_addr_t is not an available 'typedefed' type */
+#define in_addr_t unsigned long
+
+/* Define as the return type of signal handlers (int or void). */
+#define RETSIGTYPE void
+
+/* Define ssize_t if it is not an available 'typedefed' type */
+#if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || defined(__POCC__)
+#elif defined(_WIN64)
+#define ssize_t __int64
+#else
+#define ssize_t int
+#endif
+
+/* ---------------------------------------------------------------- */
+/* TYPE SIZES */
+/* ---------------------------------------------------------------- */
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `long double', as computed by sizeof. */
+#define SIZEOF_LONG_DOUBLE 16
+
+/* The size of `long long', as computed by sizeof. */
+/* #define SIZEOF_LONG_LONG 8 */
+
+/* The size of `short', as computed by sizeof. */
+#define SIZEOF_SHORT 2
+
/* Define to the size of `long', as computed by sizeof. */
#define SIZEOF_LONG 4
-/* The size of `size_t', as computed by sizeof. */
-#if defined(_WIN64)
-# define SIZEOF_SIZE_T 8
-#else
-# define SIZEOF_SIZE_T 4
-#endif
-
-/* ---------------------------------------------------------------- */
-/* STRUCT RELATED */
-/* ---------------------------------------------------------------- */
-
-/* Define this if you have struct sockaddr_storage */
-/* #define HAVE_STRUCT_SOCKADDR_STORAGE 1 */
-
-/* Define this if you have struct timeval */
-#define HAVE_STRUCT_TIMEVAL 1
-
-/* Define this if struct sockaddr_in6 has the sin6_scope_id member */
-#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
-
-/* ---------------------------------------------------------------- */
-/* COMPILER SPECIFIC */
-/* ---------------------------------------------------------------- */
-
-/* Undef keyword 'const' if it does not work. */
-/* #undef const */
-
-/* Define to avoid VS2005 complaining about portable C functions */
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
-#define _CRT_SECURE_NO_DEPRECATE 1
-#define _CRT_NONSTDC_NO_DEPRECATE 1
-#endif
-
+/* The size of `size_t', as computed by sizeof. */
+#if defined(_WIN64)
+# define SIZEOF_SIZE_T 8
+#else
+# define SIZEOF_SIZE_T 4
+#endif
+
+/* ---------------------------------------------------------------- */
+/* STRUCT RELATED */
+/* ---------------------------------------------------------------- */
+
+/* Define this if you have struct sockaddr_storage */
+/* #define HAVE_STRUCT_SOCKADDR_STORAGE 1 */
+
+/* Define this if you have struct timeval */
+#define HAVE_STRUCT_TIMEVAL 1
+
+/* Define this if struct sockaddr_in6 has the sin6_scope_id member */
+#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
+
+/* ---------------------------------------------------------------- */
+/* COMPILER SPECIFIC */
+/* ---------------------------------------------------------------- */
+
+/* Undef keyword 'const' if it does not work. */
+/* #undef const */
+
+/* Define to avoid VS2005 complaining about portable C functions */
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+#define _CRT_SECURE_NO_DEPRECATE 1
+#define _CRT_NONSTDC_NO_DEPRECATE 1
+#endif
+
/* VS2005 and later default size for time_t is 64-bit, unless */
-/* _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
-# ifndef _USE_32BIT_TIME_T
-# define SIZEOF_TIME_T 8
-# else
-# define SIZEOF_TIME_T 4
-# endif
-#endif
-
-/* ---------------------------------------------------------------- */
-/* LARGE FILE SUPPORT */
-/* ---------------------------------------------------------------- */
-
-#if defined(_MSC_VER) && !defined(_WIN32_WCE)
-# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
-# define USE_WIN32_LARGE_FILES
-# else
-# define USE_WIN32_SMALL_FILES
-# endif
-#endif
-
-#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES)
-# define USE_WIN32_SMALL_FILES
-#endif
-
-/* ---------------------------------------------------------------- */
-/* LDAP SUPPORT */
-/* ---------------------------------------------------------------- */
-
+/* _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+# ifndef _USE_32BIT_TIME_T
+# define SIZEOF_TIME_T 8
+# else
+# define SIZEOF_TIME_T 4
+# endif
+#endif
+
+/* ---------------------------------------------------------------- */
+/* LARGE FILE SUPPORT */
+/* ---------------------------------------------------------------- */
+
+#if defined(_MSC_VER) && !defined(_WIN32_WCE)
+# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
+# define USE_WIN32_LARGE_FILES
+# else
+# define USE_WIN32_SMALL_FILES
+# endif
+#endif
+
+#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES)
+# define USE_WIN32_SMALL_FILES
+#endif
+
+/* ---------------------------------------------------------------- */
+/* LDAP SUPPORT */
+/* ---------------------------------------------------------------- */
+
#define USE_WIN32_LDAP 1
-#undef HAVE_LDAP_URL_PARSE
-
-/* ---------------------------------------------------------------- */
-/* ADDITIONAL DEFINITIONS */
-/* ---------------------------------------------------------------- */
-
-/* Define cpu-machine-OS */
-#undef OS
-#define OS "i386-pc-win32ce"
-
-/* Name of package */
-#define PACKAGE "curl"
-
-/* ---------------------------------------------------------------- */
-/* WinCE */
-/* ---------------------------------------------------------------- */
-
-#ifndef UNICODE
-# define UNICODE
-#endif
-
-#ifndef _UNICODE
-# define _UNICODE
-#endif
-
-#define CURL_DISABLE_FILE 1
-#define CURL_DISABLE_TELNET 1
-#define CURL_DISABLE_LDAP 1
-
-#define ENOSPC 1
-#define ENOMEM 2
-#define EAGAIN 3
-
+#undef HAVE_LDAP_URL_PARSE
+
+/* ---------------------------------------------------------------- */
+/* ADDITIONAL DEFINITIONS */
+/* ---------------------------------------------------------------- */
+
+/* Define cpu-machine-OS */
+#undef OS
+#define OS "i386-pc-win32ce"
+
+/* Name of package */
+#define PACKAGE "curl"
+
+/* ---------------------------------------------------------------- */
+/* WinCE */
+/* ---------------------------------------------------------------- */
+
+#ifndef UNICODE
+# define UNICODE
+#endif
+
+#ifndef _UNICODE
+# define _UNICODE
+#endif
+
+#define CURL_DISABLE_FILE 1
+#define CURL_DISABLE_TELNET 1
+#define CURL_DISABLE_LDAP 1
+
+#define ENOSPC 1
+#define ENOMEM 2
+#define EAGAIN 3
+
extern int stat(const char *path, struct stat *buffer);
-
-#endif /* HEADER_CURL_CONFIG_WIN32CE_H */
+
+#endif /* HEADER_CURL_CONFIG_WIN32CE_H */
diff --git a/contrib/libs/curl/lib/conncache.c b/contrib/libs/curl/lib/conncache.c
index 9e52990832..cb3170c480 100644
--- a/contrib/libs/curl/lib/conncache.c
+++ b/contrib/libs/curl/lib/conncache.c
@@ -1,45 +1,45 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2012 - 2016, Linus Nielsen Feltzing, <linus@haxx.se>
* Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "url.h"
-#include "progress.h"
-#include "multiif.h"
-#include "sendf.h"
-#include "conncache.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "url.h"
+#include "progress.h"
+#include "multiif.h"
+#include "sendf.h"
+#include "conncache.h"
#include "share.h"
#include "sigpipe.h"
#include "connect.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
#define HASHKEY_SIZE 128
static void conn_llist_dtor(void *user, void *element)
@@ -103,43 +103,43 @@ static int bundle_remove_conn(struct connectbundle *bundle,
return 0;
}
-static void free_bundle_hash_entry(void *freethis)
-{
- struct connectbundle *b = (struct connectbundle *) freethis;
-
+static void free_bundle_hash_entry(void *freethis)
+{
+ struct connectbundle *b = (struct connectbundle *) freethis;
+
bundle_destroy(b);
-}
-
+}
+
int Curl_conncache_init(struct conncache *connc, int size)
-{
+{
int rc;
-
+
/* allocate a new easy handle to use when closing cached connections */
connc->closure_handle = curl_easy_init();
if(!connc->closure_handle)
return 1; /* bad */
-
+
rc = Curl_hash_init(&connc->hash, size, Curl_hash_str,
Curl_str_key_compare, free_bundle_hash_entry);
if(rc)
Curl_close(&connc->closure_handle);
else
connc->closure_handle->state.conn_cache = connc;
-
+
return rc;
-}
-
-void Curl_conncache_destroy(struct conncache *connc)
-{
+}
+
+void Curl_conncache_destroy(struct conncache *connc)
+{
if(connc)
Curl_hash_destroy(&connc->hash);
-}
-
+}
+
/* creates a key to find a bundle for this connection */
static void hashkey(struct connectdata *conn, char *buf,
size_t len, /* something like 128 is fine */
const char **hostp)
-{
+{
const char *hostname;
long port = conn->remote_port;
@@ -183,67 +183,67 @@ struct connectbundle *Curl_conncache_find_bundle(struct connectdata *conn,
struct conncache *connc,
const char **hostp)
{
- struct connectbundle *bundle = NULL;
+ struct connectbundle *bundle = NULL;
CONNCACHE_LOCK(conn->data);
if(connc) {
char key[HASHKEY_SIZE];
hashkey(conn, key, sizeof(key), hostp);
bundle = Curl_hash_pick(&connc->hash, key, strlen(key));
}
-
- return bundle;
-}
-
-static bool conncache_add_bundle(struct conncache *connc,
+
+ return bundle;
+}
+
+static bool conncache_add_bundle(struct conncache *connc,
char *key,
- struct connectbundle *bundle)
-{
+ struct connectbundle *bundle)
+{
void *p = Curl_hash_add(&connc->hash, key, strlen(key), bundle);
-
- return p?TRUE:FALSE;
-}
-
-static void conncache_remove_bundle(struct conncache *connc,
- struct connectbundle *bundle)
-{
+
+ return p?TRUE:FALSE;
+}
+
+static void conncache_remove_bundle(struct conncache *connc,
+ struct connectbundle *bundle)
+{
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
-
- if(!connc)
- return;
-
+
+ if(!connc)
+ return;
+
Curl_hash_start_iterate(&connc->hash, &iter);
-
- he = Curl_hash_next_element(&iter);
- while(he) {
- if(he->ptr == bundle) {
- /* The bundle is destroyed by the hash destructor function,
- free_bundle_hash_entry() */
+
+ he = Curl_hash_next_element(&iter);
+ while(he) {
+ if(he->ptr == bundle) {
+ /* The bundle is destroyed by the hash destructor function,
+ free_bundle_hash_entry() */
Curl_hash_delete(&connc->hash, he->key, he->key_len);
- return;
- }
-
- he = Curl_hash_next_element(&iter);
- }
-}
-
-CURLcode Curl_conncache_add_conn(struct conncache *connc,
- struct connectdata *conn)
-{
+ return;
+ }
+
+ he = Curl_hash_next_element(&iter);
+ }
+}
+
+CURLcode Curl_conncache_add_conn(struct conncache *connc,
+ struct connectdata *conn)
+{
CURLcode result = CURLE_OK;
struct connectbundle *bundle = NULL;
struct Curl_easy *data = conn->data;
-
+
/* *find_bundle() locks the connection cache */
bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache, NULL);
- if(!bundle) {
+ if(!bundle) {
int rc;
char key[HASHKEY_SIZE];
-
+
result = bundle_create(&bundle);
if(result) {
goto unlock;
- }
+ }
hashkey(conn, key, sizeof(key), NULL);
rc = conncache_add_bundle(data->state.conn_cache, key, bundle);
@@ -253,22 +253,22 @@ CURLcode Curl_conncache_add_conn(struct conncache *connc,
result = CURLE_OUT_OF_MEMORY;
goto unlock;
}
- }
-
+ }
+
bundle_add_conn(bundle, conn);
conn->connection_id = connc->next_connection_id++;
connc->num_conn++;
-
+
DEBUGF(infof(conn->data, "Added connection %ld. "
"The cache now contains %zu members\n",
conn->connection_id, connc->num_conn));
-
+
unlock:
CONNCACHE_UNLOCK(data);
return result;
-}
-
+}
+
/*
* Removes the connectdata object from the connection cache, but does *not*
* clear the conn->data association. The transfer still owns this connection.
@@ -278,83 +278,83 @@ CURLcode Curl_conncache_add_conn(struct conncache *connc,
*/
void Curl_conncache_remove_conn(struct Curl_easy *data,
struct connectdata *conn, bool lock)
-{
- struct connectbundle *bundle = conn->bundle;
+{
+ struct connectbundle *bundle = conn->bundle;
struct conncache *connc = data->state.conn_cache;
-
- /* The bundle pointer can be NULL, since this function can be called
- due to a failed connection attempt, before being added to a bundle */
- if(bundle) {
+
+ /* The bundle pointer can be NULL, since this function can be called
+ due to a failed connection attempt, before being added to a bundle */
+ if(bundle) {
if(lock) {
CONNCACHE_LOCK(data);
}
bundle_remove_conn(bundle, conn);
if(bundle->num_connections == 0)
- conncache_remove_bundle(connc, bundle);
+ conncache_remove_bundle(connc, bundle);
conn->bundle = NULL; /* removed from it */
if(connc) {
connc->num_conn--;
DEBUGF(infof(data, "The cache now contains %zu members\n",
connc->num_conn));
- }
+ }
if(lock) {
CONNCACHE_UNLOCK(data);
}
- }
-}
-
+ }
+}
+
/* This function iterates the entire connection cache and calls the function
func() with the connection pointer as the first argument and the supplied
'param' argument as the other.
-
+
The conncache lock is still held when the callback is called. It needs it,
so that it can safely continue traversing the lists once the callback
returns.
Returns 1 if the loop was aborted due to the callback's return code.
- Return 0 from func() to continue the loop, return 1 to abort it.
- */
+ Return 0 from func() to continue the loop, return 1 to abort it.
+ */
bool Curl_conncache_foreach(struct Curl_easy *data,
struct conncache *connc,
- void *param,
- int (*func)(struct connectdata *conn, void *param))
-{
+ void *param,
+ int (*func)(struct connectdata *conn, void *param))
+{
struct Curl_hash_iterator iter;
struct Curl_llist_element *curr;
struct Curl_hash_element *he;
-
- if(!connc)
+
+ if(!connc)
return FALSE;
-
+
CONNCACHE_LOCK(data);
Curl_hash_start_iterate(&connc->hash, &iter);
-
- he = Curl_hash_next_element(&iter);
- while(he) {
- struct connectbundle *bundle;
-
- bundle = he->ptr;
+
+ he = Curl_hash_next_element(&iter);
+ while(he) {
+ struct connectbundle *bundle;
+
+ bundle = he->ptr;
he = Curl_hash_next_element(&iter);
-
+
curr = bundle->conn_list.head;
- while(curr) {
- /* Yes, we need to update curr before calling func(), because func()
- might decide to remove the connection */
+ while(curr) {
+ /* Yes, we need to update curr before calling func(), because func()
+ might decide to remove the connection */
struct connectdata *conn = curr->ptr;
- curr = curr->next;
-
+ curr = curr->next;
+
if(1 == func(conn, param)) {
CONNCACHE_UNLOCK(data);
return TRUE;
}
- }
- }
+ }
+ }
CONNCACHE_UNLOCK(data);
return FALSE;
-}
-
-/* Return the first connection found in the cache. Used when closing all
+}
+
+/* Return the first connection found in the cache. Used when closing all
connections.
NOTE: no locking is done here as this is presumably only done when cleaning
@@ -362,29 +362,29 @@ bool Curl_conncache_foreach(struct Curl_easy *data,
*/
static struct connectdata *
conncache_find_first_connection(struct conncache *connc)
-{
+{
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
- struct connectbundle *bundle;
-
+ struct connectbundle *bundle;
+
Curl_hash_start_iterate(&connc->hash, &iter);
-
- he = Curl_hash_next_element(&iter);
- while(he) {
+
+ he = Curl_hash_next_element(&iter);
+ while(he) {
struct Curl_llist_element *curr;
- bundle = he->ptr;
-
+ bundle = he->ptr;
+
curr = bundle->conn_list.head;
- if(curr) {
- return curr->ptr;
- }
-
- he = Curl_hash_next_element(&iter);
- }
-
- return NULL;
-}
-
+ if(curr) {
+ return curr->ptr;
+ }
+
+ he = Curl_hash_next_element(&iter);
+ }
+
+ return NULL;
+}
+
/*
* Give ownership of a connection back to the connection cache. Might
* disconnect the oldest existing in there to make space.
@@ -567,39 +567,39 @@ void Curl_conncache_close_all_connections(struct conncache *connc)
}
}
-#if 0
-/* Useful for debugging the connection cache */
-void Curl_conncache_print(struct conncache *connc)
-{
+#if 0
+/* Useful for debugging the connection cache */
+void Curl_conncache_print(struct conncache *connc)
+{
struct Curl_hash_iterator iter;
struct Curl_llist_element *curr;
struct Curl_hash_element *he;
-
- if(!connc)
- return;
-
- fprintf(stderr, "=Bundle cache=\n");
-
- Curl_hash_start_iterate(connc->hash, &iter);
-
- he = Curl_hash_next_element(&iter);
- while(he) {
- struct connectbundle *bundle;
- struct connectdata *conn;
-
- bundle = he->ptr;
-
- fprintf(stderr, "%s -", he->key);
- curr = bundle->conn_list->head;
- while(curr) {
- conn = curr->ptr;
-
- fprintf(stderr, " [%p %d]", (void *)conn, conn->inuse);
- curr = curr->next;
- }
- fprintf(stderr, "\n");
-
- he = Curl_hash_next_element(&iter);
- }
-}
-#endif
+
+ if(!connc)
+ return;
+
+ fprintf(stderr, "=Bundle cache=\n");
+
+ Curl_hash_start_iterate(connc->hash, &iter);
+
+ he = Curl_hash_next_element(&iter);
+ while(he) {
+ struct connectbundle *bundle;
+ struct connectdata *conn;
+
+ bundle = he->ptr;
+
+ fprintf(stderr, "%s -", he->key);
+ curr = bundle->conn_list->head;
+ while(curr) {
+ conn = curr->ptr;
+
+ fprintf(stderr, " [%p %d]", (void *)conn, conn->inuse);
+ curr = curr->next;
+ }
+ fprintf(stderr, "\n");
+
+ he = Curl_hash_next_element(&iter);
+ }
+}
+#endif
diff --git a/contrib/libs/curl/lib/conncache.h b/contrib/libs/curl/lib/conncache.h
index 2fd3d8f869..ac5460ff4b 100644
--- a/contrib/libs/curl/lib/conncache.h
+++ b/contrib/libs/curl/lib/conncache.h
@@ -1,47 +1,47 @@
-#ifndef HEADER_CURL_CONNCACHE_H
-#define HEADER_CURL_CONNCACHE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONNCACHE_H
+#define HEADER_CURL_CONNCACHE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2015 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) 2012 - 2014, Linus Nielsen Feltzing, <linus@haxx.se>
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
/*
* All accesses to struct fields and changing of data in the connection cache
* and connectbundles must be done with the conncache LOCKED. The cache might
* be shared.
*/
-struct conncache {
+struct conncache {
struct Curl_hash hash;
size_t num_conn;
long next_connection_id;
struct curltime last_cleanup;
/* handle used for closing cached connections */
struct Curl_easy *closure_handle;
-};
-
+};
+
#define BUNDLE_NO_MULTIUSE -1
#define BUNDLE_UNKNOWN 0 /* initial value */
#define BUNDLE_MULTIPLEX 2
-
+
#ifdef CURLDEBUG
/* the debug versions of these macros make extra certain that the lock is
never doubly locked or unlocked */
@@ -71,37 +71,37 @@ struct connectbundle {
/* returns 1 on error, 0 is fine */
int Curl_conncache_init(struct conncache *, int size);
-void Curl_conncache_destroy(struct conncache *connc);
-
+void Curl_conncache_destroy(struct conncache *connc);
+
/* return the correct bundle, to a host or a proxy */
struct connectbundle *Curl_conncache_find_bundle(struct connectdata *conn,
struct conncache *connc,
const char **hostp);
/* returns number of connections currently held in the connection cache */
size_t Curl_conncache_size(struct Curl_easy *data);
-
+
bool Curl_conncache_return_conn(struct Curl_easy *data,
struct connectdata *conn);
-CURLcode Curl_conncache_add_conn(struct conncache *connc,
+CURLcode Curl_conncache_add_conn(struct conncache *connc,
struct connectdata *conn) WARN_UNUSED_RESULT;
void Curl_conncache_remove_conn(struct Curl_easy *data,
struct connectdata *conn,
bool lock);
bool Curl_conncache_foreach(struct Curl_easy *data,
struct conncache *connc,
- void *param,
- int (*func)(struct connectdata *conn,
- void *param));
-
-struct connectdata *
-Curl_conncache_find_first_connection(struct conncache *connc);
-
+ void *param,
+ int (*func)(struct connectdata *conn,
+ void *param));
+
+struct connectdata *
+Curl_conncache_find_first_connection(struct conncache *connc);
+
struct connectdata *
Curl_conncache_extract_bundle(struct Curl_easy *data,
struct connectbundle *bundle);
struct connectdata *
Curl_conncache_extract_oldest(struct Curl_easy *data);
void Curl_conncache_close_all_connections(struct conncache *connc);
-void Curl_conncache_print(struct conncache *connc);
-
-#endif /* HEADER_CURL_CONNCACHE_H */
+void Curl_conncache_print(struct conncache *connc);
+
+#endif /* HEADER_CURL_CONNCACHE_H */
diff --git a/contrib/libs/curl/lib/connect.c b/contrib/libs/curl/lib/connect.c
index 0719928bed..e65d24d9e9 100644
--- a/contrib/libs/curl/lib/connect.c
+++ b/contrib/libs/curl/lib/connect.c
@@ -1,272 +1,272 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h> /* <netinet/tcp.h> may need it */
-#endif
-#ifdef HAVE_SYS_UN_H
-#include <sys/un.h> /* for sockaddr_un */
-#endif
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h> /* <netinet/tcp.h> may need it */
+#endif
+#ifdef HAVE_SYS_UN_H
+#include <sys/un.h> /* for sockaddr_un */
+#endif
#ifdef HAVE_LINUX_TCP_H
#include <linux/tcp.h>
#elif defined(HAVE_NETINET_TCP_H)
#include <netinet/tcp.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
-#include <sys/filio.h>
-#endif
-#ifdef NETWARE
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "if2ip.h"
-#include "strerror.h"
-#include "connect.h"
-#include "select.h"
-#include "url.h" /* for Curl_safefree() */
-#include "multiif.h"
-#include "sockaddr.h" /* required for Curl_sockaddr_storage */
-#include "inet_ntop.h"
-#include "inet_pton.h"
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
+#include <sys/filio.h>
+#endif
+#ifdef NETWARE
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "if2ip.h"
+#include "strerror.h"
+#include "connect.h"
+#include "select.h"
+#include "url.h" /* for Curl_safefree() */
+#include "multiif.h"
+#include "sockaddr.h" /* required for Curl_sockaddr_storage */
+#include "inet_ntop.h"
+#include "inet_pton.h"
#include "vtls/vtls.h" /* for Curl_ssl_check_cxn() */
-#include "progress.h"
-#include "warnless.h"
-#include "conncache.h"
-#include "multihandle.h"
+#include "progress.h"
+#include "warnless.h"
+#include "conncache.h"
+#include "multihandle.h"
#include "version_win32.h"
#include "quic.h"
#include "socks.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-static bool verifyconnect(curl_socket_t sockfd, int *error);
-
-#if defined(__DragonFly__) || defined(HAVE_WINSOCK_H)
-/* DragonFlyBSD and Windows use millisecond units */
-#define KEEPALIVE_FACTOR(x) (x *= 1000)
-#else
-#define KEEPALIVE_FACTOR(x)
-#endif
-
+#include "memdebug.h"
+
+static bool verifyconnect(curl_socket_t sockfd, int *error);
+
+#if defined(__DragonFly__) || defined(HAVE_WINSOCK_H)
+/* DragonFlyBSD and Windows use millisecond units */
+#define KEEPALIVE_FACTOR(x) (x *= 1000)
+#else
+#define KEEPALIVE_FACTOR(x)
+#endif
+
#if defined(HAVE_WINSOCK2_H) && !defined(SIO_KEEPALIVE_VALS)
-#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
-
-struct tcp_keepalive {
- u_long onoff;
- u_long keepalivetime;
- u_long keepaliveinterval;
-};
-#endif
-
-static void
+#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
+
+struct tcp_keepalive {
+ u_long onoff;
+ u_long keepalivetime;
+ u_long keepaliveinterval;
+};
+#endif
+
+static void
tcpkeepalive(struct Curl_easy *data,
- curl_socket_t sockfd)
-{
- int optval = data->set.tcp_keepalive?1:0;
-
- /* only set IDLE and INTVL if setting KEEPALIVE is successful */
- if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
- (void *)&optval, sizeof(optval)) < 0) {
- infof(data, "Failed to set SO_KEEPALIVE on fd %d\n", sockfd);
- }
- else {
-#if defined(SIO_KEEPALIVE_VALS)
- struct tcp_keepalive vals;
- DWORD dummy;
- vals.onoff = 1;
- optval = curlx_sltosi(data->set.tcp_keepidle);
- KEEPALIVE_FACTOR(optval);
- vals.keepalivetime = optval;
- optval = curlx_sltosi(data->set.tcp_keepintvl);
- KEEPALIVE_FACTOR(optval);
- vals.keepaliveinterval = optval;
- if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
- NULL, 0, &dummy, NULL, NULL) != 0) {
- infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd %d: %d\n",
- (int)sockfd, WSAGetLastError());
- }
-#else
-#ifdef TCP_KEEPIDLE
- optval = curlx_sltosi(data->set.tcp_keepidle);
- KEEPALIVE_FACTOR(optval);
- if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
- (void *)&optval, sizeof(optval)) < 0) {
- infof(data, "Failed to set TCP_KEEPIDLE on fd %d\n", sockfd);
- }
-#endif
-#ifdef TCP_KEEPINTVL
- optval = curlx_sltosi(data->set.tcp_keepintvl);
- KEEPALIVE_FACTOR(optval);
- if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
- (void *)&optval, sizeof(optval)) < 0) {
- infof(data, "Failed to set TCP_KEEPINTVL on fd %d\n", sockfd);
- }
-#endif
-#ifdef TCP_KEEPALIVE
- /* Mac OS X style */
- optval = curlx_sltosi(data->set.tcp_keepidle);
- KEEPALIVE_FACTOR(optval);
- if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
- (void *)&optval, sizeof(optval)) < 0) {
- infof(data, "Failed to set TCP_KEEPALIVE on fd %d\n", sockfd);
- }
-#endif
-#endif
- }
-}
-
-static CURLcode
-singleipconnect(struct connectdata *conn,
+ curl_socket_t sockfd)
+{
+ int optval = data->set.tcp_keepalive?1:0;
+
+ /* only set IDLE and INTVL if setting KEEPALIVE is successful */
+ if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
+ (void *)&optval, sizeof(optval)) < 0) {
+ infof(data, "Failed to set SO_KEEPALIVE on fd %d\n", sockfd);
+ }
+ else {
+#if defined(SIO_KEEPALIVE_VALS)
+ struct tcp_keepalive vals;
+ DWORD dummy;
+ vals.onoff = 1;
+ optval = curlx_sltosi(data->set.tcp_keepidle);
+ KEEPALIVE_FACTOR(optval);
+ vals.keepalivetime = optval;
+ optval = curlx_sltosi(data->set.tcp_keepintvl);
+ KEEPALIVE_FACTOR(optval);
+ vals.keepaliveinterval = optval;
+ if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
+ NULL, 0, &dummy, NULL, NULL) != 0) {
+ infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd %d: %d\n",
+ (int)sockfd, WSAGetLastError());
+ }
+#else
+#ifdef TCP_KEEPIDLE
+ optval = curlx_sltosi(data->set.tcp_keepidle);
+ KEEPALIVE_FACTOR(optval);
+ if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
+ (void *)&optval, sizeof(optval)) < 0) {
+ infof(data, "Failed to set TCP_KEEPIDLE on fd %d\n", sockfd);
+ }
+#endif
+#ifdef TCP_KEEPINTVL
+ optval = curlx_sltosi(data->set.tcp_keepintvl);
+ KEEPALIVE_FACTOR(optval);
+ if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
+ (void *)&optval, sizeof(optval)) < 0) {
+ infof(data, "Failed to set TCP_KEEPINTVL on fd %d\n", sockfd);
+ }
+#endif
+#ifdef TCP_KEEPALIVE
+ /* Mac OS X style */
+ optval = curlx_sltosi(data->set.tcp_keepidle);
+ KEEPALIVE_FACTOR(optval);
+ if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
+ (void *)&optval, sizeof(optval)) < 0) {
+ infof(data, "Failed to set TCP_KEEPALIVE on fd %d\n", sockfd);
+ }
+#endif
+#endif
+ }
+}
+
+static CURLcode
+singleipconnect(struct connectdata *conn,
const struct Curl_addrinfo *ai, /* start connecting to this */
int tempindex); /* 0 or 1 among the temp ones */
-
-/*
- * Curl_timeleft() returns the amount of milliseconds left allowed for the
+
+/*
+ * Curl_timeleft() returns the amount of milliseconds left allowed for the
* transfer/connection. If the value is 0, there's no timeout (ie there's
* infinite time left). If the value is negative, the timeout time has already
- * elapsed.
- *
- * The start time is stored in progress.t_startsingle - as set with
- * Curl_pgrsTime(..., TIMER_STARTSINGLE);
- *
- * If 'nowp' is non-NULL, it points to the current time.
- * 'duringconnect' is FALSE if not during a connect, as then of course the
- * connect timeout is not taken into account!
- *
- * @unittest: 1303
- */
+ * elapsed.
+ *
+ * The start time is stored in progress.t_startsingle - as set with
+ * Curl_pgrsTime(..., TIMER_STARTSINGLE);
+ *
+ * If 'nowp' is non-NULL, it points to the current time.
+ * 'duringconnect' is FALSE if not during a connect, as then of course the
+ * connect timeout is not taken into account!
+ *
+ * @unittest: 1303
+ */
timediff_t Curl_timeleft(struct Curl_easy *data,
struct curltime *nowp,
bool duringconnect)
-{
- int timeout_set = 0;
+{
+ int timeout_set = 0;
timediff_t timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0;
struct curltime now;
-
- /* if a timeout is set, use the most restrictive one */
-
- if(data->set.timeout > 0)
- timeout_set |= 1;
- if(duringconnect && (data->set.connecttimeout > 0))
- timeout_set |= 2;
-
+
+ /* if a timeout is set, use the most restrictive one */
+
+ if(data->set.timeout > 0)
+ timeout_set |= 1;
+ if(duringconnect && (data->set.connecttimeout > 0))
+ timeout_set |= 2;
+
switch(timeout_set) {
- case 1:
- timeout_ms = data->set.timeout;
- break;
- case 2:
- timeout_ms = data->set.connecttimeout;
- break;
- case 3:
- if(data->set.timeout < data->set.connecttimeout)
- timeout_ms = data->set.timeout;
- else
- timeout_ms = data->set.connecttimeout;
- break;
- default:
- /* use the default */
- if(!duringconnect)
- /* if we're not during connect, there's no default timeout so if we're
- at zero we better just return zero and not make it a negative number
- by the math below */
- return 0;
- break;
- }
-
- if(!nowp) {
+ case 1:
+ timeout_ms = data->set.timeout;
+ break;
+ case 2:
+ timeout_ms = data->set.connecttimeout;
+ break;
+ case 3:
+ if(data->set.timeout < data->set.connecttimeout)
+ timeout_ms = data->set.timeout;
+ else
+ timeout_ms = data->set.connecttimeout;
+ break;
+ default:
+ /* use the default */
+ if(!duringconnect)
+ /* if we're not during connect, there's no default timeout so if we're
+ at zero we better just return zero and not make it a negative number
+ by the math below */
+ return 0;
+ break;
+ }
+
+ if(!nowp) {
now = Curl_now();
- nowp = &now;
- }
-
- /* subtract elapsed time */
+ nowp = &now;
+ }
+
+ /* subtract elapsed time */
if(duringconnect)
/* since this most recent connect started */
timeout_ms -= Curl_timediff(*nowp, data->progress.t_startsingle);
else
/* since the entire operation started */
timeout_ms -= Curl_timediff(*nowp, data->progress.t_startop);
- if(!timeout_ms)
- /* avoid returning 0 as that means no timeout! */
- return -1;
-
- return timeout_ms;
-}
-
-static CURLcode bindlocal(struct connectdata *conn,
+ if(!timeout_ms)
+ /* avoid returning 0 as that means no timeout! */
+ return -1;
+
+ return timeout_ms;
+}
+
+static CURLcode bindlocal(struct connectdata *conn,
curl_socket_t sockfd, int af, unsigned int scope)
-{
+{
struct Curl_easy *data = conn->data;
-
- struct Curl_sockaddr_storage sa;
- struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
- curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
- struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
-#ifdef ENABLE_IPV6
- struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
-#endif
-
+
+ struct Curl_sockaddr_storage sa;
+ struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
+ curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
+ struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
+#ifdef ENABLE_IPV6
+ struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
+#endif
+
struct Curl_dns_entry *h = NULL;
- unsigned short port = data->set.localport; /* use this port number, 0 for
- "random" */
- /* how many port numbers to try to bind to, increasing one at a time */
- int portnum = data->set.localportrange;
- const char *dev = data->set.str[STRING_DEVICE];
- int error;
-
- /*************************************************************
- * Select device to bind socket to
- *************************************************************/
- if(!dev && !port)
- /* no local kind of binding was requested */
- return CURLE_OK;
-
- memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
-
- if(dev && (strlen(dev)<255) ) {
+ unsigned short port = data->set.localport; /* use this port number, 0 for
+ "random" */
+ /* how many port numbers to try to bind to, increasing one at a time */
+ int portnum = data->set.localportrange;
+ const char *dev = data->set.str[STRING_DEVICE];
+ int error;
+
+ /*************************************************************
+ * Select device to bind socket to
+ *************************************************************/
+ if(!dev && !port)
+ /* no local kind of binding was requested */
+ return CURLE_OK;
+
+ memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
+
+ if(dev && (strlen(dev)<255) ) {
char myhost[256] = "";
int done = 0; /* -1 for error, 1 for address found */
bool is_interface = FALSE;
@@ -274,17 +274,17 @@ static CURLcode bindlocal(struct connectdata *conn,
static const char *if_prefix = "if!";
static const char *host_prefix = "host!";
- if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
- dev += strlen(if_prefix);
- is_interface = TRUE;
- }
- else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
- dev += strlen(host_prefix);
- is_host = TRUE;
- }
-
- /* interface */
- if(!is_host) {
+ if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
+ dev += strlen(if_prefix);
+ is_interface = TRUE;
+ }
+ else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
+ dev += strlen(host_prefix);
+ is_host = TRUE;
+ }
+
+ /* interface */
+ if(!is_host) {
#ifdef SO_BINDTODEVICE
/* I am not sure any other OSs than Linux that provide this feature,
* and at the least I cannot test. --Ben
@@ -315,242 +315,242 @@ static CURLcode bindlocal(struct connectdata *conn,
switch(Curl_if2ip(af, scope, conn->scope_id, dev,
myhost, sizeof(myhost))) {
- case IF2IP_NOT_FOUND:
- if(is_interface) {
- /* Do not fall back to treating it as a host name */
- failf(data, "Couldn't bind to interface '%s'", dev);
- return CURLE_INTERFACE_FAILED;
- }
- break;
- case IF2IP_AF_NOT_SUPPORTED:
- /* Signal the caller to try another address family if available */
- return CURLE_UNSUPPORTED_PROTOCOL;
- case IF2IP_FOUND:
- is_interface = TRUE;
- /*
- * We now have the numerical IP address in the 'myhost' buffer
- */
- infof(data, "Local Interface %s is ip %s using address family %i\n",
- dev, myhost, af);
- done = 1;
- break;
- }
- }
- if(!is_interface) {
- /*
- * This was not an interface, resolve the name as a host name
- * or IP number
- *
- * Temporarily force name resolution to use only the address type
- * of the connection. The resolve functions should really be changed
- * to take a type parameter instead.
- */
- long ipver = conn->ip_version;
- int rc;
-
- if(af == AF_INET)
- conn->ip_version = CURL_IPRESOLVE_V4;
-#ifdef ENABLE_IPV6
- else if(af == AF_INET6)
- conn->ip_version = CURL_IPRESOLVE_V6;
-#endif
-
+ case IF2IP_NOT_FOUND:
+ if(is_interface) {
+ /* Do not fall back to treating it as a host name */
+ failf(data, "Couldn't bind to interface '%s'", dev);
+ return CURLE_INTERFACE_FAILED;
+ }
+ break;
+ case IF2IP_AF_NOT_SUPPORTED:
+ /* Signal the caller to try another address family if available */
+ return CURLE_UNSUPPORTED_PROTOCOL;
+ case IF2IP_FOUND:
+ is_interface = TRUE;
+ /*
+ * We now have the numerical IP address in the 'myhost' buffer
+ */
+ infof(data, "Local Interface %s is ip %s using address family %i\n",
+ dev, myhost, af);
+ done = 1;
+ break;
+ }
+ }
+ if(!is_interface) {
+ /*
+ * This was not an interface, resolve the name as a host name
+ * or IP number
+ *
+ * Temporarily force name resolution to use only the address type
+ * of the connection. The resolve functions should really be changed
+ * to take a type parameter instead.
+ */
+ long ipver = conn->ip_version;
+ int rc;
+
+ if(af == AF_INET)
+ conn->ip_version = CURL_IPRESOLVE_V4;
+#ifdef ENABLE_IPV6
+ else if(af == AF_INET6)
+ conn->ip_version = CURL_IPRESOLVE_V6;
+#endif
+
rc = Curl_resolv(conn, dev, 0, FALSE, &h);
- if(rc == CURLRESOLV_PENDING)
- (void)Curl_resolver_wait_resolv(conn, &h);
- conn->ip_version = ipver;
-
- if(h) {
- /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
- Curl_printable_address(h->addr, myhost, sizeof(myhost));
- infof(data, "Name '%s' family %i resolved to '%s' family %i\n",
- dev, af, myhost, h->addr->ai_family);
- Curl_resolv_unlock(data, h);
+ if(rc == CURLRESOLV_PENDING)
+ (void)Curl_resolver_wait_resolv(conn, &h);
+ conn->ip_version = ipver;
+
+ if(h) {
+ /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
+ Curl_printable_address(h->addr, myhost, sizeof(myhost));
+ infof(data, "Name '%s' family %i resolved to '%s' family %i\n",
+ dev, af, myhost, h->addr->ai_family);
+ Curl_resolv_unlock(data, h);
if(af != h->addr->ai_family) {
/* bad IP version combo, signal the caller to try another address
family if available */
return CURLE_UNSUPPORTED_PROTOCOL;
}
- done = 1;
- }
- else {
- /*
- * provided dev was no interface (or interfaces are not supported
- * e.g. solaris) no ip address and no domain we fail here
- */
- done = -1;
- }
- }
-
- if(done > 0) {
-#ifdef ENABLE_IPV6
+ done = 1;
+ }
+ else {
+ /*
+ * provided dev was no interface (or interfaces are not supported
+ * e.g. solaris) no ip address and no domain we fail here
+ */
+ done = -1;
+ }
+ }
+
+ if(done > 0) {
+#ifdef ENABLE_IPV6
/* IPv6 address */
- if(af == AF_INET6) {
-#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
- char *scope_ptr = strchr(myhost, '%');
- if(scope_ptr)
- *(scope_ptr++) = 0;
-#endif
- if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
- si6->sin6_family = AF_INET6;
- si6->sin6_port = htons(port);
-#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
- if(scope_ptr)
- /* The "myhost" string either comes from Curl_if2ip or from
- Curl_printable_address. The latter returns only numeric scope
- IDs and the former returns none at all. So the scope ID, if
- present, is known to be numeric */
- si6->sin6_scope_id = atoi(scope_ptr);
-#endif
- }
- sizeof_sa = sizeof(struct sockaddr_in6);
- }
- else
-#endif
+ if(af == AF_INET6) {
+#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
+ char *scope_ptr = strchr(myhost, '%');
+ if(scope_ptr)
+ *(scope_ptr++) = 0;
+#endif
+ if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
+ si6->sin6_family = AF_INET6;
+ si6->sin6_port = htons(port);
+#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
+ if(scope_ptr)
+ /* The "myhost" string either comes from Curl_if2ip or from
+ Curl_printable_address. The latter returns only numeric scope
+ IDs and the former returns none at all. So the scope ID, if
+ present, is known to be numeric */
+ si6->sin6_scope_id = atoi(scope_ptr);
+#endif
+ }
+ sizeof_sa = sizeof(struct sockaddr_in6);
+ }
+ else
+#endif
/* IPv4 address */
- if((af == AF_INET) &&
- (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
- si4->sin_family = AF_INET;
- si4->sin_port = htons(port);
- sizeof_sa = sizeof(struct sockaddr_in);
- }
- }
-
- if(done < 1) {
+ if((af == AF_INET) &&
+ (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
+ si4->sin_family = AF_INET;
+ si4->sin_port = htons(port);
+ sizeof_sa = sizeof(struct sockaddr_in);
+ }
+ }
+
+ if(done < 1) {
/* errorbuf is set false so failf will overwrite any message already in
the error buffer, so the user receives this error message instead of a
generic resolve error. */
data->state.errorbuf = FALSE;
- failf(data, "Couldn't bind to '%s'", dev);
- return CURLE_INTERFACE_FAILED;
- }
- }
- else {
- /* no device was given, prepare sa to match af's needs */
-#ifdef ENABLE_IPV6
- if(af == AF_INET6) {
- si6->sin6_family = AF_INET6;
- si6->sin6_port = htons(port);
- sizeof_sa = sizeof(struct sockaddr_in6);
- }
- else
-#endif
- if(af == AF_INET) {
- si4->sin_family = AF_INET;
- si4->sin_port = htons(port);
- sizeof_sa = sizeof(struct sockaddr_in);
- }
- }
-
- for(;;) {
- if(bind(sockfd, sock, sizeof_sa) >= 0) {
- /* we succeeded to bind */
- struct Curl_sockaddr_storage add;
- curl_socklen_t size = sizeof(add);
- memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
- if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
+ failf(data, "Couldn't bind to '%s'", dev);
+ return CURLE_INTERFACE_FAILED;
+ }
+ }
+ else {
+ /* no device was given, prepare sa to match af's needs */
+#ifdef ENABLE_IPV6
+ if(af == AF_INET6) {
+ si6->sin6_family = AF_INET6;
+ si6->sin6_port = htons(port);
+ sizeof_sa = sizeof(struct sockaddr_in6);
+ }
+ else
+#endif
+ if(af == AF_INET) {
+ si4->sin_family = AF_INET;
+ si4->sin_port = htons(port);
+ sizeof_sa = sizeof(struct sockaddr_in);
+ }
+ }
+
+ for(;;) {
+ if(bind(sockfd, sock, sizeof_sa) >= 0) {
+ /* we succeeded to bind */
+ struct Curl_sockaddr_storage add;
+ curl_socklen_t size = sizeof(add);
+ memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
+ if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
char buffer[STRERROR_LEN];
- data->state.os_errno = error = SOCKERRNO;
- failf(data, "getsockname() failed with errno %d: %s",
+ data->state.os_errno = error = SOCKERRNO;
+ failf(data, "getsockname() failed with errno %d: %s",
error, Curl_strerror(error, buffer, sizeof(buffer)));
- return CURLE_INTERFACE_FAILED;
- }
- infof(data, "Local port: %hu\n", port);
- conn->bits.bound = TRUE;
- return CURLE_OK;
- }
-
- if(--portnum > 0) {
- infof(data, "Bind to local port %hu failed, trying next\n", port);
- port++; /* try next port */
- /* We re-use/clobber the port variable here below */
- if(sock->sa_family == AF_INET)
- si4->sin_port = ntohs(port);
-#ifdef ENABLE_IPV6
- else
- si6->sin6_port = ntohs(port);
-#endif
- }
- else
- break;
- }
+ return CURLE_INTERFACE_FAILED;
+ }
+ infof(data, "Local port: %hu\n", port);
+ conn->bits.bound = TRUE;
+ return CURLE_OK;
+ }
+
+ if(--portnum > 0) {
+ infof(data, "Bind to local port %hu failed, trying next\n", port);
+ port++; /* try next port */
+ /* We re-use/clobber the port variable here below */
+ if(sock->sa_family == AF_INET)
+ si4->sin_port = ntohs(port);
+#ifdef ENABLE_IPV6
+ else
+ si6->sin6_port = ntohs(port);
+#endif
+ }
+ else
+ break;
+ }
{
char buffer[STRERROR_LEN];
data->state.os_errno = error = SOCKERRNO;
failf(data, "bind failed with errno %d: %s",
error, Curl_strerror(error, buffer, sizeof(buffer)));
}
-
- return CURLE_INTERFACE_FAILED;
-}
-
-/*
- * verifyconnect() returns TRUE if the connect really has happened.
- */
-static bool verifyconnect(curl_socket_t sockfd, int *error)
-{
- bool rc = TRUE;
-#ifdef SO_ERROR
- int err = 0;
- curl_socklen_t errSize = sizeof(err);
-
-#ifdef WIN32
- /*
- * In October 2003 we effectively nullified this function on Windows due to
- * problems with it using all CPU in multi-threaded cases.
- *
- * In May 2004, we bring it back to offer more info back on connect failures.
- * Gisle Vanem could reproduce the former problems with this function, but
- * could avoid them by adding this SleepEx() call below:
- *
- * "I don't have Rational Quantify, but the hint from his post was
- * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
- * just Sleep(0) would be enough?) would release whatever
- * mutex/critical-section the ntdll call is waiting on.
- *
- * Someone got to verify this on Win-NT 4.0, 2000."
- */
-
-#ifdef _WIN32_WCE
- Sleep(0);
-#else
- SleepEx(0, FALSE);
-#endif
-
-#endif
-
- if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
- err = SOCKERRNO;
-#ifdef _WIN32_WCE
- /* Old WinCE versions don't support SO_ERROR */
- if(WSAENOPROTOOPT == err) {
- SET_SOCKERRNO(0);
- err = 0;
- }
-#endif
+
+ return CURLE_INTERFACE_FAILED;
+}
+
+/*
+ * verifyconnect() returns TRUE if the connect really has happened.
+ */
+static bool verifyconnect(curl_socket_t sockfd, int *error)
+{
+ bool rc = TRUE;
+#ifdef SO_ERROR
+ int err = 0;
+ curl_socklen_t errSize = sizeof(err);
+
+#ifdef WIN32
+ /*
+ * In October 2003 we effectively nullified this function on Windows due to
+ * problems with it using all CPU in multi-threaded cases.
+ *
+ * In May 2004, we bring it back to offer more info back on connect failures.
+ * Gisle Vanem could reproduce the former problems with this function, but
+ * could avoid them by adding this SleepEx() call below:
+ *
+ * "I don't have Rational Quantify, but the hint from his post was
+ * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
+ * just Sleep(0) would be enough?) would release whatever
+ * mutex/critical-section the ntdll call is waiting on.
+ *
+ * Someone got to verify this on Win-NT 4.0, 2000."
+ */
+
+#ifdef _WIN32_WCE
+ Sleep(0);
+#else
+ SleepEx(0, FALSE);
+#endif
+
+#endif
+
+ if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
+ err = SOCKERRNO;
+#ifdef _WIN32_WCE
+ /* Old WinCE versions don't support SO_ERROR */
+ if(WSAENOPROTOOPT == err) {
+ SET_SOCKERRNO(0);
+ err = 0;
+ }
+#endif
#if defined(EBADIOCTL) && defined(__minix)
- /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
- if(EBADIOCTL == err) {
- SET_SOCKERRNO(0);
- err = 0;
- }
-#endif
- if((0 == err) || (EISCONN == err))
- /* we are connected, awesome! */
- rc = TRUE;
- else
- /* This wasn't a successful connect */
- rc = FALSE;
- if(error)
- *error = err;
-#else
- (void)sockfd;
- if(error)
- *error = SOCKERRNO;
-#endif
- return rc;
-}
-
+ /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
+ if(EBADIOCTL == err) {
+ SET_SOCKERRNO(0);
+ err = 0;
+ }
+#endif
+ if((0 == err) || (EISCONN == err))
+ /* we are connected, awesome! */
+ rc = TRUE;
+ else
+ /* This wasn't a successful connect */
+ rc = FALSE;
+ if(error)
+ *error = err;
+#else
+ (void)sockfd;
+ if(error)
+ *error = SOCKERRNO;
+#endif
+ return rc;
+}
+
/* update tempaddr[tempindex] (to the next entry), makes sure to stick
to the correct family */
static struct Curl_addrinfo *ainext(struct connectdata *conn,
@@ -567,23 +567,23 @@ static struct Curl_addrinfo *ainext(struct connectdata *conn,
}
/* Used within the multi interface. Try next IP address, returns error if no
- more address exists or error */
-static CURLcode trynextip(struct connectdata *conn,
- int sockindex,
+ more address exists or error */
+static CURLcode trynextip(struct connectdata *conn,
+ int sockindex,
int tempindex)
-{
+{
CURLcode result = CURLE_COULDNT_CONNECT;
-
- /* First clean up after the failed socket.
- Don't close it yet to ensure that the next IP's socket gets a different
- file descriptor, which can prevent bugs when the curl_multi_socket_action
- interface is used with certain select() replacements such as kqueue. */
+
+ /* First clean up after the failed socket.
+ Don't close it yet to ensure that the next IP's socket gets a different
+ file descriptor, which can prevent bugs when the curl_multi_socket_action
+ interface is used with certain select() replacements such as kqueue. */
curl_socket_t fd_to_close = conn->tempsock[tempindex];
conn->tempsock[tempindex] = CURL_SOCKET_BAD;
-
+
if(sockindex == FIRSTSOCKET) {
struct Curl_addrinfo *ai = conn->tempaddr[tempindex];
-
+
while(ai) {
if(ai) {
result = singleipconnect(conn, ai, tempindex);
@@ -593,88 +593,88 @@ static CURLcode trynextip(struct connectdata *conn,
}
}
break;
- }
- }
+ }
+ }
if(fd_to_close != CURL_SOCKET_BAD)
Curl_closesocket(conn, fd_to_close);
return result;
-}
-
-/* Copies connection info into the session handle to make it available
- when the session handle is no longer associated with a connection. */
-void Curl_persistconninfo(struct connectdata *conn)
-{
- memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
- memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
+}
+
+/* Copies connection info into the session handle to make it available
+ when the session handle is no longer associated with a connection. */
+void Curl_persistconninfo(struct connectdata *conn)
+{
+ memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
+ memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
conn->data->info.conn_scheme = conn->handler->scheme;
conn->data->info.conn_protocol = conn->handler->protocol;
- conn->data->info.conn_primary_port = conn->primary_port;
- conn->data->info.conn_local_port = conn->local_port;
-}
-
+ conn->data->info.conn_primary_port = conn->primary_port;
+ conn->data->info.conn_local_port = conn->local_port;
+}
+
/* retrieves ip address and port from a sockaddr structure.
note it calls Curl_inet_ntop which sets errno on fail, not SOCKERRNO. */
bool Curl_addr2string(struct sockaddr *sa, curl_socklen_t salen,
char *addr, long *port)
-{
+{
struct sockaddr_in *si = NULL;
-#ifdef ENABLE_IPV6
+#ifdef ENABLE_IPV6
struct sockaddr_in6 *si6 = NULL;
-#endif
-#if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
+#endif
+#if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
struct sockaddr_un *su = NULL;
#else
(void)salen;
-#endif
-
+#endif
+
switch(sa->sa_family) {
- case AF_INET:
+ case AF_INET:
si = (struct sockaddr_in *)(void *) sa;
- if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
- addr, MAX_IPADR_LEN)) {
+ if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
+ addr, MAX_IPADR_LEN)) {
unsigned short us_port = ntohs(si->sin_port);
- *port = us_port;
- return TRUE;
- }
- break;
-#ifdef ENABLE_IPV6
- case AF_INET6:
+ *port = us_port;
+ return TRUE;
+ }
+ break;
+#ifdef ENABLE_IPV6
+ case AF_INET6:
si6 = (struct sockaddr_in6 *)(void *) sa;
- if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
- addr, MAX_IPADR_LEN)) {
+ if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
+ addr, MAX_IPADR_LEN)) {
unsigned short us_port = ntohs(si6->sin6_port);
- *port = us_port;
- return TRUE;
- }
- break;
-#endif
-#if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
- case AF_UNIX:
+ *port = us_port;
+ return TRUE;
+ }
+ break;
+#endif
+#if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
+ case AF_UNIX:
if(salen > (curl_socklen_t)sizeof(sa_family_t)) {
su = (struct sockaddr_un*)sa;
msnprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
}
else
addr[0] = 0; /* socket with no name */
- *port = 0;
- return TRUE;
-#endif
- default:
- break;
- }
-
- addr[0] = '\0';
- *port = 0;
+ *port = 0;
+ return TRUE;
+#endif
+ default:
+ break;
+ }
+
+ addr[0] = '\0';
+ *port = 0;
errno = EAFNOSUPPORT;
- return FALSE;
-}
-
-/* retrieves the start/end point information of a socket of an established
- connection */
+ return FALSE;
+}
+
+/* retrieves the start/end point information of a socket of an established
+ connection */
void Curl_conninfo_remote(struct connectdata *conn, curl_socket_t sockfd)
-{
+{
#ifdef HAVE_GETPEERNAME
char buffer[STRERROR_LEN];
struct Curl_sockaddr_storage ssrem;
@@ -698,7 +698,7 @@ void Curl_conninfo_remote(struct connectdata *conn, curl_socket_t sockfd)
(void)sockfd;
#endif
}
-
+
/* retrieves the start/end point information of a socket of an established
connection */
void Curl_conninfo_local(struct connectdata *conn, curl_socket_t sockfd)
@@ -714,7 +714,7 @@ void Curl_conninfo_local(struct connectdata *conn, curl_socket_t sockfd)
failf(conn->data, "getsockname() failed with errno %d: %s",
error, Curl_strerror(error, buffer, sizeof(buffer)));
return;
- }
+ }
if(!Curl_addr2string((struct sockaddr*)&ssloc, slen,
conn->local_ip, &conn->local_port)) {
failf(conn->data, "ssloc inet_ntop() failed with errno %d: %s",
@@ -726,7 +726,7 @@ void Curl_conninfo_local(struct connectdata *conn, curl_socket_t sockfd)
(void)sockfd;
#endif
}
-
+
/* retrieves the start/end point information of a socket of an established
connection */
void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
@@ -738,10 +738,10 @@ void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
}
} /* end of TCP-only section */
- /* persist connection info in session handle */
- Curl_persistconninfo(conn);
-}
-
+ /* persist connection info in session handle */
+ Curl_persistconninfo(conn);
+}
+
/* After a TCP connection to the proxy has been verified, this function does
the next magic steps. If 'done' isn't set TRUE, it is not done yet and
must be called again.
@@ -803,7 +803,7 @@ static CURLcode connect_SOCKS(struct connectdata *conn, int sockindex,
return result;
}
-/*
+/*
* post_SOCKS() is called after a successful connect to the peer, which
* *could* be a SOCKS proxy
*/
@@ -822,42 +822,42 @@ static void post_SOCKS(struct connectdata *conn,
}
/*
- * Curl_is_connected() checks if the socket has connected.
- */
-
-CURLcode Curl_is_connected(struct connectdata *conn,
- int sockindex,
- bool *connected)
-{
+ * Curl_is_connected() checks if the socket has connected.
+ */
+
+CURLcode Curl_is_connected(struct connectdata *conn,
+ int sockindex,
+ bool *connected)
+{
struct Curl_easy *data = conn->data;
CURLcode result = CURLE_OK;
timediff_t allow;
- int error = 0;
+ int error = 0;
struct curltime now;
int rc = 0;
unsigned int i;
-
- DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
-
- *connected = FALSE; /* a very negative world view is best */
-
- if(conn->bits.tcpconnect[sockindex]) {
- /* we are connected already! */
- *connected = TRUE;
- return CURLE_OK;
- }
-
+
+ DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
+
+ *connected = FALSE; /* a very negative world view is best */
+
+ if(conn->bits.tcpconnect[sockindex]) {
+ /* we are connected already! */
+ *connected = TRUE;
+ return CURLE_OK;
+ }
+
now = Curl_now();
-
- /* figure out how long time we have left to connect */
- allow = Curl_timeleft(data, &now, TRUE);
-
- if(allow < 0) {
- /* time-out, bail out, go home */
- failf(data, "Connection time-out");
- return CURLE_OPERATION_TIMEDOUT;
- }
-
+
+ /* figure out how long time we have left to connect */
+ allow = Curl_timeleft(data, &now, TRUE);
+
+ if(allow < 0) {
+ /* time-out, bail out, go home */
+ failf(data, "Connection time-out");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
if(SOCKS_STATE(conn->cnnct.state)) {
/* still doing SOCKS */
result = connect_SOCKS(conn, sockindex, connected);
@@ -916,11 +916,11 @@ CURLcode Curl_is_connected(struct connectdata *conn,
conn->bits.parallel_connect = TRUE; /* starting now */
trynextip(conn, sockindex, 1);
}
- }
+ }
else if(rc == CURL_CSELECT_OUT || conn->bits.tcp_fastopen) {
if(verifyconnect(conn->tempsock[i], &error)) {
/* we are connected with TCP, awesome! */
-
+
/* use this socket from now on */
conn->sock[sockindex] = conn->tempsock[i];
conn->ip_addr = conn->tempaddr[i];
@@ -928,24 +928,24 @@ CURLcode Curl_is_connected(struct connectdata *conn,
#ifdef ENABLE_IPV6
conn->bits.ipv6 = (conn->ip_addr->ai_family == AF_INET6)?TRUE:FALSE;
#endif
-
+
/* close the other socket, if open */
if(conn->tempsock[other] != CURL_SOCKET_BAD) {
Curl_closesocket(conn, conn->tempsock[other]);
conn->tempsock[other] = CURL_SOCKET_BAD;
}
-
+
/* see if we need to kick off any SOCKS proxy magic once we
connected */
result = connect_SOCKS(conn, sockindex, connected);
if(result || !*connected)
return result;
-
+
post_SOCKS(conn, sockindex, connected);
-
+
return CURLE_OK;
}
- }
+ }
else if(rc & CURL_CSELECT_ERR) {
(void)verifyconnect(conn->tempsock[i], &error);
}
@@ -978,16 +978,16 @@ CURLcode Curl_is_connected(struct connectdata *conn,
/* the last attempt failed and no other sockets remain open */
result = status;
}
- }
- }
-
+ }
+ }
+
if(result &&
(conn->tempsock[0] == CURL_SOCKET_BAD) &&
(conn->tempsock[1] == CURL_SOCKET_BAD)) {
/* no more addresses to try */
const char *hostname;
char buffer[STRERROR_LEN];
-
+
/* if the first address family runs out of addresses to try before the
happy eyeball timeout, go ahead and try the next family now */
result = trynextip(conn, sockindex, 1);
@@ -1020,15 +1020,15 @@ CURLcode Curl_is_connected(struct connectdata *conn,
if(ETIMEDOUT == data->state.os_errno)
result = CURLE_OPERATION_TIMEDOUT;
#endif
- }
+ }
else
result = CURLE_OK; /* still trying */
-
+
return result;
-}
-
+}
+
static void tcpnodelay(struct connectdata *conn, curl_socket_t sockfd)
-{
+{
#if defined(TCP_NODELAY)
curl_socklen_t onoff = (curl_socklen_t) 1;
int level = IPPROTO_TCP;
@@ -1037,102 +1037,102 @@ static void tcpnodelay(struct connectdata *conn, curl_socket_t sockfd)
char buffer[STRERROR_LEN];
#else
(void) conn;
-#endif
-
- if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
- sizeof(onoff)) < 0)
- infof(data, "Could not set TCP_NODELAY: %s\n",
+#endif
+
+ if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
+ sizeof(onoff)) < 0)
+ infof(data, "Could not set TCP_NODELAY: %s\n",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
-#else
- (void)conn;
- (void)sockfd;
-#endif
-}
-
-#ifdef SO_NOSIGPIPE
-/* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
- sending data to a dead peer (instead of relying on the 4th argument to send
- being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
- systems? */
-static void nosigpipe(struct connectdata *conn,
- curl_socket_t sockfd)
-{
+#else
+ (void)conn;
+ (void)sockfd;
+#endif
+}
+
+#ifdef SO_NOSIGPIPE
+/* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
+ sending data to a dead peer (instead of relying on the 4th argument to send
+ being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
+ systems? */
+static void nosigpipe(struct connectdata *conn,
+ curl_socket_t sockfd)
+{
struct Curl_easy *data = conn->data;
- int onoff = 1;
- if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
+ int onoff = 1;
+ if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
sizeof(onoff)) < 0) {
char buffer[STRERROR_LEN];
- infof(data, "Could not set SO_NOSIGPIPE: %s\n",
+ infof(data, "Could not set SO_NOSIGPIPE: %s\n",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
}
-}
-#else
-#define nosigpipe(x,y) Curl_nop_stmt
-#endif
-
-#ifdef USE_WINSOCK
-/* When you run a program that uses the Windows Sockets API, you may
- experience slow performance when you copy data to a TCP server.
-
+}
+#else
+#define nosigpipe(x,y) Curl_nop_stmt
+#endif
+
+#ifdef USE_WINSOCK
+/* When you run a program that uses the Windows Sockets API, you may
+ experience slow performance when you copy data to a TCP server.
+
https://support.microsoft.com/kb/823764
-
- Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
- Buffer Size
-
- The problem described in this knowledge-base is applied only to pre-Vista
- Windows. Following function trying to detect OS version and skips
- SO_SNDBUF adjustment for Windows Vista and above.
-*/
-#define DETECT_OS_NONE 0
-#define DETECT_OS_PREVISTA 1
-#define DETECT_OS_VISTA_OR_LATER 2
-
-void Curl_sndbufset(curl_socket_t sockfd)
-{
- int val = CURL_MAX_WRITE_SIZE + 32;
- int curval = 0;
- int curlen = sizeof(curval);
-
- static int detectOsState = DETECT_OS_NONE;
-
- if(detectOsState == DETECT_OS_NONE) {
+
+ Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
+ Buffer Size
+
+ The problem described in this knowledge-base is applied only to pre-Vista
+ Windows. Following function trying to detect OS version and skips
+ SO_SNDBUF adjustment for Windows Vista and above.
+*/
+#define DETECT_OS_NONE 0
+#define DETECT_OS_PREVISTA 1
+#define DETECT_OS_VISTA_OR_LATER 2
+
+void Curl_sndbufset(curl_socket_t sockfd)
+{
+ int val = CURL_MAX_WRITE_SIZE + 32;
+ int curval = 0;
+ int curlen = sizeof(curval);
+
+ static int detectOsState = DETECT_OS_NONE;
+
+ if(detectOsState == DETECT_OS_NONE) {
if(curlx_verify_windows_version(6, 0, PLATFORM_WINNT,
VERSION_GREATER_THAN_EQUAL))
detectOsState = DETECT_OS_VISTA_OR_LATER;
else
detectOsState = DETECT_OS_PREVISTA;
- }
-
- if(detectOsState == DETECT_OS_VISTA_OR_LATER)
- return;
-
- if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
- if(curval > val)
- return;
-
- setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
-}
-#endif
-
-/*
- * singleipconnect()
- *
- * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
- * CURL_SOCKET_BAD. Other errors will however return proper errors.
- *
- * singleipconnect() connects to the given IP only, and it may return without
- * having connected.
- */
+ }
+
+ if(detectOsState == DETECT_OS_VISTA_OR_LATER)
+ return;
+
+ if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
+ if(curval > val)
+ return;
+
+ setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
+}
+#endif
+
+/*
+ * singleipconnect()
+ *
+ * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
+ * CURL_SOCKET_BAD. Other errors will however return proper errors.
+ *
+ * singleipconnect() connects to the given IP only, and it may return without
+ * having connected.
+ */
static CURLcode singleipconnect(struct connectdata *conn,
const struct Curl_addrinfo *ai,
int tempindex)
-{
- struct Curl_sockaddr_ex addr;
+{
+ struct Curl_sockaddr_ex addr;
int rc = -1;
- int error = 0;
- bool isconnected = FALSE;
+ int error = 0;
+ bool isconnected = FALSE;
struct Curl_easy *data = conn->data;
- curl_socket_t sockfd;
+ curl_socket_t sockfd;
CURLcode result;
char ipaddress[MAX_IPADR_LEN];
long port;
@@ -1142,23 +1142,23 @@ static CURLcode singleipconnect(struct connectdata *conn,
#endif
char buffer[STRERROR_LEN];
curl_socket_t *sockp = &conn->tempsock[tempindex];
- *sockp = CURL_SOCKET_BAD;
-
+ *sockp = CURL_SOCKET_BAD;
+
result = Curl_socket(conn, ai, &addr, &sockfd);
if(result)
return result;
-
- /* store remote address and port used in this connection attempt */
+
+ /* store remote address and port used in this connection attempt */
if(!Curl_addr2string((struct sockaddr*)&addr.sa_addr, addr.addrlen,
ipaddress, &port)) {
- /* malformed address or bug in inet_ntop, try next address */
- failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
+ /* malformed address or bug in inet_ntop, try next address */
+ failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- Curl_closesocket(conn, sockfd);
- return CURLE_OK;
- }
+ Curl_closesocket(conn, sockfd);
+ return CURLE_OK;
+ }
infof(data, " Trying %s:%ld...\n", ipaddress, port);
-
+
#ifdef ENABLE_IPV6
is_tcp = (addr.family == AF_INET || addr.family == AF_INET6) &&
addr.socktype == SOCK_STREAM;
@@ -1167,31 +1167,31 @@ static CURLcode singleipconnect(struct connectdata *conn,
#endif
if(is_tcp && data->set.tcp_nodelay)
tcpnodelay(conn, sockfd);
-
- nosigpipe(conn, sockfd);
-
- Curl_sndbufset(sockfd);
-
+
+ nosigpipe(conn, sockfd);
+
+ Curl_sndbufset(sockfd);
+
if(is_tcp && data->set.tcp_keepalive)
- tcpkeepalive(data, sockfd);
-
- if(data->set.fsockopt) {
- /* activate callback for setting socket options */
+ tcpkeepalive(data, sockfd);
+
+ if(data->set.fsockopt) {
+ /* activate callback for setting socket options */
Curl_set_in_callback(data, true);
- error = data->set.fsockopt(data->set.sockopt_client,
- sockfd,
- CURLSOCKTYPE_IPCXN);
+ error = data->set.fsockopt(data->set.sockopt_client,
+ sockfd,
+ CURLSOCKTYPE_IPCXN);
Curl_set_in_callback(data, false);
-
- if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
- isconnected = TRUE;
- else if(error) {
- Curl_closesocket(conn, sockfd); /* close the socket and bail out */
- return CURLE_ABORTED_BY_CALLBACK;
- }
- }
-
- /* possibly bind the local end to an IP, interface or port */
+
+ if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
+ isconnected = TRUE;
+ else if(error) {
+ Curl_closesocket(conn, sockfd); /* close the socket and bail out */
+ return CURLE_ABORTED_BY_CALLBACK;
+ }
+ }
+
+ /* possibly bind the local end to an IP, interface or port */
if(addr.family == AF_INET
#ifdef ENABLE_IPV6
|| addr.family == AF_INET6
@@ -1207,18 +1207,18 @@ static CURLcode singleipconnect(struct connectdata *conn,
return CURLE_COULDNT_CONNECT;
}
return result;
- }
- }
-
- /* set socket non-blocking */
+ }
+ }
+
+ /* set socket non-blocking */
(void)curlx_nonblock(sockfd, TRUE);
-
+
conn->connecttime = Curl_now();
if(conn->num_addr > 1) {
Curl_expire(data, conn->timeoutms_per_addr[0], EXPIRE_DNS_PER_NAME);
Curl_expire(data, conn->timeoutms_per_addr[1], EXPIRE_DNS_PER_NAME2);
}
-
+
/* Connect TCP and QUIC sockets */
if(!isconnected && (conn->transport != TRNSPRT_UDP)) {
if(conn->bits.tcp_fastopen) {
@@ -1262,8 +1262,8 @@ static CURLcode singleipconnect(struct connectdata *conn,
rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
}
- if(-1 == rc)
- error = SOCKERRNO;
+ if(-1 == rc)
+ error = SOCKERRNO;
#ifdef ENABLE_QUIC
else if(conn->transport == TRNSPRT_QUIC) {
/* pass in 'sockfd' separately since it hasn't been put into the
@@ -1274,76 +1274,76 @@ static CURLcode singleipconnect(struct connectdata *conn,
error = SOCKERRNO;
}
#endif
- }
- else {
- *sockp = sockfd;
- return CURLE_OK;
- }
-
- if(-1 == rc) {
+ }
+ else {
+ *sockp = sockfd;
+ return CURLE_OK;
+ }
+
+ if(-1 == rc) {
switch(error) {
- case EINPROGRESS:
- case EWOULDBLOCK:
-#if defined(EAGAIN)
-#if (EAGAIN) != (EWOULDBLOCK)
- /* On some platforms EAGAIN and EWOULDBLOCK are the
- * same value, and on others they are different, hence
- * the odd #if
- */
- case EAGAIN:
-#endif
-#endif
+ case EINPROGRESS:
+ case EWOULDBLOCK:
+#if defined(EAGAIN)
+#if (EAGAIN) != (EWOULDBLOCK)
+ /* On some platforms EAGAIN and EWOULDBLOCK are the
+ * same value, and on others they are different, hence
+ * the odd #if
+ */
+ case EAGAIN:
+#endif
+#endif
result = CURLE_OK;
break;
-
- default:
- /* unknown error, fallthrough and try another address! */
+
+ default:
+ /* unknown error, fallthrough and try another address! */
infof(data, "Immediate connect fail for %s: %s\n",
ipaddress, Curl_strerror(error, buffer, sizeof(buffer)));
- data->state.os_errno = error;
-
- /* connect failed */
- Curl_closesocket(conn, sockfd);
+ data->state.os_errno = error;
+
+ /* connect failed */
+ Curl_closesocket(conn, sockfd);
result = CURLE_COULDNT_CONNECT;
- }
- }
+ }
+ }
if(!result)
- *sockp = sockfd;
-
+ *sockp = sockfd;
+
return result;
-}
-
-/*
- * TCP connect to the given host with timeout, proxy or remote doesn't matter.
- * There might be more than one IP address to try out. Fill in the passed
- * pointer with the connected socket.
- */
-
-CURLcode Curl_connecthost(struct connectdata *conn, /* context */
+}
+
+/*
+ * TCP connect to the given host with timeout, proxy or remote doesn't matter.
+ * There might be more than one IP address to try out. Fill in the passed
+ * pointer with the connected socket.
+ */
+
+CURLcode Curl_connecthost(struct connectdata *conn, /* context */
const struct Curl_dns_entry *remotehost)
-{
+{
struct Curl_easy *data = conn->data;
CURLcode result = CURLE_COULDNT_CONNECT;
int i;
timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
-
- if(timeout_ms < 0) {
- /* a precaution, no need to continue if time already is up */
- failf(data, "Connection time-out");
- return CURLE_OPERATION_TIMEDOUT;
- }
-
- conn->num_addr = Curl_num_addresses(remotehost->addr);
+
+ if(timeout_ms < 0) {
+ /* a precaution, no need to continue if time already is up */
+ failf(data, "Connection time-out");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ conn->num_addr = Curl_num_addresses(remotehost->addr);
conn->tempaddr[0] = conn->tempaddr[1] = remotehost->addr;
conn->tempsock[0] = conn->tempsock[1] = CURL_SOCKET_BAD;
-
+
/* Max time for the next connection attempt */
conn->timeoutms_per_addr[0] =
conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
conn->timeoutms_per_addr[1] =
conn->tempaddr[1]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
-
+
conn->tempfamily[0] = conn->tempaddr[0]?
conn->tempaddr[0]->ai_family:0;
#ifdef ENABLE_IPV6
@@ -1369,39 +1369,39 @@ CURLcode Curl_connecthost(struct connectdata *conn, /* context */
}
if(result)
return result;
-
+
Curl_expire(conn->data, data->set.happy_eyeballs_timeout,
EXPIRE_HAPPY_EYEBALLS);
-
- return CURLE_OK;
-}
-
-struct connfind {
+
+ return CURLE_OK;
+}
+
+struct connfind {
long id_tofind;
struct connectdata *found;
-};
-
-static int conn_is_conn(struct connectdata *conn, void *param)
-{
- struct connfind *f = (struct connfind *)param;
+};
+
+static int conn_is_conn(struct connectdata *conn, void *param)
+{
+ struct connfind *f = (struct connfind *)param;
if(conn->connection_id == f->id_tofind) {
f->found = conn;
- return 1;
- }
- return 0;
-}
-
-/*
- * Used to extract socket and connectdata struct for the most recent
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * Used to extract socket and connectdata struct for the most recent
* transfer on the given Curl_easy.
- *
- * The returned socket will be CURL_SOCKET_BAD in case of failure!
- */
+ *
+ * The returned socket will be CURL_SOCKET_BAD in case of failure!
+ */
curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
- struct connectdata **connp)
-{
- DEBUGASSERT(data);
-
+ struct connectdata **connp)
+{
+ DEBUGASSERT(data);
+
/* this works for an easy handle:
* - that has been used for curl_easy_perform()
* - that is associated with a multi handle, and whose connection
@@ -1409,25 +1409,25 @@ curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
*/
if((data->state.lastconnect_id != -1) && (data->multi_easy || data->multi)) {
struct connectdata *c;
- struct connfind find;
+ struct connfind find;
find.id_tofind = data->state.lastconnect_id;
find.found = NULL;
-
+
Curl_conncache_foreach(data, data->multi_easy?
&data->multi_easy->conn_cache:
&data->multi->conn_cache, &find, conn_is_conn);
-
- if(!find.found) {
+
+ if(!find.found) {
data->state.lastconnect_id = -1;
- return CURL_SOCKET_BAD;
- }
-
+ return CURL_SOCKET_BAD;
+ }
+
c = find.found;
if(connp) {
- /* only store this if the caller cares for it */
- *connp = c;
+ /* only store this if the caller cares for it */
+ *connp = c;
c->data = data;
- }
+ }
return c->sock[FIRSTSOCKET];
}
return CURL_SOCKET_BAD;
@@ -1444,8 +1444,8 @@ bool Curl_connalive(struct connectdata *conn)
if(!Curl_ssl_check_cxn(conn))
return false; /* FIN received */
}
-/* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
-#ifdef MSG_PEEK
+/* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
+#ifdef MSG_PEEK
else if(conn->sock[FIRSTSOCKET] == CURL_SOCKET_BAD)
return false;
else {
@@ -1454,25 +1454,25 @@ bool Curl_connalive(struct connectdata *conn)
if(recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
(RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
return false; /* FIN received */
- }
+ }
}
-#endif
+#endif
return true;
-}
-
-/*
- * Close a socket.
- *
- * 'conn' can be NULL, beware!
- */
-int Curl_closesocket(struct connectdata *conn,
- curl_socket_t sock)
-{
- if(conn && conn->fclosesocket) {
+}
+
+/*
+ * Close a socket.
+ *
+ * 'conn' can be NULL, beware!
+ */
+int Curl_closesocket(struct connectdata *conn,
+ curl_socket_t sock)
+{
+ if(conn && conn->fclosesocket) {
if((sock == conn->sock[SECONDARYSOCKET]) && conn->bits.sock_accepted)
- /* if this socket matches the second socket, and that was created with
- accept, then we MUST NOT call the callback but clear the accepted
- status */
+ /* if this socket matches the second socket, and that was created with
+ accept, then we MUST NOT call the callback but clear the accepted
+ status */
conn->bits.sock_accepted = FALSE;
else {
int rc;
@@ -1482,95 +1482,95 @@ int Curl_closesocket(struct connectdata *conn,
Curl_set_in_callback(conn->data, false);
return rc;
}
- }
-
- if(conn)
- /* tell the multi-socket code about this */
+ }
+
+ if(conn)
+ /* tell the multi-socket code about this */
Curl_multi_closed(conn->data, sock);
-
+
sclose(sock);
- return 0;
-}
-
-/*
- * Create a socket based on info from 'conn' and 'ai'.
- *
- * 'addr' should be a pointer to the correct struct to get data back, or NULL.
- * 'sockfd' must be a pointer to a socket descriptor.
- *
- * If the open socket callback is set, used that!
- *
- */
-CURLcode Curl_socket(struct connectdata *conn,
+ return 0;
+}
+
+/*
+ * Create a socket based on info from 'conn' and 'ai'.
+ *
+ * 'addr' should be a pointer to the correct struct to get data back, or NULL.
+ * 'sockfd' must be a pointer to a socket descriptor.
+ *
+ * If the open socket callback is set, used that!
+ *
+ */
+CURLcode Curl_socket(struct connectdata *conn,
const struct Curl_addrinfo *ai,
- struct Curl_sockaddr_ex *addr,
- curl_socket_t *sockfd)
-{
+ struct Curl_sockaddr_ex *addr,
+ curl_socket_t *sockfd)
+{
struct Curl_easy *data = conn->data;
- struct Curl_sockaddr_ex dummy;
-
- if(!addr)
- /* if the caller doesn't want info back, use a local temp copy */
- addr = &dummy;
-
- /*
- * The Curl_sockaddr_ex structure is basically libcurl's external API
- * curl_sockaddr structure with enough space available to directly hold
- * any protocol-specific address structures. The variable declared here
- * will be used to pass / receive data to/from the fopensocket callback
- * if this has been set, before that, it is initialized from parameters.
- */
-
- addr->family = ai->ai_family;
+ struct Curl_sockaddr_ex dummy;
+
+ if(!addr)
+ /* if the caller doesn't want info back, use a local temp copy */
+ addr = &dummy;
+
+ /*
+ * The Curl_sockaddr_ex structure is basically libcurl's external API
+ * curl_sockaddr structure with enough space available to directly hold
+ * any protocol-specific address structures. The variable declared here
+ * will be used to pass / receive data to/from the fopensocket callback
+ * if this has been set, before that, it is initialized from parameters.
+ */
+
+ addr->family = ai->ai_family;
addr->socktype = (conn->transport == TRNSPRT_TCP) ? SOCK_STREAM : SOCK_DGRAM;
addr->protocol = conn->transport != TRNSPRT_TCP ? IPPROTO_UDP :
ai->ai_protocol;
- addr->addrlen = ai->ai_addrlen;
-
- if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
- addr->addrlen = sizeof(struct Curl_sockaddr_storage);
- memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
-
+ addr->addrlen = ai->ai_addrlen;
+
+ if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
+ addr->addrlen = sizeof(struct Curl_sockaddr_storage);
+ memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
+
if(data->set.fopensocket) {
- /*
- * If the opensocket callback is set, all the destination address
- * information is passed to the callback. Depending on this information the
- * callback may opt to abort the connection, this is indicated returning
- * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
- * the callback returns a valid socket the destination address information
- * might have been changed and this 'new' address will actually be used
- * here to connect.
- */
+ /*
+ * If the opensocket callback is set, all the destination address
+ * information is passed to the callback. Depending on this information the
+ * callback may opt to abort the connection, this is indicated returning
+ * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
+ * the callback returns a valid socket the destination address information
+ * might have been changed and this 'new' address will actually be used
+ * here to connect.
+ */
Curl_set_in_callback(data, true);
- *sockfd = data->set.fopensocket(data->set.opensocket_client,
- CURLSOCKTYPE_IPCXN,
- (struct curl_sockaddr *)addr);
+ *sockfd = data->set.fopensocket(data->set.opensocket_client,
+ CURLSOCKTYPE_IPCXN,
+ (struct curl_sockaddr *)addr);
Curl_set_in_callback(data, false);
}
- else
- /* opensocket callback not set, so simply create the socket now */
- *sockfd = socket(addr->family, addr->socktype, addr->protocol);
-
- if(*sockfd == CURL_SOCKET_BAD)
- /* no socket, no connection */
- return CURLE_COULDNT_CONNECT;
-
+ else
+ /* opensocket callback not set, so simply create the socket now */
+ *sockfd = socket(addr->family, addr->socktype, addr->protocol);
+
+ if(*sockfd == CURL_SOCKET_BAD)
+ /* no socket, no connection */
+ return CURLE_COULDNT_CONNECT;
+
if(conn->transport == TRNSPRT_QUIC) {
/* QUIC sockets need to be nonblocking */
(void)curlx_nonblock(*sockfd, TRUE);
}
-#if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
+#if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
if(conn->scope_id && (addr->family == AF_INET6)) {
- struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
+ struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
sa6->sin6_scope_id = conn->scope_id;
- }
-#endif
-
- return CURLE_OK;
-
-}
+ }
+#endif
+
+ return CURLE_OK;
+
+}
/*
* Curl_conncontrol() marks streams or connection for closure.
diff --git a/contrib/libs/curl/lib/connect.h b/contrib/libs/curl/lib/connect.h
index f84f088d14..9b1faf8fb7 100644
--- a/contrib/libs/curl/lib/connect.h
+++ b/contrib/libs/curl/lib/connect.h
@@ -1,56 +1,56 @@
-#ifndef HEADER_CURL_CONNECT_H
-#define HEADER_CURL_CONNECT_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONNECT_H
+#define HEADER_CURL_CONNECT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#include "nonblock.h" /* for curlx_nonblock(), formerly Curl_nonblock() */
-#include "sockaddr.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#include "nonblock.h" /* for curlx_nonblock(), formerly Curl_nonblock() */
+#include "sockaddr.h"
#include "timeval.h"
-
-CURLcode Curl_is_connected(struct connectdata *conn,
- int sockindex,
- bool *connected);
-
-CURLcode Curl_connecthost(struct connectdata *conn,
+
+CURLcode Curl_is_connected(struct connectdata *conn,
+ int sockindex,
+ bool *connected);
+
+CURLcode Curl_connecthost(struct connectdata *conn,
const struct Curl_dns_entry *host);
-
-/* generic function that returns how much time there's left to run, according
- to the timeouts set */
+
+/* generic function that returns how much time there's left to run, according
+ to the timeouts set */
timediff_t Curl_timeleft(struct Curl_easy *data,
struct curltime *nowp,
bool duringconnect);
-
-#define DEFAULT_CONNECT_TIMEOUT 300000 /* milliseconds == five minutes */
-
-/*
- * Used to extract socket and connectdata struct for the most recent
+
+#define DEFAULT_CONNECT_TIMEOUT 300000 /* milliseconds == five minutes */
+
+/*
+ * Used to extract socket and connectdata struct for the most recent
* transfer on the given Curl_easy.
- *
- * The returned socket will be CURL_SOCKET_BAD in case of failure!
- */
+ *
+ * The returned socket will be CURL_SOCKET_BAD in case of failure!
+ */
curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
- struct connectdata **connp);
-
+ struct connectdata **connp);
+
bool Curl_addr2string(struct sockaddr *sa, curl_socklen_t salen,
char *addr, long *port);
@@ -59,58 +59,58 @@ bool Curl_addr2string(struct sockaddr *sa, curl_socklen_t salen,
*/
bool Curl_connalive(struct connectdata *conn);
-#ifdef USE_WINSOCK
-/* When you run a program that uses the Windows Sockets API, you may
- experience slow performance when you copy data to a TCP server.
-
+#ifdef USE_WINSOCK
+/* When you run a program that uses the Windows Sockets API, you may
+ experience slow performance when you copy data to a TCP server.
+
https://support.microsoft.com/kb/823764
-
- Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
- Buffer Size
-
-*/
-void Curl_sndbufset(curl_socket_t sockfd);
-#else
-#define Curl_sndbufset(y) Curl_nop_stmt
-#endif
-
-void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd);
+
+ Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
+ Buffer Size
+
+*/
+void Curl_sndbufset(curl_socket_t sockfd);
+#else
+#define Curl_sndbufset(y) Curl_nop_stmt
+#endif
+
+void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd);
void Curl_conninfo_remote(struct connectdata *conn, curl_socket_t sockfd);
void Curl_conninfo_local(struct connectdata *conn, curl_socket_t sockfd);
-void Curl_persistconninfo(struct connectdata *conn);
-int Curl_closesocket(struct connectdata *conn, curl_socket_t sock);
-
-/*
- * The Curl_sockaddr_ex structure is basically libcurl's external API
- * curl_sockaddr structure with enough space available to directly hold any
- * protocol-specific address structures. The variable declared here will be
- * used to pass / receive data to/from the fopensocket callback if this has
- * been set, before that, it is initialized from parameters.
- */
-struct Curl_sockaddr_ex {
- int family;
- int socktype;
- int protocol;
- unsigned int addrlen;
- union {
- struct sockaddr addr;
- struct Curl_sockaddr_storage buff;
- } _sa_ex_u;
-};
-#define sa_addr _sa_ex_u.addr
-
-/*
- * Create a socket based on info from 'conn' and 'ai'.
- *
- * Fill in 'addr' and 'sockfd' accordingly if OK is returned. If the open
- * socket callback is set, used that!
- *
- */
-CURLcode Curl_socket(struct connectdata *conn,
+void Curl_persistconninfo(struct connectdata *conn);
+int Curl_closesocket(struct connectdata *conn, curl_socket_t sock);
+
+/*
+ * The Curl_sockaddr_ex structure is basically libcurl's external API
+ * curl_sockaddr structure with enough space available to directly hold any
+ * protocol-specific address structures. The variable declared here will be
+ * used to pass / receive data to/from the fopensocket callback if this has
+ * been set, before that, it is initialized from parameters.
+ */
+struct Curl_sockaddr_ex {
+ int family;
+ int socktype;
+ int protocol;
+ unsigned int addrlen;
+ union {
+ struct sockaddr addr;
+ struct Curl_sockaddr_storage buff;
+ } _sa_ex_u;
+};
+#define sa_addr _sa_ex_u.addr
+
+/*
+ * Create a socket based on info from 'conn' and 'ai'.
+ *
+ * Fill in 'addr' and 'sockfd' accordingly if OK is returned. If the open
+ * socket callback is set, used that!
+ *
+ */
+CURLcode Curl_socket(struct connectdata *conn,
const struct Curl_addrinfo *ai,
- struct Curl_sockaddr_ex *addr,
- curl_socket_t *sockfd);
-
+ struct Curl_sockaddr_ex *addr,
+ curl_socket_t *sockfd);
+
/*
* Curl_conncontrol() marks the end of a connection/stream. The 'closeit'
* argument specifies if it is the end of a connection or a stream.
@@ -146,4 +146,4 @@ void Curl_conncontrol(struct connectdata *conn,
bool Curl_conn_data_pending(struct connectdata *conn, int sockindex);
-#endif /* HEADER_CURL_CONNECT_H */
+#endif /* HEADER_CURL_CONNECT_H */
diff --git a/contrib/libs/curl/lib/content_encoding.c b/contrib/libs/curl/lib/content_encoding.c
index 37e83cd7fc..68da3fa1cf 100644
--- a/contrib/libs/curl/lib/content_encoding.c
+++ b/contrib/libs/curl/lib/content_encoding.c
@@ -1,29 +1,29 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "urldata.h"
-#include <curl/curl.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include "urldata.h"
+#include <curl/curl.h>
#include <stddef.h>
#ifdef HAVE_ZLIB_H
@@ -38,14 +38,14 @@
#error #include <zstd.h>
#endif
-#include "sendf.h"
+#include "sendf.h"
#include "http.h"
-#include "content_encoding.h"
+#include "content_encoding.h"
#include "strdup.h"
#include "strcase.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
#define CONTENT_ENCODING_DEFAULT "identity"
#ifndef CURL_DISABLE_HTTP
@@ -55,21 +55,21 @@
#ifdef HAVE_LIBZ
-/* Comment this out if zlib is always going to be at least ver. 1.2.0.4
- (doing so will reduce code size slightly). */
-#define OLD_ZLIB_SUPPORT 1
-
-#define GZIP_MAGIC_0 0x1f
-#define GZIP_MAGIC_1 0x8b
-
-/* gzip flag byte */
-#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
-#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
-#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
-#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
-#define COMMENT 0x10 /* bit 4 set: file comment present */
-#define RESERVED 0xE0 /* bits 5..7: reserved */
-
+/* Comment this out if zlib is always going to be at least ver. 1.2.0.4
+ (doing so will reduce code size slightly). */
+#define OLD_ZLIB_SUPPORT 1
+
+#define GZIP_MAGIC_0 0x1f
+#define GZIP_MAGIC_1 0x8b
+
+/* gzip flag byte */
+#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
+#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
+#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
+#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
+#define COMMENT 0x10 /* bit 4 set: file comment present */
+#define RESERVED 0xE0 /* bits 5..7: reserved */
+
typedef enum {
ZLIB_UNINIT, /* uninitialized */
ZLIB_INIT, /* initialized */
@@ -88,39 +88,39 @@ struct zlib_params {
};
-static voidpf
-zalloc_cb(voidpf opaque, unsigned int items, unsigned int size)
-{
- (void) opaque;
- /* not a typo, keep it calloc() */
- return (voidpf) calloc(items, size);
-}
-
-static void
-zfree_cb(voidpf opaque, voidpf ptr)
-{
- (void) opaque;
- free(ptr);
-}
-
-static CURLcode
-process_zlib_error(struct connectdata *conn, z_stream *z)
-{
+static voidpf
+zalloc_cb(voidpf opaque, unsigned int items, unsigned int size)
+{
+ (void) opaque;
+ /* not a typo, keep it calloc() */
+ return (voidpf) calloc(items, size);
+}
+
+static void
+zfree_cb(voidpf opaque, voidpf ptr)
+{
+ (void) opaque;
+ free(ptr);
+}
+
+static CURLcode
+process_zlib_error(struct connectdata *conn, z_stream *z)
+{
struct Curl_easy *data = conn->data;
- if(z->msg)
+ if(z->msg)
failf(data, "Error while processing content unencoding: %s",
z->msg);
- else
+ else
failf(data, "Error while processing content unencoding: "
"Unknown failure within decompression software.");
-
- return CURLE_BAD_CONTENT_ENCODING;
-}
-
-static CURLcode
+
+ return CURLE_BAD_CONTENT_ENCODING;
+}
+
+static CURLcode
exit_zlib(struct connectdata *conn,
z_stream *z, zlibInitState *zlib_init, CURLcode result)
-{
+{
if(*zlib_init == ZLIB_GZIP_HEADER)
Curl_safefree(z->next_in);
@@ -130,12 +130,12 @@ exit_zlib(struct connectdata *conn,
*zlib_init = ZLIB_UNINIT;
}
- return result;
-}
-
+ return result;
+}
+
static CURLcode process_trailer(struct connectdata *conn,
struct zlib_params *zp)
-{
+{
z_stream *z = &zp->z;
CURLcode result = CURLE_OK;
uInt len = z->avail_in < zp->trailerlen? z->avail_in: zp->trailerlen;
@@ -163,12 +163,12 @@ static CURLcode inflate_stream(struct connectdata *conn,
{
struct zlib_params *zp = (struct zlib_params *) &writer->params;
z_stream *z = &zp->z; /* zlib state structure */
- uInt nread = z->avail_in;
- Bytef *orig_in = z->next_in;
+ uInt nread = z->avail_in;
+ Bytef *orig_in = z->next_in;
bool done = FALSE;
- CURLcode result = CURLE_OK; /* Curl_client_write status */
- char *decomp; /* Put the decompressed data here. */
-
+ CURLcode result = CURLE_OK; /* Curl_client_write status */
+ char *decomp; /* Put the decompressed data here. */
+
/* Check state. */
if(zp->zlib_init != ZLIB_INIT &&
zp->zlib_init != ZLIB_INFLATING &&
@@ -176,28 +176,28 @@ static CURLcode inflate_stream(struct connectdata *conn,
zp->zlib_init != ZLIB_GZIP_INFLATING)
return exit_zlib(conn, z, &zp->zlib_init, CURLE_WRITE_ERROR);
- /* Dynamically allocate a buffer for decompression because it's uncommonly
- large to hold on the stack */
- decomp = malloc(DSIZ);
+ /* Dynamically allocate a buffer for decompression because it's uncommonly
+ large to hold on the stack */
+ decomp = malloc(DSIZ);
if(decomp == NULL)
return exit_zlib(conn, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);
-
- /* because the buffer size is fixed, iteratively decompress and transfer to
+
+ /* because the buffer size is fixed, iteratively decompress and transfer to
the client via downstream_write function. */
while(!done) {
int status; /* zlib status */
done = TRUE;
- /* (re)set buffer for decompressed output for every iteration */
+ /* (re)set buffer for decompressed output for every iteration */
z->next_out = (Bytef *) decomp;
- z->avail_out = DSIZ;
-
+ z->avail_out = DSIZ;
+
#ifdef Z_BLOCK
/* Z_BLOCK is only available in zlib ver. >= 1.2.0.5 */
status = inflate(z, Z_BLOCK);
#else
/* fallback for zlib ver. < 1.2.0.5 */
- status = inflate(z, Z_SYNC_FLUSH);
+ status = inflate(z, Z_SYNC_FLUSH);
#endif
/* Flush output data if some. */
@@ -206,13 +206,13 @@ static CURLcode inflate_stream(struct connectdata *conn,
zp->zlib_init = started; /* Data started. */
result = Curl_unencode_write(conn, writer->downstream, decomp,
DSIZ - z->avail_out);
- if(result) {
+ if(result) {
exit_zlib(conn, z, &zp->zlib_init, result);
break;
- }
- }
+ }
+ }
}
-
+
/* Dispatch by inflate() status. */
switch(status) {
case Z_OK:
@@ -226,8 +226,8 @@ static CURLcode inflate_stream(struct connectdata *conn,
result = process_trailer(conn, zp);
break;
case Z_DATA_ERROR:
- /* some servers seem to not generate zlib headers, so this is an attempt
- to fix and continue anyway */
+ /* some servers seem to not generate zlib headers, so this is an attempt
+ to fix and continue anyway */
if(zp->zlib_init == ZLIB_INIT) {
/* Do not use inflateReset2(): only available since zlib 1.2.3.4. */
(void) inflateEnd(z); /* don't care about the return code */
@@ -240,13 +240,13 @@ static CURLcode inflate_stream(struct connectdata *conn,
break;
}
zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */
- }
+ }
/* FALLTHROUGH */
default:
result = exit_zlib(conn, z, &zp->zlib_init, process_zlib_error(conn, z));
break;
- }
- }
+ }
+ }
free(decomp);
/* We're about to leave this call so the `nread' data bytes won't be seen
@@ -256,23 +256,23 @@ static CURLcode inflate_stream(struct connectdata *conn,
zp->zlib_init = started; /* Cannot restart anymore. */
return result;
-}
-
+}
+
/* Deflate handler. */
static CURLcode deflate_init_writer(struct connectdata *conn,
struct contenc_writer *writer)
-{
+{
struct zlib_params *zp = (struct zlib_params *) &writer->params;
z_stream *z = &zp->z; /* zlib state structure */
-
+
if(!writer->downstream)
return CURLE_WRITE_ERROR;
-
+
/* Initialize zlib */
z->zalloc = (alloc_func) zalloc_cb;
z->zfree = (free_func) zfree_cb;
-
+
if(inflateInit(z) != Z_OK)
return process_zlib_error(conn, z);
zp->zlib_init = ZLIB_INIT;
@@ -286,17 +286,17 @@ static CURLcode deflate_unencode_write(struct connectdata *conn,
struct zlib_params *zp = (struct zlib_params *) &writer->params;
z_stream *z = &zp->z; /* zlib state structure */
- /* Set the compressed input when this function is called */
+ /* Set the compressed input when this function is called */
z->next_in = (Bytef *) buf;
z->avail_in = (uInt) nbytes;
-
+
if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER)
return process_trailer(conn, zp);
- /* Now uncompress the data */
+ /* Now uncompress the data */
return inflate_stream(conn, writer, ZLIB_INFLATING);
-}
-
+}
+
static void deflate_close_writer(struct connectdata *conn,
struct contenc_writer *writer)
{
@@ -349,218 +349,218 @@ static CURLcode gzip_init_writer(struct connectdata *conn,
return CURLE_OK;
}
-#ifdef OLD_ZLIB_SUPPORT
-/* Skip over the gzip header */
-static enum {
- GZIP_OK,
- GZIP_BAD,
- GZIP_UNDERFLOW
-} check_gzip_header(unsigned char const *data, ssize_t len, ssize_t *headerlen)
-{
- int method, flags;
- const ssize_t totallen = len;
-
- /* The shortest header is 10 bytes */
- if(len < 10)
- return GZIP_UNDERFLOW;
-
- if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1))
- return GZIP_BAD;
-
- method = data[2];
- flags = data[3];
-
- if(method != Z_DEFLATED || (flags & RESERVED) != 0) {
- /* Can't handle this compression method or unknown flag */
- return GZIP_BAD;
- }
-
- /* Skip over time, xflags, OS code and all previous bytes */
- len -= 10;
- data += 10;
-
- if(flags & EXTRA_FIELD) {
- ssize_t extra_len;
-
- if(len < 2)
- return GZIP_UNDERFLOW;
-
- extra_len = (data[1] << 8) | data[0];
-
+#ifdef OLD_ZLIB_SUPPORT
+/* Skip over the gzip header */
+static enum {
+ GZIP_OK,
+ GZIP_BAD,
+ GZIP_UNDERFLOW
+} check_gzip_header(unsigned char const *data, ssize_t len, ssize_t *headerlen)
+{
+ int method, flags;
+ const ssize_t totallen = len;
+
+ /* The shortest header is 10 bytes */
+ if(len < 10)
+ return GZIP_UNDERFLOW;
+
+ if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1))
+ return GZIP_BAD;
+
+ method = data[2];
+ flags = data[3];
+
+ if(method != Z_DEFLATED || (flags & RESERVED) != 0) {
+ /* Can't handle this compression method or unknown flag */
+ return GZIP_BAD;
+ }
+
+ /* Skip over time, xflags, OS code and all previous bytes */
+ len -= 10;
+ data += 10;
+
+ if(flags & EXTRA_FIELD) {
+ ssize_t extra_len;
+
+ if(len < 2)
+ return GZIP_UNDERFLOW;
+
+ extra_len = (data[1] << 8) | data[0];
+
if(len < (extra_len + 2))
- return GZIP_UNDERFLOW;
-
- len -= (extra_len + 2);
- data += (extra_len + 2);
- }
-
- if(flags & ORIG_NAME) {
- /* Skip over NUL-terminated file name */
- while(len && *data) {
- --len;
- ++data;
- }
- if(!len || *data)
- return GZIP_UNDERFLOW;
-
- /* Skip over the NUL */
- --len;
- ++data;
- }
-
- if(flags & COMMENT) {
- /* Skip over NUL-terminated comment */
- while(len && *data) {
- --len;
- ++data;
- }
- if(!len || *data)
- return GZIP_UNDERFLOW;
-
- /* Skip over the NUL */
- --len;
- }
-
- if(flags & HEAD_CRC) {
- if(len < 2)
- return GZIP_UNDERFLOW;
-
- len -= 2;
- }
-
- *headerlen = totallen - len;
- return GZIP_OK;
-}
-#endif
-
+ return GZIP_UNDERFLOW;
+
+ len -= (extra_len + 2);
+ data += (extra_len + 2);
+ }
+
+ if(flags & ORIG_NAME) {
+ /* Skip over NUL-terminated file name */
+ while(len && *data) {
+ --len;
+ ++data;
+ }
+ if(!len || *data)
+ return GZIP_UNDERFLOW;
+
+ /* Skip over the NUL */
+ --len;
+ ++data;
+ }
+
+ if(flags & COMMENT) {
+ /* Skip over NUL-terminated comment */
+ while(len && *data) {
+ --len;
+ ++data;
+ }
+ if(!len || *data)
+ return GZIP_UNDERFLOW;
+
+ /* Skip over the NUL */
+ --len;
+ }
+
+ if(flags & HEAD_CRC) {
+ if(len < 2)
+ return GZIP_UNDERFLOW;
+
+ len -= 2;
+ }
+
+ *headerlen = totallen - len;
+ return GZIP_OK;
+}
+#endif
+
static CURLcode gzip_unencode_write(struct connectdata *conn,
struct contenc_writer *writer,
const char *buf, size_t nbytes)
-{
+{
struct zlib_params *zp = (struct zlib_params *) &writer->params;
z_stream *z = &zp->z; /* zlib state structure */
-
+
if(zp->zlib_init == ZLIB_INIT_GZIP) {
- /* Let zlib handle the gzip decompression entirely */
+ /* Let zlib handle the gzip decompression entirely */
z->next_in = (Bytef *) buf;
z->avail_in = (uInt) nbytes;
- /* Now uncompress the data */
+ /* Now uncompress the data */
return inflate_stream(conn, writer, ZLIB_INIT_GZIP);
- }
-
-#ifndef OLD_ZLIB_SUPPORT
- /* Support for old zlib versions is compiled away and we are running with
- an old version, so return an error. */
+ }
+
+#ifndef OLD_ZLIB_SUPPORT
+ /* Support for old zlib versions is compiled away and we are running with
+ an old version, so return an error. */
return exit_zlib(conn, z, &zp->zlib_init, CURLE_WRITE_ERROR);
-
-#else
- /* This next mess is to get around the potential case where there isn't
- * enough data passed in to skip over the gzip header. If that happens, we
- * malloc a block and copy what we have then wait for the next call. If
- * there still isn't enough (this is definitely a worst-case scenario), we
- * make the block bigger, copy the next part in and keep waiting.
- *
- * This is only required with zlib versions < 1.2.0.4 as newer versions
- * can handle the gzip header themselves.
- */
-
+
+#else
+ /* This next mess is to get around the potential case where there isn't
+ * enough data passed in to skip over the gzip header. If that happens, we
+ * malloc a block and copy what we have then wait for the next call. If
+ * there still isn't enough (this is definitely a worst-case scenario), we
+ * make the block bigger, copy the next part in and keep waiting.
+ *
+ * This is only required with zlib versions < 1.2.0.4 as newer versions
+ * can handle the gzip header themselves.
+ */
+
switch(zp->zlib_init) {
- /* Skip over gzip header? */
- case ZLIB_INIT:
- {
- /* Initial call state */
- ssize_t hlen;
-
+ /* Skip over gzip header? */
+ case ZLIB_INIT:
+ {
+ /* Initial call state */
+ ssize_t hlen;
+
switch(check_gzip_header((unsigned char *) buf, nbytes, &hlen)) {
- case GZIP_OK:
+ case GZIP_OK:
z->next_in = (Bytef *) buf + hlen;
z->avail_in = (uInt) (nbytes - hlen);
zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */
- break;
-
- case GZIP_UNDERFLOW:
- /* We need more data so we can find the end of the gzip header. It's
- * possible that the memory block we malloc here will never be freed if
- * the transfer abruptly aborts after this point. Since it's unlikely
- * that circumstances will be right for this code path to be followed in
- * the first place, and it's even more unlikely for a transfer to fail
- * immediately afterwards, it should seldom be a problem.
- */
+ break;
+
+ case GZIP_UNDERFLOW:
+ /* We need more data so we can find the end of the gzip header. It's
+ * possible that the memory block we malloc here will never be freed if
+ * the transfer abruptly aborts after this point. Since it's unlikely
+ * that circumstances will be right for this code path to be followed in
+ * the first place, and it's even more unlikely for a transfer to fail
+ * immediately afterwards, it should seldom be a problem.
+ */
z->avail_in = (uInt) nbytes;
- z->next_in = malloc(z->avail_in);
- if(z->next_in == NULL) {
+ z->next_in = malloc(z->avail_in);
+ if(z->next_in == NULL) {
return exit_zlib(conn, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);
- }
+ }
memcpy(z->next_in, buf, z->avail_in);
zp->zlib_init = ZLIB_GZIP_HEADER; /* Need more gzip header data state */
- /* We don't have any data to inflate yet */
- return CURLE_OK;
-
- case GZIP_BAD:
- default:
+ /* We don't have any data to inflate yet */
+ return CURLE_OK;
+
+ case GZIP_BAD:
+ default:
return exit_zlib(conn, z, &zp->zlib_init, process_zlib_error(conn, z));
- }
-
- }
- break;
-
- case ZLIB_GZIP_HEADER:
- {
- /* Need more gzip header data state */
- ssize_t hlen;
+ }
+
+ }
+ break;
+
+ case ZLIB_GZIP_HEADER:
+ {
+ /* Need more gzip header data state */
+ ssize_t hlen;
z->avail_in += (uInt) nbytes;
z->next_in = Curl_saferealloc(z->next_in, z->avail_in);
- if(z->next_in == NULL) {
+ if(z->next_in == NULL) {
return exit_zlib(conn, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);
- }
- /* Append the new block of data to the previous one */
+ }
+ /* Append the new block of data to the previous one */
memcpy(z->next_in + z->avail_in - nbytes, buf, nbytes);
-
+
switch(check_gzip_header(z->next_in, z->avail_in, &hlen)) {
- case GZIP_OK:
- /* This is the zlib stream data */
- free(z->next_in);
- /* Don't point into the malloced block since we just freed it */
+ case GZIP_OK:
+ /* This is the zlib stream data */
+ free(z->next_in);
+ /* Don't point into the malloced block since we just freed it */
z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in;
z->avail_in = (uInt) (z->avail_in - hlen);
zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */
- break;
-
- case GZIP_UNDERFLOW:
- /* We still don't have any data to inflate! */
- return CURLE_OK;
-
- case GZIP_BAD:
- default:
+ break;
+
+ case GZIP_UNDERFLOW:
+ /* We still don't have any data to inflate! */
+ return CURLE_OK;
+
+ case GZIP_BAD:
+ default:
return exit_zlib(conn, z, &zp->zlib_init, process_zlib_error(conn, z));
- }
-
- }
- break;
-
+ }
+
+ }
+ break;
+
case ZLIB_EXTERNAL_TRAILER:
z->next_in = (Bytef *) buf;
z->avail_in = (uInt) nbytes;
return process_trailer(conn, zp);
- case ZLIB_GZIP_INFLATING:
- default:
- /* Inflating stream state */
+ case ZLIB_GZIP_INFLATING:
+ default:
+ /* Inflating stream state */
z->next_in = (Bytef *) buf;
z->avail_in = (uInt) nbytes;
- break;
- }
-
- if(z->avail_in == 0) {
- /* We don't have any data to inflate; wait until next time */
- return CURLE_OK;
- }
-
- /* We've parsed the header, now uncompress the data */
+ break;
+ }
+
+ if(z->avail_in == 0) {
+ /* We don't have any data to inflate; wait until next time */
+ return CURLE_OK;
+ }
+
+ /* We've parsed the header, now uncompress the data */
return inflate_stream(conn, writer, ZLIB_GZIP_INFLATING);
-#endif
-}
-
+#endif
+}
+
static void gzip_close_writer(struct connectdata *conn,
struct contenc_writer *writer)
{
@@ -998,10 +998,10 @@ CURLcode Curl_unencode_write(struct connectdata *conn,
}
/* Close and clean-up the connection's writer stack. */
-void Curl_unencode_cleanup(struct connectdata *conn)
-{
+void Curl_unencode_cleanup(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- struct SingleRequest *k = &data->req;
+ struct SingleRequest *k = &data->req;
struct contenc_writer *writer = k->writer_stack;
while(writer) {
@@ -1010,8 +1010,8 @@ void Curl_unencode_cleanup(struct connectdata *conn)
free(writer);
writer = k->writer_stack;
}
-}
-
+}
+
/* Find the content encoding by name. */
static const struct content_encoding *find_encoding(const char *name,
size_t len)
diff --git a/contrib/libs/curl/lib/content_encoding.h b/contrib/libs/curl/lib/content_encoding.h
index 7d2b1ecbda..70310875a0 100644
--- a/contrib/libs/curl/lib/content_encoding.h
+++ b/contrib/libs/curl/lib/content_encoding.h
@@ -1,34 +1,34 @@
-#ifndef HEADER_CURL_CONTENT_ENCODING_H
-#define HEADER_CURL_CONTENT_ENCODING_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CONTENT_ENCODING_H
+#define HEADER_CURL_CONTENT_ENCODING_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
struct contenc_writer {
const struct content_encoding *handler; /* Encoding handler. */
struct contenc_writer *downstream; /* Downstream writer. */
void *params; /* Encoding-specific storage (variable length). */
};
-
+
/* Content encoding writer. */
struct content_encoding {
const char *name; /* Encoding name. */
@@ -42,8 +42,8 @@ struct content_encoding {
struct contenc_writer *writer);
size_t paramsize;
};
-
-
+
+
CURLcode Curl_build_unencoding_stack(struct connectdata *conn,
const char *enclist, int maybechunked);
CURLcode Curl_unencode_write(struct connectdata *conn,
@@ -52,4 +52,4 @@ CURLcode Curl_unencode_write(struct connectdata *conn,
void Curl_unencode_cleanup(struct connectdata *conn);
char *Curl_all_content_encodings(void);
-#endif /* HEADER_CURL_CONTENT_ENCODING_H */
+#endif /* HEADER_CURL_CONTENT_ENCODING_H */
diff --git a/contrib/libs/curl/lib/cookie.c b/contrib/libs/curl/lib/cookie.c
index 7b5b57126c..e88678c219 100644
--- a/contrib/libs/curl/lib/cookie.c
+++ b/contrib/libs/curl/lib/cookie.c
@@ -1,112 +1,112 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/***
-
-
-RECEIVING COOKIE INFORMATION
-============================
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/***
+
+
+RECEIVING COOKIE INFORMATION
+============================
+
struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
const char *file, struct CookieInfo *inc, bool newsession);
-
- Inits a cookie struct to store data in a local file. This is always
- called before any cookies are set.
-
+
+ Inits a cookie struct to store data in a local file. This is always
+ called before any cookies are set.
+
struct Cookie *Curl_cookie_add(struct Curl_easy *data,
struct CookieInfo *c, bool httpheader, char *lineptr,
const char *domain, const char *path);
-
+
The 'lineptr' parameter is a full "Set-cookie:" line as
- received from a server.
-
- The function need to replace previously stored lines that this new
+ received from a server.
+
+ The function need to replace previously stored lines that this new
line supersedes.
-
- It may remove lines that are expired.
-
- It should return an indication of success/error.
-
-
-SENDING COOKIE INFORMATION
-==========================
-
+
+ It may remove lines that are expired.
+
+ It should return an indication of success/error.
+
+
+SENDING COOKIE INFORMATION
+==========================
+
struct Cookies *Curl_cookie_getlist(struct CookieInfo *cookie,
char *host, char *path, bool secure);
-
- For a given host and path, return a linked list of cookies that
- the client should send to the server if used now. The secure
- boolean informs the cookie if a secure connection is achieved or
- not.
-
- It shall only return cookies that haven't expired.
-
-
-Example set of cookies:
-
- Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
- Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
- domain=.fidelity.com; path=/ftgw; secure
- Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
- domain=.fidelity.com; path=/; secure
- Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
- domain=.fidelity.com; path=/; secure
- Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
- domain=.fidelity.com; path=/; secure
- Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
- domain=.fidelity.com; path=/; secure
- Set-cookie:
- Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
- 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
-****/
-
-
-#include "curl_setup.h"
-
-#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
-
-#include "urldata.h"
-#include "cookie.h"
+
+ For a given host and path, return a linked list of cookies that
+ the client should send to the server if used now. The secure
+ boolean informs the cookie if a secure connection is achieved or
+ not.
+
+ It shall only return cookies that haven't expired.
+
+
+Example set of cookies:
+
+ Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
+ Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
+ domain=.fidelity.com; path=/ftgw; secure
+ Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
+ domain=.fidelity.com; path=/; secure
+ Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
+ domain=.fidelity.com; path=/; secure
+ Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
+ domain=.fidelity.com; path=/; secure
+ Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
+ domain=.fidelity.com; path=/; secure
+ Set-cookie:
+ Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
+ 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
+****/
+
+
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+
+#include "urldata.h"
+#include "cookie.h"
#include "psl.h"
-#include "strtok.h"
-#include "sendf.h"
-#include "slist.h"
-#include "share.h"
-#include "strtoofft.h"
+#include "strtok.h"
+#include "sendf.h"
+#include "slist.h"
+#include "share.h"
+#include "strtoofft.h"
#include "strcase.h"
#include "curl_get_line.h"
-#include "curl_memrchr.h"
+#include "curl_memrchr.h"
#include "inet_pton.h"
#include "parsedate.h"
#include "rand.h"
#include "rename.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-static void freecookie(struct Cookie *co)
-{
+#include "memdebug.h"
+
+static void freecookie(struct Cookie *co)
+{
free(co->expirestr);
free(co->domain);
free(co->path);
@@ -115,35 +115,35 @@ static void freecookie(struct Cookie *co)
free(co->value);
free(co->maxage);
free(co->version);
- free(co);
-}
-
-static bool tailmatch(const char *cooke_domain, const char *hostname)
-{
- size_t cookie_domain_len = strlen(cooke_domain);
- size_t hostname_len = strlen(hostname);
-
- if(hostname_len < cookie_domain_len)
- return FALSE;
-
+ free(co);
+}
+
+static bool tailmatch(const char *cooke_domain, const char *hostname)
+{
+ size_t cookie_domain_len = strlen(cooke_domain);
+ size_t hostname_len = strlen(hostname);
+
+ if(hostname_len < cookie_domain_len)
+ return FALSE;
+
if(!strcasecompare(cooke_domain, hostname + hostname_len-cookie_domain_len))
- return FALSE;
-
- /* A lead char of cookie_domain is not '.'.
- RFC6265 4.1.2.3. The Domain Attribute says:
- For example, if the value of the Domain attribute is
- "example.com", the user agent will include the cookie in the Cookie
- header when making HTTP requests to example.com, www.example.com, and
- www.corp.example.com.
- */
- if(hostname_len == cookie_domain_len)
- return TRUE;
- if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
- return TRUE;
- return FALSE;
-}
-
-/*
+ return FALSE;
+
+ /* A lead char of cookie_domain is not '.'.
+ RFC6265 4.1.2.3. The Domain Attribute says:
+ For example, if the value of the Domain attribute is
+ "example.com", the user agent will include the cookie in the Cookie
+ header when making HTTP requests to example.com, www.example.com, and
+ www.corp.example.com.
+ */
+ if(hostname_len == cookie_domain_len)
+ return TRUE;
+ if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
+ return TRUE;
+ return FALSE;
+}
+
+/*
* Return true if the given string is an IP(v4|v6) address.
*/
static bool isip(const char *domain)
@@ -166,81 +166,81 @@ static bool isip(const char *domain)
}
/*
- * matching cookie path and url path
- * RFC6265 5.1.4 Paths and Path-Match
- */
+ * matching cookie path and url path
+ * RFC6265 5.1.4 Paths and Path-Match
+ */
static bool pathmatch(const char *cookie_path, const char *request_uri)
-{
- size_t cookie_path_len;
- size_t uri_path_len;
+{
+ size_t cookie_path_len;
+ size_t uri_path_len;
char *uri_path = NULL;
char *pos;
- bool ret = FALSE;
-
- /* cookie_path must not have last '/' separator. ex: /sample */
- cookie_path_len = strlen(cookie_path);
- if(1 == cookie_path_len) {
- /* cookie_path must be '/' */
- return TRUE;
- }
-
- uri_path = strdup(request_uri);
- if(!uri_path)
- return FALSE;
- pos = strchr(uri_path, '?');
- if(pos)
- *pos = 0x0;
-
- /* #-fragments are already cut off! */
- if(0 == strlen(uri_path) || uri_path[0] != '/') {
- free(uri_path);
- uri_path = strdup("/");
- if(!uri_path)
- return FALSE;
- }
-
- /* here, RFC6265 5.1.4 says
- 4. Output the characters of the uri-path from the first character up
- to, but not including, the right-most %x2F ("/").
- but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
- without redirect.
- Ignore this algorithm because /hoge is uri path for this case
- (uri path is not /).
- */
-
- uri_path_len = strlen(uri_path);
-
- if(uri_path_len < cookie_path_len) {
- ret = FALSE;
- goto pathmatched;
- }
-
- /* not using checkprefix() because matching should be case-sensitive */
- if(strncmp(cookie_path, uri_path, cookie_path_len)) {
- ret = FALSE;
- goto pathmatched;
- }
-
- /* The cookie-path and the uri-path are identical. */
- if(cookie_path_len == uri_path_len) {
- ret = TRUE;
- goto pathmatched;
- }
-
+ bool ret = FALSE;
+
+ /* cookie_path must not have last '/' separator. ex: /sample */
+ cookie_path_len = strlen(cookie_path);
+ if(1 == cookie_path_len) {
+ /* cookie_path must be '/' */
+ return TRUE;
+ }
+
+ uri_path = strdup(request_uri);
+ if(!uri_path)
+ return FALSE;
+ pos = strchr(uri_path, '?');
+ if(pos)
+ *pos = 0x0;
+
+ /* #-fragments are already cut off! */
+ if(0 == strlen(uri_path) || uri_path[0] != '/') {
+ free(uri_path);
+ uri_path = strdup("/");
+ if(!uri_path)
+ return FALSE;
+ }
+
+ /* here, RFC6265 5.1.4 says
+ 4. Output the characters of the uri-path from the first character up
+ to, but not including, the right-most %x2F ("/").
+ but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
+ without redirect.
+ Ignore this algorithm because /hoge is uri path for this case
+ (uri path is not /).
+ */
+
+ uri_path_len = strlen(uri_path);
+
+ if(uri_path_len < cookie_path_len) {
+ ret = FALSE;
+ goto pathmatched;
+ }
+
+ /* not using checkprefix() because matching should be case-sensitive */
+ if(strncmp(cookie_path, uri_path, cookie_path_len)) {
+ ret = FALSE;
+ goto pathmatched;
+ }
+
+ /* The cookie-path and the uri-path are identical. */
+ if(cookie_path_len == uri_path_len) {
+ ret = TRUE;
+ goto pathmatched;
+ }
+
/* here, cookie_path_len < uri_path_len */
- if(uri_path[cookie_path_len] == '/') {
- ret = TRUE;
- goto pathmatched;
- }
-
- ret = FALSE;
-
-pathmatched:
- free(uri_path);
- return ret;
-}
-
-/*
+ if(uri_path[cookie_path_len] == '/') {
+ ret = TRUE;
+ goto pathmatched;
+ }
+
+ ret = FALSE;
+
+pathmatched:
+ free(uri_path);
+ return ret;
+}
+
+/*
* Return the top-level domain, for optimal hashing.
*/
static const char *get_top_domain(const char * const domain, size_t *outlen)
@@ -296,53 +296,53 @@ static size_t cookiehash(const char * const domain)
}
/*
- * cookie path sanitize
- */
-static char *sanitize_cookie_path(const char *cookie_path)
-{
- size_t len;
- char *new_path = strdup(cookie_path);
- if(!new_path)
- return NULL;
-
- /* some stupid site sends path attribute with '"'. */
+ * cookie path sanitize
+ */
+static char *sanitize_cookie_path(const char *cookie_path)
+{
+ size_t len;
+ char *new_path = strdup(cookie_path);
+ if(!new_path)
+ return NULL;
+
+ /* some stupid site sends path attribute with '"'. */
len = strlen(new_path);
- if(new_path[0] == '\"') {
+ if(new_path[0] == '\"') {
memmove((void *)new_path, (const void *)(new_path + 1), len);
len--;
- }
+ }
if(len && (new_path[len - 1] == '\"')) {
new_path[len - 1] = 0x0;
len--;
- }
-
- /* RFC6265 5.2.4 The Path Attribute */
- if(new_path[0] != '/') {
- /* Let cookie-path be the default-path. */
- free(new_path);
- new_path = strdup("/");
- return new_path;
- }
-
- /* convert /hoge/ to /hoge */
+ }
+
+ /* RFC6265 5.2.4 The Path Attribute */
+ if(new_path[0] != '/') {
+ /* Let cookie-path be the default-path. */
+ free(new_path);
+ new_path = strdup("/");
+ return new_path;
+ }
+
+ /* convert /hoge/ to /hoge */
if(len && new_path[len - 1] == '/') {
- new_path[len - 1] = 0x0;
- }
-
- return new_path;
-}
-
-/*
- * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
+ new_path[len - 1] = 0x0;
+ }
+
+ return new_path;
+}
+
+/*
+ * Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
*
* NOTE: OOM or cookie parsing failures are ignored.
- */
+ */
void Curl_cookie_loadfiles(struct Curl_easy *data)
-{
- struct curl_slist *list = data->change.cookielist;
- if(list) {
- Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
- while(list) {
+{
+ struct curl_slist *list = data->change.cookielist;
+ if(list) {
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+ while(list) {
struct CookieInfo *newcookies = Curl_cookie_init(data,
list->data,
data->cookies,
@@ -354,35 +354,35 @@ void Curl_cookie_loadfiles(struct Curl_easy *data)
infof(data, "ignoring failed cookie_init for %s\n", list->data);
else
data->cookies = newcookies;
- list = list->next;
- }
- curl_slist_free_all(data->change.cookielist); /* clean up list */
- data->change.cookielist = NULL; /* don't do this again! */
- Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
- }
-}
-
-/*
- * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
- * that will be freed before the allocated string is stored there.
- *
- * It is meant to easily replace strdup()
- */
-static void strstore(char **str, const char *newstr)
-{
+ list = list->next;
+ }
+ curl_slist_free_all(data->change.cookielist); /* clean up list */
+ data->change.cookielist = NULL; /* don't do this again! */
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ }
+}
+
+/*
+ * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL
+ * that will be freed before the allocated string is stored there.
+ *
+ * It is meant to easily replace strdup()
+ */
+static void strstore(char **str, const char *newstr)
+{
free(*str);
- *str = strdup(newstr);
-}
-
-/*
- * remove_expired() removes expired cookies.
- */
-static void remove_expired(struct CookieInfo *cookies)
-{
+ *str = strdup(newstr);
+}
+
+/*
+ * remove_expired() removes expired cookies.
+ */
+static void remove_expired(struct CookieInfo *cookies)
+{
struct Cookie *co, *nx;
- curl_off_t now = (curl_off_t)time(NULL);
+ curl_off_t now = (curl_off_t)time(NULL);
unsigned int i;
-
+
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
struct Cookie *pv = NULL;
co = cookies->cookies[i];
@@ -397,103 +397,103 @@ static void remove_expired(struct CookieInfo *cookies)
}
cookies->numcookies--;
freecookie(co);
- }
- else {
+ }
+ else {
pv = co;
- }
+ }
co = nx;
- }
- }
-}
-
+ }
+ }
+}
+
/* Make sure domain contains a dot or is localhost. */
static bool bad_domain(const char *domain)
{
return !strchr(domain, '.') && !strcasecompare(domain, "localhost");
}
-/****************************************************************************
- *
- * Curl_cookie_add()
- *
- * Add a single cookie line to the cookie keeping object.
- *
- * Be aware that sometimes we get an IP-only host name, and that might also be
- * a numerical IPv6 address.
- *
+/****************************************************************************
+ *
+ * Curl_cookie_add()
+ *
+ * Add a single cookie line to the cookie keeping object.
+ *
+ * Be aware that sometimes we get an IP-only host name, and that might also be
+ * a numerical IPv6 address.
+ *
* Returns NULL on out of memory or invalid cookie. This is suboptimal,
* as they should be treated separately.
- ***************************************************************************/
-
-struct Cookie *
+ ***************************************************************************/
+
+struct Cookie *
Curl_cookie_add(struct Curl_easy *data,
- /* The 'data' pointer here may be NULL at times, and thus
- must only be used very carefully for things that can deal
- with data being NULL. Such as infof() and similar */
-
- struct CookieInfo *c,
- bool httpheader, /* TRUE if HTTP header-style line */
+ /* The 'data' pointer here may be NULL at times, and thus
+ must only be used very carefully for things that can deal
+ with data being NULL. Such as infof() and similar */
+
+ struct CookieInfo *c,
+ bool httpheader, /* TRUE if HTTP header-style line */
bool noexpire, /* if TRUE, skip remove_expired() */
- char *lineptr, /* first character of the line */
- const char *domain, /* default domain */
+ char *lineptr, /* first character of the line */
+ const char *domain, /* default domain */
const char *path, /* full path used when this cookie is set,
- used to get default path for the cookie
- unless set */
+ used to get default path for the cookie
+ unless set */
bool secure) /* TRUE if connection is over secure origin */
-{
- struct Cookie *clist;
- struct Cookie *co;
+{
+ struct Cookie *clist;
+ struct Cookie *co;
struct Cookie *lastc = NULL;
- time_t now = time(NULL);
- bool replace_old = FALSE;
- bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
+ time_t now = time(NULL);
+ bool replace_old = FALSE;
+ bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
size_t myhash;
-
-#ifdef CURL_DISABLE_VERBOSE_STRINGS
- (void)data;
-#endif
-
- /* First, alloc and init a new struct for it */
- co = calloc(1, sizeof(struct Cookie));
- if(!co)
- return NULL; /* bail out if we're this low on memory */
-
- if(httpheader) {
- /* This line was read off a HTTP-header */
+
+#ifdef CURL_DISABLE_VERBOSE_STRINGS
+ (void)data;
+#endif
+
+ /* First, alloc and init a new struct for it */
+ co = calloc(1, sizeof(struct Cookie));
+ if(!co)
+ return NULL; /* bail out if we're this low on memory */
+
+ if(httpheader) {
+ /* This line was read off a HTTP-header */
char name[MAX_NAME];
char what[MAX_NAME];
- const char *ptr;
- const char *semiptr;
-
+ const char *ptr;
+ const char *semiptr;
+
size_t linelength = strlen(lineptr);
if(linelength > MAX_COOKIE_LINE) {
/* discard overly long lines at once */
- free(co);
- return NULL;
- }
-
+ free(co);
+ return NULL;
+ }
+
semiptr = strchr(lineptr, ';'); /* first, find a semicolon */
-
- while(*lineptr && ISBLANK(*lineptr))
- lineptr++;
-
- ptr = lineptr;
- do {
- /* we have a <what>=<this> pair or a stand-alone word here */
+
+ while(*lineptr && ISBLANK(*lineptr))
+ lineptr++;
+
+ ptr = lineptr;
+ do {
+ /* we have a <what>=<this> pair or a stand-alone word here */
name[0] = what[0] = 0; /* init the buffers */
if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
MAX_NAME_TXT "[^;\r\n]",
- name, what)) {
- /* Use strstore() below to properly deal with received cookie
- headers that have the same string property set more than once,
- and then we use the last one. */
- const char *whatptr;
- bool done = FALSE;
- bool sep;
+ name, what)) {
+ /* Use strstore() below to properly deal with received cookie
+ headers that have the same string property set more than once,
+ and then we use the last one. */
+ const char *whatptr;
+ bool done = FALSE;
+ bool sep;
size_t len = strlen(what);
size_t nlen = strlen(name);
const char *endofn = &ptr[ nlen ];
-
+
if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) ||
((nlen + len) > MAX_NAME)) {
/* too long individual name or contents, or too long combination of
@@ -504,10 +504,10 @@ Curl_cookie_add(struct Curl_easy *data,
nlen, len);
return NULL;
}
-
- /* name ends with a '=' ? */
- sep = (*endofn == '=')?TRUE:FALSE;
-
+
+ /* name ends with a '=' ? */
+ sep = (*endofn == '=')?TRUE:FALSE;
+
if(nlen) {
endofn--; /* move to the last character */
if(ISBLANK(*endofn)) {
@@ -520,17 +520,17 @@ Curl_cookie_add(struct Curl_easy *data,
}
}
- /* Strip off trailing whitespace from the 'what' */
- while(len && ISBLANK(what[len-1])) {
+ /* Strip off trailing whitespace from the 'what' */
+ while(len && ISBLANK(what[len-1])) {
what[len-1] = 0;
- len--;
- }
-
- /* Skip leading whitespace from the 'what' */
+ len--;
+ }
+
+ /* Skip leading whitespace from the 'what' */
whatptr = what;
- while(*whatptr && ISBLANK(*whatptr))
- whatptr++;
-
+ while(*whatptr && ISBLANK(*whatptr))
+ whatptr++;
+
/*
* Check if we have a reserved prefix set before anything else, as we
* otherwise have to test for the prefix in both the cookie name and
@@ -560,9 +560,9 @@ Curl_cookie_add(struct Curl_easy *data,
}
}
else if(!len) {
- /* this was a "<name>=" with no content, and we must allow
- 'secure' and 'httponly' specified this weirdly */
- done = TRUE;
+ /* this was a "<name>=" with no content, and we must allow
+ 'secure' and 'httponly' specified this weirdly */
+ done = TRUE;
/*
* secure cookies are only allowed to be set when the connection is
* using a secure protocol, or when the cookie is being set by
@@ -578,35 +578,35 @@ Curl_cookie_add(struct Curl_easy *data,
}
}
else if(strcasecompare("httponly", name))
- co->httponly = TRUE;
- else if(sep)
- /* there was a '=' so we're not done parsing this field */
- done = FALSE;
- }
- if(done)
- ;
+ co->httponly = TRUE;
+ else if(sep)
+ /* there was a '=' so we're not done parsing this field */
+ done = FALSE;
+ }
+ if(done)
+ ;
else if(strcasecompare("path", name)) {
- strstore(&co->path, whatptr);
- if(!co->path) {
- badcookie = TRUE; /* out of memory bad */
- break;
- }
+ strstore(&co->path, whatptr);
+ if(!co->path) {
+ badcookie = TRUE; /* out of memory bad */
+ break;
+ }
free(co->spath); /* if this is set again */
- co->spath = sanitize_cookie_path(co->path);
- if(!co->spath) {
- badcookie = TRUE; /* out of memory bad */
- break;
- }
- }
+ co->spath = sanitize_cookie_path(co->path);
+ if(!co->spath) {
+ badcookie = TRUE; /* out of memory bad */
+ break;
+ }
+ }
else if(strcasecompare("domain", name)) {
bool is_ip;
- /* Now, we make sure that our host is within the given domain,
- or the given domain is not valid and thus cannot be set. */
-
- if('.' == whatptr[0])
- whatptr++; /* ignore preceding dot */
-
+ /* Now, we make sure that our host is within the given domain,
+ or the given domain is not valid and thus cannot be set. */
+
+ if('.' == whatptr[0])
+ whatptr++; /* ignore preceding dot */
+
#ifndef USE_LIBPSL
/*
* Without PSL we don't know when the incoming cookie is set on a
@@ -623,78 +623,78 @@ Curl_cookie_add(struct Curl_easy *data,
|| (is_ip && !strcmp(whatptr, domain))
|| (!is_ip && tailmatch(whatptr, domain))) {
strstore(&co->domain, whatptr);
- if(!co->domain) {
- badcookie = TRUE;
- break;
- }
+ if(!co->domain) {
+ badcookie = TRUE;
+ break;
+ }
if(!is_ip)
co->tailmatch = TRUE; /* we always do that if the domain name was
given */
- }
- else {
- /* we did not get a tailmatch and then the attempted set domain
- is not a domain to which the current host belongs. Mark as
- bad. */
+ }
+ else {
+ /* we did not get a tailmatch and then the attempted set domain
+ is not a domain to which the current host belongs. Mark as
+ bad. */
badcookie = TRUE;
- infof(data, "skipped cookie with bad tailmatch domain: %s\n",
- whatptr);
- }
- }
+ infof(data, "skipped cookie with bad tailmatch domain: %s\n",
+ whatptr);
+ }
+ }
else if(strcasecompare("version", name)) {
- strstore(&co->version, whatptr);
- if(!co->version) {
- badcookie = TRUE;
- break;
- }
- }
+ strstore(&co->version, whatptr);
+ if(!co->version) {
+ badcookie = TRUE;
+ break;
+ }
+ }
else if(strcasecompare("max-age", name)) {
- /* Defined in RFC2109:
-
- Optional. The Max-Age attribute defines the lifetime of the
- cookie, in seconds. The delta-seconds value is a decimal non-
- negative integer. After delta-seconds seconds elapse, the
- client should discard the cookie. A value of zero means the
- cookie should be discarded immediately.
-
- */
- strstore(&co->maxage, whatptr);
- if(!co->maxage) {
- badcookie = TRUE;
- break;
- }
- }
+ /* Defined in RFC2109:
+
+ Optional. The Max-Age attribute defines the lifetime of the
+ cookie, in seconds. The delta-seconds value is a decimal non-
+ negative integer. After delta-seconds seconds elapse, the
+ client should discard the cookie. A value of zero means the
+ cookie should be discarded immediately.
+
+ */
+ strstore(&co->maxage, whatptr);
+ if(!co->maxage) {
+ badcookie = TRUE;
+ break;
+ }
+ }
else if(strcasecompare("expires", name)) {
- strstore(&co->expirestr, whatptr);
- if(!co->expirestr) {
- badcookie = TRUE;
- break;
- }
- }
- /*
- else this is the second (or more) name we don't know
- about! */
- }
- else {
- /* this is an "illegal" <what>=<this> pair */
- }
-
- if(!semiptr || !*semiptr) {
- /* we already know there are no more cookies */
- semiptr = NULL;
- continue;
- }
-
+ strstore(&co->expirestr, whatptr);
+ if(!co->expirestr) {
+ badcookie = TRUE;
+ break;
+ }
+ }
+ /*
+ else this is the second (or more) name we don't know
+ about! */
+ }
+ else {
+ /* this is an "illegal" <what>=<this> pair */
+ }
+
+ if(!semiptr || !*semiptr) {
+ /* we already know there are no more cookies */
+ semiptr = NULL;
+ continue;
+ }
+
ptr = semiptr + 1;
- while(*ptr && ISBLANK(*ptr))
- ptr++;
+ while(*ptr && ISBLANK(*ptr))
+ ptr++;
semiptr = strchr(ptr, ';'); /* now, find the next semicolon */
-
- if(!semiptr && *ptr)
- /* There are no more semicolons, but there's a final name=value pair
- coming up */
+
+ if(!semiptr && *ptr)
+ /* There are no more semicolons, but there's a final name=value pair
+ coming up */
semiptr = strchr(ptr, '\0');
- } while(semiptr);
-
+ } while(semiptr);
+
if(co->maxage) {
CURLofft offt;
offt = curlx_strtoofft((*co->maxage == '\"')?
@@ -728,130 +728,130 @@ Curl_cookie_add(struct Curl_easy *data,
co->expires = 0;
}
- if(!badcookie && !co->domain) {
- if(domain) {
- /* no domain was given in the header line, set the default */
+ if(!badcookie && !co->domain) {
+ if(domain) {
+ /* no domain was given in the header line, set the default */
co->domain = strdup(domain);
- if(!co->domain)
- badcookie = TRUE;
- }
- }
-
- if(!badcookie && !co->path && path) {
- /* No path was given in the header line, set the default.
- Note that the passed-in path to this function MAY have a '?' and
- following part that MUST not be stored as part of the path. */
- char *queryp = strchr(path, '?');
-
- /* queryp is where the interesting part of the path ends, so now we
- want to the find the last */
- char *endslash;
- if(!queryp)
- endslash = strrchr(path, '/');
- else
+ if(!co->domain)
+ badcookie = TRUE;
+ }
+ }
+
+ if(!badcookie && !co->path && path) {
+ /* No path was given in the header line, set the default.
+ Note that the passed-in path to this function MAY have a '?' and
+ following part that MUST not be stored as part of the path. */
+ char *queryp = strchr(path, '?');
+
+ /* queryp is where the interesting part of the path ends, so now we
+ want to the find the last */
+ char *endslash;
+ if(!queryp)
+ endslash = strrchr(path, '/');
+ else
endslash = memrchr(path, '/', (queryp - path));
- if(endslash) {
+ if(endslash) {
size_t pathlen = (endslash-path + 1); /* include end slash */
co->path = malloc(pathlen + 1); /* one extra for the zero byte */
- if(co->path) {
- memcpy(co->path, path, pathlen);
+ if(co->path) {
+ memcpy(co->path, path, pathlen);
co->path[pathlen] = 0; /* null-terminate */
- co->spath = sanitize_cookie_path(co->path);
- if(!co->spath)
- badcookie = TRUE; /* out of memory bad */
- }
- else
- badcookie = TRUE;
- }
- }
-
- if(badcookie || !co->name) {
- /* we didn't get a cookie name or a bad one,
- this is an illegal line, bail out */
- freecookie(co);
- return NULL;
- }
-
- }
- else {
- /* This line is NOT a HTTP header style line, we do offer support for
- reading the odd netscape cookies-file format here */
- char *ptr;
- char *firstptr;
+ co->spath = sanitize_cookie_path(co->path);
+ if(!co->spath)
+ badcookie = TRUE; /* out of memory bad */
+ }
+ else
+ badcookie = TRUE;
+ }
+ }
+
+ if(badcookie || !co->name) {
+ /* we didn't get a cookie name or a bad one,
+ this is an illegal line, bail out */
+ freecookie(co);
+ return NULL;
+ }
+
+ }
+ else {
+ /* This line is NOT a HTTP header style line, we do offer support for
+ reading the odd netscape cookies-file format here */
+ char *ptr;
+ char *firstptr;
char *tok_buf = NULL;
- int fields;
-
- /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
- marked with httpOnly after the domain name are not accessible
- from javascripts, but since curl does not operate at javascript
- level, we include them anyway. In Firefox's cookie files, these
- lines are preceded with #HttpOnly_ and then everything is
- as usual, so we skip 10 characters of the line..
- */
- if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
- lineptr += 10;
- co->httponly = TRUE;
- }
-
- if(lineptr[0]=='#') {
- /* don't even try the comments */
- free(co);
- return NULL;
- }
- /* strip off the possible end-of-line characters */
+ int fields;
+
+ /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
+ marked with httpOnly after the domain name are not accessible
+ from javascripts, but since curl does not operate at javascript
+ level, we include them anyway. In Firefox's cookie files, these
+ lines are preceded with #HttpOnly_ and then everything is
+ as usual, so we skip 10 characters of the line..
+ */
+ if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
+ lineptr += 10;
+ co->httponly = TRUE;
+ }
+
+ if(lineptr[0]=='#') {
+ /* don't even try the comments */
+ free(co);
+ return NULL;
+ }
+ /* strip off the possible end-of-line characters */
ptr = strchr(lineptr, '\r');
- if(ptr)
+ if(ptr)
*ptr = 0; /* clear it */
ptr = strchr(lineptr, '\n');
- if(ptr)
+ if(ptr)
*ptr = 0; /* clear it */
-
+
firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
-
- /* Now loop through the fields and init the struct we already have
- allocated */
+
+ /* Now loop through the fields and init the struct we already have
+ allocated */
for(ptr = firstptr, fields = 0; ptr && !badcookie;
ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
- switch(fields) {
- case 0:
- if(ptr[0]=='.') /* skip preceding dots */
- ptr++;
- co->domain = strdup(ptr);
- if(!co->domain)
- badcookie = TRUE;
- break;
- case 1:
+ switch(fields) {
+ case 0:
+ if(ptr[0]=='.') /* skip preceding dots */
+ ptr++;
+ co->domain = strdup(ptr);
+ if(!co->domain)
+ badcookie = TRUE;
+ break;
+ case 1:
/* flag: A TRUE/FALSE value indicating if all machines within a given
domain can access the variable. Set TRUE when the cookie says
- .domain.com and to false when the domain is complete www.domain.com
- */
+ .domain.com and to false when the domain is complete www.domain.com
+ */
co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
- break;
- case 2:
+ break;
+ case 2:
/* The file format allows the path field to remain not filled in */
- if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
- /* only if the path doesn't look like a boolean option! */
- co->path = strdup(ptr);
- if(!co->path)
- badcookie = TRUE;
- else {
- co->spath = sanitize_cookie_path(co->path);
- if(!co->spath) {
- badcookie = TRUE; /* out of memory bad */
- }
- }
- break;
- }
- /* this doesn't look like a path, make one up! */
- co->path = strdup("/");
- if(!co->path)
- badcookie = TRUE;
- co->spath = strdup("/");
- if(!co->spath)
- badcookie = TRUE;
- fields++; /* add a field and fall down to secure */
- /* FALLTHROUGH */
- case 3:
+ if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
+ /* only if the path doesn't look like a boolean option! */
+ co->path = strdup(ptr);
+ if(!co->path)
+ badcookie = TRUE;
+ else {
+ co->spath = sanitize_cookie_path(co->path);
+ if(!co->spath) {
+ badcookie = TRUE; /* out of memory bad */
+ }
+ }
+ break;
+ }
+ /* this doesn't look like a path, make one up! */
+ co->path = strdup("/");
+ if(!co->path)
+ badcookie = TRUE;
+ co->spath = strdup("/");
+ if(!co->spath)
+ badcookie = TRUE;
+ fields++; /* add a field and fall down to secure */
+ /* FALLTHROUGH */
+ case 3:
co->secure = FALSE;
if(strcasecompare(ptr, "TRUE")) {
if(secure || c->running)
@@ -859,15 +859,15 @@ Curl_cookie_add(struct Curl_easy *data,
else
badcookie = TRUE;
}
- break;
- case 4:
+ break;
+ case 4:
if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
badcookie = TRUE;
- break;
- case 5:
- co->name = strdup(ptr);
- if(!co->name)
- badcookie = TRUE;
+ break;
+ case 5:
+ co->name = strdup(ptr);
+ if(!co->name)
+ badcookie = TRUE;
else {
/* For Netscape file format cookies we check prefix on the name */
if(strncasecompare("__Secure-", co->name, 9))
@@ -875,34 +875,34 @@ Curl_cookie_add(struct Curl_easy *data,
else if(strncasecompare("__Host-", co->name, 7))
co->prefix |= COOKIE_PREFIX__HOST;
}
- break;
- case 6:
- co->value = strdup(ptr);
- if(!co->value)
- badcookie = TRUE;
- break;
- }
- }
- if(6 == fields) {
- /* we got a cookie with blank contents, fix it */
- co->value = strdup("");
- if(!co->value)
- badcookie = TRUE;
- else
- fields++;
- }
-
- if(!badcookie && (7 != fields))
- /* we did not find the sufficient number of fields */
- badcookie = TRUE;
-
- if(badcookie) {
- freecookie(co);
- return NULL;
- }
-
- }
-
+ break;
+ case 6:
+ co->value = strdup(ptr);
+ if(!co->value)
+ badcookie = TRUE;
+ break;
+ }
+ }
+ if(6 == fields) {
+ /* we got a cookie with blank contents, fix it */
+ co->value = strdup("");
+ if(!co->value)
+ badcookie = TRUE;
+ else
+ fields++;
+ }
+
+ if(!badcookie && (7 != fields))
+ /* we did not find the sufficient number of fields */
+ badcookie = TRUE;
+
+ if(badcookie) {
+ freecookie(co);
+ return NULL;
+ }
+
+ }
+
if(co->prefix & COOKIE_PREFIX__SECURE) {
/* The __Secure- prefix only requires that the cookie be set secure */
if(!co->secure) {
@@ -923,24 +923,24 @@ Curl_cookie_add(struct Curl_easy *data,
}
}
- if(!c->running && /* read from a file */
- c->newsession && /* clean session cookies */
- !co->expires) { /* this is a session cookie since it doesn't expire! */
- freecookie(co);
- return NULL;
- }
-
- co->livecookie = c->running;
+ if(!c->running && /* read from a file */
+ c->newsession && /* clean session cookies */
+ !co->expires) { /* this is a session cookie since it doesn't expire! */
+ freecookie(co);
+ return NULL;
+ }
+
+ co->livecookie = c->running;
co->creationtime = ++c->lastct;
-
- /* now, we have parsed the incoming line, we must now check if this
+
+ /* now, we have parsed the incoming line, we must now check if this
supersedes an already existing cookie, which it may if the previous have
- the same domain and path as this */
-
- /* at first, remove expired cookies */
+ the same domain and path as this */
+
+ /* at first, remove expired cookies */
if(!noexpire)
remove_expired(c);
-
+
#ifdef USE_LIBPSL
/* Check if the domain is a Public Suffix and if yes, ignore the cookie. */
if(domain && co->domain && !isip(co->domain)) {
@@ -965,24 +965,24 @@ Curl_cookie_add(struct Curl_easy *data,
myhash = cookiehash(co->domain);
clist = c->cookies[myhash];
- replace_old = FALSE;
- while(clist) {
+ replace_old = FALSE;
+ while(clist) {
if(strcasecompare(clist->name, co->name)) {
- /* the names are identical */
-
- if(clist->domain && co->domain) {
+ /* the names are identical */
+
+ if(clist->domain && co->domain) {
if(strcasecompare(clist->domain, co->domain) &&
(clist->tailmatch == co->tailmatch))
- /* The domains are identical */
+ /* The domains are identical */
replace_old = TRUE;
- }
- else if(!clist->domain && !co->domain)
- replace_old = TRUE;
-
- if(replace_old) {
- /* the domains were identical */
-
- if(clist->spath && co->spath) {
+ }
+ else if(!clist->domain && !co->domain)
+ replace_old = TRUE;
+
+ if(replace_old) {
+ /* the domains were identical */
+
+ if(clist->spath && co->spath) {
if(clist->secure && !co->secure && !secure) {
size_t cllen;
const char *sep;
@@ -1007,36 +1007,36 @@ Curl_cookie_add(struct Curl_easy *data,
}
}
else if(strcasecompare(clist->spath, co->spath))
- replace_old = TRUE;
- else
- replace_old = FALSE;
- }
- else if(!clist->spath && !co->spath)
- replace_old = TRUE;
- else
- replace_old = FALSE;
-
- }
-
- if(replace_old && !co->livecookie && clist->livecookie) {
- /* Both cookies matched fine, except that the already present
- cookie is "live", which means it was set from a header, while
- the new one isn't "live" and thus only read from a file. We let
- live cookies stay alive */
-
- /* Free the newcomer and get out of here! */
- freecookie(co);
- return NULL;
- }
-
- if(replace_old) {
- co->next = clist->next; /* get the next-pointer first */
-
+ replace_old = TRUE;
+ else
+ replace_old = FALSE;
+ }
+ else if(!clist->spath && !co->spath)
+ replace_old = TRUE;
+ else
+ replace_old = FALSE;
+
+ }
+
+ if(replace_old && !co->livecookie && clist->livecookie) {
+ /* Both cookies matched fine, except that the already present
+ cookie is "live", which means it was set from a header, while
+ the new one isn't "live" and thus only read from a file. We let
+ live cookies stay alive */
+
+ /* Free the newcomer and get out of here! */
+ freecookie(co);
+ return NULL;
+ }
+
+ if(replace_old) {
+ co->next = clist->next; /* get the next-pointer first */
+
/* when replacing, creationtime is kept from old */
co->creationtime = clist->creationtime;
- /* then free all the old pointers */
- free(clist->name);
+ /* then free all the old pointers */
+ free(clist->name);
free(clist->value);
free(clist->domain);
free(clist->path);
@@ -1044,100 +1044,100 @@ Curl_cookie_add(struct Curl_easy *data,
free(clist->expirestr);
free(clist->version);
free(clist->maxage);
-
- *clist = *co; /* then store all the new data */
-
+
+ *clist = *co; /* then store all the new data */
+
free(co); /* free the newly allocated memory */
- co = clist; /* point to the previous struct instead */
-
- /* We have replaced a cookie, now skip the rest of the list but
- make sure the 'lastc' pointer is properly set */
- do {
- lastc = clist;
- clist = clist->next;
- } while(clist);
- break;
- }
- }
- lastc = clist;
- clist = clist->next;
- }
-
- if(c->running)
- /* Only show this when NOT reading the cookies from a file */
- infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
+ co = clist; /* point to the previous struct instead */
+
+ /* We have replaced a cookie, now skip the rest of the list but
+ make sure the 'lastc' pointer is properly set */
+ do {
+ lastc = clist;
+ clist = clist->next;
+ } while(clist);
+ break;
+ }
+ }
+ lastc = clist;
+ clist = clist->next;
+ }
+
+ if(c->running)
+ /* Only show this when NOT reading the cookies from a file */
+ infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
"expire %" CURL_FORMAT_CURL_OFF_T "\n",
- replace_old?"Replaced":"Added", co->name, co->value,
- co->domain, co->path, co->expires);
-
- if(!replace_old) {
- /* then make the last item point on this new one */
- if(lastc)
- lastc->next = co;
- else
+ replace_old?"Replaced":"Added", co->name, co->value,
+ co->domain, co->path, co->expires);
+
+ if(!replace_old) {
+ /* then make the last item point on this new one */
+ if(lastc)
+ lastc->next = co;
+ else
c->cookies[myhash] = co;
- c->numcookies++; /* one more cookie in the jar */
- }
-
- return co;
-}
-
-
-/*****************************************************************************
- *
- * Curl_cookie_init()
- *
- * Inits a cookie struct to read data from a local file. This is always
- * called before any cookies are set. File may be NULL.
- *
- * If 'newsession' is TRUE, discard all "session cookies" on read from file.
- *
+ c->numcookies++; /* one more cookie in the jar */
+ }
+
+ return co;
+}
+
+
+/*****************************************************************************
+ *
+ * Curl_cookie_init()
+ *
+ * Inits a cookie struct to read data from a local file. This is always
+ * called before any cookies are set. File may be NULL.
+ *
+ * If 'newsession' is TRUE, discard all "session cookies" on read from file.
+ *
* Note that 'data' might be called as NULL pointer.
*
* Returns NULL on out of memory. Invalid cookies are ignored.
- ****************************************************************************/
+ ****************************************************************************/
struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
- const char *file,
- struct CookieInfo *inc,
- bool newsession)
-{
- struct CookieInfo *c;
+ const char *file,
+ struct CookieInfo *inc,
+ bool newsession)
+{
+ struct CookieInfo *c;
FILE *fp = NULL;
bool fromfile = TRUE;
char *line = NULL;
-
- if(NULL == inc) {
- /* we didn't get a struct, create one */
- c = calloc(1, sizeof(struct CookieInfo));
- if(!c)
- return NULL; /* failed to get memory */
- c->filename = strdup(file?file:"none"); /* copy the name just in case */
+
+ if(NULL == inc) {
+ /* we didn't get a struct, create one */
+ c = calloc(1, sizeof(struct CookieInfo));
+ if(!c)
+ return NULL; /* failed to get memory */
+ c->filename = strdup(file?file:"none"); /* copy the name just in case */
if(!c->filename)
goto fail; /* failed to get memory */
- }
- else {
- /* we got an already existing one, use that */
- c = inc;
- }
- c->running = FALSE; /* this is not running, this is init */
-
+ }
+ else {
+ /* we got an already existing one, use that */
+ c = inc;
+ }
+ c->running = FALSE; /* this is not running, this is init */
+
if(file && !strcmp(file, "-")) {
- fp = stdin;
+ fp = stdin;
fromfile = FALSE;
- }
- else if(file && !*file) {
- /* points to a "" string */
- fp = NULL;
- }
- else
+ }
+ else if(file && !*file) {
+ /* points to a "" string */
+ fp = NULL;
+ }
+ else
fp = file?fopen(file, FOPEN_READTEXT):NULL;
-
- c->newsession = newsession; /* new session? */
-
- if(fp) {
- char *lineptr;
- bool headerline;
-
+
+ c->newsession = newsession; /* new session? */
+
+ if(fp) {
+ char *lineptr;
+ bool headerline;
+
line = malloc(MAX_COOKIE_LINE);
if(!line)
goto fail;
@@ -1153,21 +1153,21 @@ struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
}
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
-
+
Curl_cookie_add(data, c, headerline, TRUE, lineptr, NULL, NULL, TRUE);
- }
+ }
free(line); /* free the line buffer */
remove_expired(c); /* run this once, not on every cookie */
- if(fromfile)
- fclose(fp);
- }
-
- c->running = TRUE; /* now, we're running */
+ if(fromfile)
+ fclose(fp);
+ }
+
+ c->running = TRUE; /* now, we're running */
if(data)
data->state.cookie_engine = TRUE;
-
- return c;
+
+ return c;
fail:
free(line);
@@ -1178,40 +1178,40 @@ fail:
if(fromfile && fp)
fclose(fp);
return NULL; /* out of memory */
-}
-
-/* sort this so that the longest path gets before the shorter path */
-static int cookie_sort(const void *p1, const void *p2)
-{
- struct Cookie *c1 = *(struct Cookie **)p1;
- struct Cookie *c2 = *(struct Cookie **)p2;
- size_t l1, l2;
-
- /* 1 - compare cookie path lengths */
- l1 = c1->path ? strlen(c1->path) : 0;
- l2 = c2->path ? strlen(c2->path) : 0;
-
- if(l1 != l2)
- return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
-
- /* 2 - compare cookie domain lengths */
- l1 = c1->domain ? strlen(c1->domain) : 0;
- l2 = c2->domain ? strlen(c2->domain) : 0;
-
- if(l1 != l2)
- return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
-
+}
+
+/* sort this so that the longest path gets before the shorter path */
+static int cookie_sort(const void *p1, const void *p2)
+{
+ struct Cookie *c1 = *(struct Cookie **)p1;
+ struct Cookie *c2 = *(struct Cookie **)p2;
+ size_t l1, l2;
+
+ /* 1 - compare cookie path lengths */
+ l1 = c1->path ? strlen(c1->path) : 0;
+ l2 = c2->path ? strlen(c2->path) : 0;
+
+ if(l1 != l2)
+ return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
+
+ /* 2 - compare cookie domain lengths */
+ l1 = c1->domain ? strlen(c1->domain) : 0;
+ l2 = c2->domain ? strlen(c2->domain) : 0;
+
+ if(l1 != l2)
+ return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
+
/* 3 - compare cookie name lengths */
l1 = c1->name ? strlen(c1->name) : 0;
l2 = c2->name ? strlen(c2->name) : 0;
-
+
if(l1 != l2)
return (l2 > l1) ? 1 : -1;
/* 4 - compare cookie creation time */
return (c2->creationtime > c1->creationtime) ? 1 : -1;
-}
-
+}
+
/* sort cookies only according to creation time */
static int cookie_sort_ct(const void *p1, const void *p2)
{
@@ -1256,173 +1256,173 @@ static struct Cookie *dup_cookie(struct Cookie *src)
return NULL;
}
-/*****************************************************************************
- *
- * Curl_cookie_getlist()
- *
- * For a given host and path, return a linked list of cookies that the
- * client should send to the server if used now. The secure boolean informs
- * the cookie if a secure connection is achieved or not.
- *
- * It shall only return cookies that haven't expired.
- *
- ****************************************************************************/
-
-struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
- const char *host, const char *path,
- bool secure)
-{
- struct Cookie *newco;
- struct Cookie *co;
+/*****************************************************************************
+ *
+ * Curl_cookie_getlist()
+ *
+ * For a given host and path, return a linked list of cookies that the
+ * client should send to the server if used now. The secure boolean informs
+ * the cookie if a secure connection is achieved or not.
+ *
+ * It shall only return cookies that haven't expired.
+ *
+ ****************************************************************************/
+
+struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
+ const char *host, const char *path,
+ bool secure)
+{
+ struct Cookie *newco;
+ struct Cookie *co;
struct Cookie *mainco = NULL;
- size_t matches = 0;
+ size_t matches = 0;
bool is_ip;
const size_t myhash = cookiehash(host);
-
+
if(!c || !c->cookies[myhash])
- return NULL; /* no cookie struct or no cookies in the struct */
-
- /* at first, remove expired cookies */
- remove_expired(c);
-
+ return NULL; /* no cookie struct or no cookies in the struct */
+
+ /* at first, remove expired cookies */
+ remove_expired(c);
+
/* check if host is an IP(v4|v6) address */
is_ip = isip(host);
-
+
co = c->cookies[myhash];
- while(co) {
+ while(co) {
/* if the cookie requires we're secure we must only continue if we are! */
if(co->secure?secure:TRUE) {
-
- /* now check if the domain is correct */
- if(!co->domain ||
+
+ /* now check if the domain is correct */
+ if(!co->domain ||
(co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
- /* the right part of the host matches the domain stuff in the
- cookie data */
-
- /* now check the left part of the path with the cookies path
- requirement */
- if(!co->spath || pathmatch(co->spath, path) ) {
-
- /* and now, we know this is a match and we should create an
- entry for the return-linked-list */
-
+ /* the right part of the host matches the domain stuff in the
+ cookie data */
+
+ /* now check the left part of the path with the cookies path
+ requirement */
+ if(!co->spath || pathmatch(co->spath, path) ) {
+
+ /* and now, we know this is a match and we should create an
+ entry for the return-linked-list */
+
newco = dup_cookie(co);
- if(newco) {
- /* then modify our next */
- newco->next = mainco;
-
- /* point the main to us */
- mainco = newco;
-
- matches++;
- }
+ if(newco) {
+ /* then modify our next */
+ newco->next = mainco;
+
+ /* point the main to us */
+ mainco = newco;
+
+ matches++;
+ }
else
goto fail;
- }
- }
- }
- co = co->next;
- }
-
- if(matches) {
- /* Now we need to make sure that if there is a name appearing more than
- once, the longest specified path version comes first. To make this
- the swiftest way, we just sort them all based on path length. */
- struct Cookie **array;
- size_t i;
-
- /* alloc an array and store all cookie pointers */
- array = malloc(sizeof(struct Cookie *) * matches);
- if(!array)
- goto fail;
-
- co = mainco;
-
+ }
+ }
+ }
+ co = co->next;
+ }
+
+ if(matches) {
+ /* Now we need to make sure that if there is a name appearing more than
+ once, the longest specified path version comes first. To make this
+ the swiftest way, we just sort them all based on path length. */
+ struct Cookie **array;
+ size_t i;
+
+ /* alloc an array and store all cookie pointers */
+ array = malloc(sizeof(struct Cookie *) * matches);
+ if(!array)
+ goto fail;
+
+ co = mainco;
+
for(i = 0; co; co = co->next)
- array[i++] = co;
-
- /* now sort the cookie pointers in path length order */
- qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
-
- /* remake the linked list order according to the new order */
-
- mainco = array[0]; /* start here */
+ array[i++] = co;
+
+ /* now sort the cookie pointers in path length order */
+ qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
+
+ /* remake the linked list order according to the new order */
+
+ mainco = array[0]; /* start here */
for(i = 0; i<matches-1; i++)
array[i]->next = array[i + 1];
- array[matches-1]->next = NULL; /* terminate the list */
-
- free(array); /* remove the temporary data again */
- }
-
- return mainco; /* return the new list */
+ array[matches-1]->next = NULL; /* terminate the list */
+
+ free(array); /* remove the temporary data again */
+ }
+
+ return mainco; /* return the new list */
fail:
/* failure, clear up the allocated chain and return NULL */
Curl_cookie_freelist(mainco);
return NULL;
-}
-
-/*****************************************************************************
- *
- * Curl_cookie_clearall()
- *
- * Clear all existing cookies and reset the counter.
- *
- ****************************************************************************/
-void Curl_cookie_clearall(struct CookieInfo *cookies)
-{
- if(cookies) {
+}
+
+/*****************************************************************************
+ *
+ * Curl_cookie_clearall()
+ *
+ * Clear all existing cookies and reset the counter.
+ *
+ ****************************************************************************/
+void Curl_cookie_clearall(struct CookieInfo *cookies)
+{
+ if(cookies) {
unsigned int i;
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
Curl_cookie_freelist(cookies->cookies[i]);
cookies->cookies[i] = NULL;
}
- cookies->numcookies = 0;
- }
-}
-
-/*****************************************************************************
- *
- * Curl_cookie_freelist()
- *
- * Free a list of cookies previously returned by Curl_cookie_getlist();
- *
- ****************************************************************************/
-
+ cookies->numcookies = 0;
+ }
+}
+
+/*****************************************************************************
+ *
+ * Curl_cookie_freelist()
+ *
+ * Free a list of cookies previously returned by Curl_cookie_getlist();
+ *
+ ****************************************************************************/
+
void Curl_cookie_freelist(struct Cookie *co)
-{
- struct Cookie *next;
+{
+ struct Cookie *next;
while(co) {
next = co->next;
freecookie(co);
co = next;
- }
-}
-
-
-/*****************************************************************************
- *
- * Curl_cookie_clearsess()
- *
- * Free all session cookies in the cookies list.
- *
- ****************************************************************************/
-void Curl_cookie_clearsess(struct CookieInfo *cookies)
-{
- struct Cookie *first, *curr, *next, *prev = NULL;
+ }
+}
+
+
+/*****************************************************************************
+ *
+ * Curl_cookie_clearsess()
+ *
+ * Free all session cookies in the cookies list.
+ *
+ ****************************************************************************/
+void Curl_cookie_clearsess(struct CookieInfo *cookies)
+{
+ struct Cookie *first, *curr, *next, *prev = NULL;
unsigned int i;
-
+
if(!cookies)
- return;
-
+ return;
+
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
if(!cookies->cookies[i])
continue;
-
+
first = curr = prev = cookies->cookies[i];
-
+
for(; curr; curr = next) {
next = curr->next;
if(!curr->expires) {
@@ -1437,93 +1437,93 @@ void Curl_cookie_clearsess(struct CookieInfo *cookies)
freecookie(curr);
cookies->numcookies--;
}
- else
+ else
prev = curr;
}
-
+
cookies->cookies[i] = first;
- }
-}
-
-
-/*****************************************************************************
- *
- * Curl_cookie_cleanup()
- *
+ }
+}
+
+
+/*****************************************************************************
+ *
+ * Curl_cookie_cleanup()
+ *
* Free a "cookie object" previous created with Curl_cookie_init().
- *
- ****************************************************************************/
-void Curl_cookie_cleanup(struct CookieInfo *c)
-{
- if(c) {
+ *
+ ****************************************************************************/
+void Curl_cookie_cleanup(struct CookieInfo *c)
+{
+ if(c) {
unsigned int i;
free(c->filename);
for(i = 0; i < COOKIE_HASH_SIZE; i++)
Curl_cookie_freelist(c->cookies[i]);
- free(c); /* free the base struct as well */
- }
-}
-
-/* get_netscape_format()
- *
- * Formats a string for Netscape output file, w/o a newline at the end.
- *
- * Function returns a char * to a formatted line. Has to be free()d
-*/
-static char *get_netscape_format(const struct Cookie *co)
-{
- return aprintf(
- "%s" /* httponly preamble */
- "%s%s\t" /* domain */
- "%s\t" /* tailmatch */
- "%s\t" /* path */
- "%s\t" /* secure */
+ free(c); /* free the base struct as well */
+ }
+}
+
+/* get_netscape_format()
+ *
+ * Formats a string for Netscape output file, w/o a newline at the end.
+ *
+ * Function returns a char * to a formatted line. Has to be free()d
+*/
+static char *get_netscape_format(const struct Cookie *co)
+{
+ return aprintf(
+ "%s" /* httponly preamble */
+ "%s%s\t" /* domain */
+ "%s\t" /* tailmatch */
+ "%s\t" /* path */
+ "%s\t" /* secure */
"%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
- "%s\t" /* name */
- "%s", /* value */
- co->httponly?"#HttpOnly_":"",
- /* Make sure all domains are prefixed with a dot if they allow
- tailmatching. This is Mozilla-style. */
- (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
- co->domain?co->domain:"unknown",
- co->tailmatch?"TRUE":"FALSE",
- co->path?co->path:"/",
- co->secure?"TRUE":"FALSE",
- co->expires,
- co->name,
- co->value?co->value:"");
-}
-
-/*
- * cookie_output()
- *
- * Writes all internally known cookies to the specified file. Specify
- * "-" as file name to write to stdout.
- *
- * The function returns non-zero on write failure.
- */
+ "%s\t" /* name */
+ "%s", /* value */
+ co->httponly?"#HttpOnly_":"",
+ /* Make sure all domains are prefixed with a dot if they allow
+ tailmatching. This is Mozilla-style. */
+ (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
+ co->domain?co->domain:"unknown",
+ co->tailmatch?"TRUE":"FALSE",
+ co->path?co->path:"/",
+ co->secure?"TRUE":"FALSE",
+ co->expires,
+ co->name,
+ co->value?co->value:"");
+}
+
+/*
+ * cookie_output()
+ *
+ * Writes all internally known cookies to the specified file. Specify
+ * "-" as file name to write to stdout.
+ *
+ * The function returns non-zero on write failure.
+ */
static int cookie_output(struct Curl_easy *data,
struct CookieInfo *c, const char *filename)
-{
- struct Cookie *co;
+{
+ struct Cookie *co;
FILE *out = NULL;
bool use_stdout = FALSE;
char *tempstore = NULL;
bool error = false;
-
+
if(!c)
/* no cookie engine alive */
return 0;
- /* at first, remove expired cookies */
- remove_expired(c);
-
+ /* at first, remove expired cookies */
+ remove_expired(c);
+
if(!strcmp("-", filename)) {
- /* use stdout */
- out = stdout;
+ /* use stdout */
+ out = stdout;
use_stdout = TRUE;
- }
- else {
+ }
+ else {
unsigned char randsuffix[9];
if(Curl_rand_hex(data, randsuffix, sizeof(randsuffix)))
@@ -1536,13 +1536,13 @@ static int cookie_output(struct Curl_easy *data,
out = fopen(tempstore, FOPEN_WRITETEXT);
if(!out)
goto error;
- }
-
+ }
+
fputs("# Netscape HTTP Cookie File\n"
"# https://curl.se/docs/http-cookies.html\n"
"# This file was generated by libcurl! Edit at your own risk.\n\n",
out);
-
+
if(c->numcookies) {
unsigned int i;
size_t nvalid = 0;
@@ -1552,7 +1552,7 @@ static int cookie_output(struct Curl_easy *data,
if(!array) {
goto error;
}
-
+
/* only sort the cookies with a domain property */
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
for(co = c->cookies[i]; co; co = co->next) {
@@ -1566,27 +1566,27 @@ static int cookie_output(struct Curl_easy *data,
for(i = 0; i < nvalid; i++) {
char *format_ptr = get_netscape_format(array[i]);
- if(format_ptr == NULL) {
- fprintf(out, "#\n# Fatal libcurl error\n");
+ if(format_ptr == NULL) {
+ fprintf(out, "#\n# Fatal libcurl error\n");
free(array);
goto error;
- }
- fprintf(out, "%s\n", format_ptr);
- free(format_ptr);
- }
+ }
+ fprintf(out, "%s\n", format_ptr);
+ free(format_ptr);
+ }
free(array);
- }
+ }
if(!use_stdout) {
- fclose(out);
+ fclose(out);
out = NULL;
if(Curl_rename(tempstore, filename)) {
unlink(tempstore);
goto error;
}
}
-
+
goto cleanup;
error:
error = true;
@@ -1595,20 +1595,20 @@ cleanup:
fclose(out);
free(tempstore);
return error ? 1 : 0;
-}
-
+}
+
static struct curl_slist *cookie_list(struct Curl_easy *data)
-{
- struct curl_slist *list = NULL;
- struct curl_slist *beg;
- struct Cookie *c;
- char *line;
+{
+ struct curl_slist *list = NULL;
+ struct curl_slist *beg;
+ struct Cookie *c;
+ char *line;
unsigned int i;
-
- if((data->cookies == NULL) ||
- (data->cookies->numcookies == 0))
- return NULL;
-
+
+ if((data->cookies == NULL) ||
+ (data->cookies->numcookies == 0))
+ return NULL;
+
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
for(c = data->cookies->cookies[i]; c; c = c->next) {
if(!c->domain)
@@ -1625,14 +1625,14 @@ static struct curl_slist *cookie_list(struct Curl_easy *data)
return NULL;
}
list = beg;
- }
- }
-
- return list;
-}
-
+ }
+ }
+
+ return list;
+}
+
struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
-{
+{
struct curl_slist *list;
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
list = cookie_list(data);
@@ -1642,36 +1642,36 @@ struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
{
- if(data->set.str[STRING_COOKIEJAR]) {
- if(data->change.cookielist) {
- /* If there is a list of cookie files to read, do it first so that
- we have all the told files read before we write the new jar.
- Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
- Curl_cookie_loadfiles(data);
- }
-
- Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
-
- /* if we have a destination file for all the cookies to get dumped to */
+ if(data->set.str[STRING_COOKIEJAR]) {
+ if(data->change.cookielist) {
+ /* If there is a list of cookie files to read, do it first so that
+ we have all the told files read before we write the new jar.
+ Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
+ Curl_cookie_loadfiles(data);
+ }
+
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+
+ /* if we have a destination file for all the cookies to get dumped to */
if(cookie_output(data, data->cookies, data->set.str[STRING_COOKIEJAR]))
- infof(data, "WARNING: failed to save cookies in %s\n",
- data->set.str[STRING_COOKIEJAR]);
- }
- else {
- if(cleanup && data->change.cookielist) {
- /* since nothing is written, we can just free the list of cookie file
- names */
- curl_slist_free_all(data->change.cookielist); /* clean up list */
- data->change.cookielist = NULL;
- }
- Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
- }
-
- if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
- Curl_cookie_cleanup(data->cookies);
+ infof(data, "WARNING: failed to save cookies in %s\n",
+ data->set.str[STRING_COOKIEJAR]);
+ }
+ else {
+ if(cleanup && data->change.cookielist) {
+ /* since nothing is written, we can just free the list of cookie file
+ names */
+ curl_slist_free_all(data->change.cookielist); /* clean up list */
+ data->change.cookielist = NULL;
+ }
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+ }
+
+ if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
+ Curl_cookie_cleanup(data->cookies);
data->cookies = NULL;
- }
- Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
-}
-
-#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */
+ }
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+}
+
+#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */
diff --git a/contrib/libs/curl/lib/cookie.h b/contrib/libs/curl/lib/cookie.h
index ff14d40929..066396f0d5 100644
--- a/contrib/libs/curl/lib/cookie.h
+++ b/contrib/libs/curl/lib/cookie.h
@@ -1,52 +1,52 @@
-#ifndef HEADER_CURL_COOKIE_H
-#define HEADER_CURL_COOKIE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_COOKIE_H
+#define HEADER_CURL_COOKIE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
-struct Cookie {
- struct Cookie *next; /* next in the chain */
- char *name; /* <this> = value */
- char *value; /* name = <this> */
- char *path; /* path = <this> which is in Set-Cookie: */
- char *spath; /* sanitized cookie path */
- char *domain; /* domain = <this> */
- curl_off_t expires; /* expires = <this> */
- char *expirestr; /* the plain text version */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+struct Cookie {
+ struct Cookie *next; /* next in the chain */
+ char *name; /* <this> = value */
+ char *value; /* name = <this> */
+ char *path; /* path = <this> which is in Set-Cookie: */
+ char *spath; /* sanitized cookie path */
+ char *domain; /* domain = <this> */
+ curl_off_t expires; /* expires = <this> */
+ char *expirestr; /* the plain text version */
bool tailmatch; /* whether we do tail-matching of the domain name */
-
- /* RFC 2109 keywords. Version=1 means 2109-compliant cookie sending */
- char *version; /* Version = <value> */
- char *maxage; /* Max-Age = <value> */
-
- bool secure; /* whether the 'secure' keyword was used */
- bool livecookie; /* updated from a server, not a stored file */
- bool httponly; /* true if the httponly directive is present */
+
+ /* RFC 2109 keywords. Version=1 means 2109-compliant cookie sending */
+ char *version; /* Version = <value> */
+ char *maxage; /* Max-Age = <value> */
+
+ bool secure; /* whether the 'secure' keyword was used */
+ bool livecookie; /* updated from a server, not a stored file */
+ bool httponly; /* true if the httponly directive is present */
int creationtime; /* time when the cookie was written */
unsigned char prefix; /* bitmap fields indicating which prefix are set */
-};
-
+};
+
/*
* Available cookie prefixes, as defined in
* draft-ietf-httpbis-rfc6265bis-02
@@ -56,65 +56,65 @@ struct Cookie {
#define COOKIE_HASH_SIZE 256
-struct CookieInfo {
- /* linked list of cookies we know of */
+struct CookieInfo {
+ /* linked list of cookies we know of */
struct Cookie *cookies[COOKIE_HASH_SIZE];
-
- char *filename; /* file we read from/write to */
- bool running; /* state info, for cookie adding information */
- long numcookies; /* number of cookies in the "jar" */
- bool newsession; /* new session, discard session cookies on load */
+
+ char *filename; /* file we read from/write to */
+ bool running; /* state info, for cookie adding information */
+ long numcookies; /* number of cookies in the "jar" */
+ bool newsession; /* new session, discard session cookies on load */
int lastct; /* last creation-time used in the jar */
-};
-
-/* This is the maximum line length we accept for a cookie line. RFC 2109
- section 6.3 says:
-
- "at least 4096 bytes per cookie (as measured by the size of the characters
- that comprise the cookie non-terminal in the syntax description of the
- Set-Cookie header)"
-
+};
+
+/* This is the maximum line length we accept for a cookie line. RFC 2109
+ section 6.3 says:
+
+ "at least 4096 bytes per cookie (as measured by the size of the characters
+ that comprise the cookie non-terminal in the syntax description of the
+ Set-Cookie header)"
+
We allow max 5000 bytes cookie header. Max 4095 bytes length per cookie
name and value. Name + value may not exceed 4096 bytes.
-*/
-#define MAX_COOKIE_LINE 5000
-
+*/
+#define MAX_COOKIE_LINE 5000
+
/* This is the maximum length of a cookie name or content we deal with: */
#define MAX_NAME 4096
#define MAX_NAME_TXT "4095"
-
+
struct Curl_easy;
-/*
- * Add a cookie to the internal list of cookies. The domain and path arguments
- * are only used if the header boolean is TRUE.
- */
-
+/*
+ * Add a cookie to the internal list of cookies. The domain and path arguments
+ * are only used if the header boolean is TRUE.
+ */
+
struct Cookie *Curl_cookie_add(struct Curl_easy *data,
struct CookieInfo *, bool header, bool noexpiry,
char *lineptr,
const char *domain, const char *path,
bool secure);
-
-struct Cookie *Curl_cookie_getlist(struct CookieInfo *, const char *,
- const char *, bool);
+
+struct Cookie *Curl_cookie_getlist(struct CookieInfo *, const char *,
+ const char *, bool);
void Curl_cookie_freelist(struct Cookie *cookies);
-void Curl_cookie_clearall(struct CookieInfo *cookies);
-void Curl_cookie_clearsess(struct CookieInfo *cookies);
-
-#if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_COOKIES)
-#define Curl_cookie_list(x) NULL
-#define Curl_cookie_loadfiles(x) Curl_nop_stmt
-#define Curl_cookie_init(x,y,z,w) NULL
-#define Curl_cookie_cleanup(x) Curl_nop_stmt
-#define Curl_flush_cookies(x,y) Curl_nop_stmt
-#else
+void Curl_cookie_clearall(struct CookieInfo *cookies);
+void Curl_cookie_clearsess(struct CookieInfo *cookies);
+
+#if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_COOKIES)
+#define Curl_cookie_list(x) NULL
+#define Curl_cookie_loadfiles(x) Curl_nop_stmt
+#define Curl_cookie_init(x,y,z,w) NULL
+#define Curl_cookie_cleanup(x) Curl_nop_stmt
+#define Curl_flush_cookies(x,y) Curl_nop_stmt
+#else
void Curl_flush_cookies(struct Curl_easy *data, bool cleanup);
-void Curl_cookie_cleanup(struct CookieInfo *);
+void Curl_cookie_cleanup(struct CookieInfo *);
struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
- const char *, struct CookieInfo *, bool);
+ const char *, struct CookieInfo *, bool);
struct curl_slist *Curl_cookie_list(struct Curl_easy *data);
void Curl_cookie_loadfiles(struct Curl_easy *data);
-#endif
-
-#endif /* HEADER_CURL_COOKIE_H */
+#endif
+
+#endif /* HEADER_CURL_COOKIE_H */
diff --git a/contrib/libs/curl/lib/curl_addrinfo.c b/contrib/libs/curl/lib/curl_addrinfo.c
index 3bdb86f568..9007259d4c 100644
--- a/contrib/libs/curl/lib/curl_addrinfo.c
+++ b/contrib/libs/curl/lib/curl_addrinfo.c
@@ -1,466 +1,466 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
-#ifdef HAVE_NETINET_IN_H
-# include <netinet/in.h>
-#endif
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#ifdef HAVE_NETINET_IN_H
+# include <netinet/in.h>
+#endif
#ifdef HAVE_NETINET_IN6_H
# error #include <netinet/in6.h>
#endif
-#ifdef HAVE_NETDB_H
-# include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-# include <arpa/inet.h>
-#endif
+#ifdef HAVE_NETDB_H
+# include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+# include <arpa/inet.h>
+#endif
#ifdef HAVE_SYS_UN_H
# include <sys/un.h>
#endif
-
-#ifdef __VMS
-# include <in.h>
-# include <inet.h>
-#endif
-
-#if defined(NETWARE) && defined(__NOVELL_LIBC__)
-# undef in_addr_t
-# define in_addr_t unsigned long
-#endif
-
+
+#ifdef __VMS
+# include <in.h>
+# include <inet.h>
+#endif
+
+#if defined(NETWARE) && defined(__NOVELL_LIBC__)
+# undef in_addr_t
+# define in_addr_t unsigned long
+#endif
+
#include <stddef.h>
-#include "curl_addrinfo.h"
-#include "inet_pton.h"
-#include "warnless.h"
+#include "curl_addrinfo.h"
+#include "inet_pton.h"
+#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
- * Curl_freeaddrinfo()
- *
- * This is used to free a linked list of Curl_addrinfo structs along
- * with all its associated allocated storage. This function should be
- * called once for each successful call to Curl_getaddrinfo_ex() or to
- * any function call which actually allocates a Curl_addrinfo struct.
- */
-
-#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
- defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__)
- /* workaround icc 9.1 optimizer issue */
-# define vqualifier volatile
-#else
-# define vqualifier
-#endif
-
-void
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/*
+ * Curl_freeaddrinfo()
+ *
+ * This is used to free a linked list of Curl_addrinfo structs along
+ * with all its associated allocated storage. This function should be
+ * called once for each successful call to Curl_getaddrinfo_ex() or to
+ * any function call which actually allocates a Curl_addrinfo struct.
+ */
+
+#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
+ defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__)
+ /* workaround icc 9.1 optimizer issue */
+# define vqualifier volatile
+#else
+# define vqualifier
+#endif
+
+void
Curl_freeaddrinfo(struct Curl_addrinfo *cahead)
-{
+{
struct Curl_addrinfo *vqualifier canext;
struct Curl_addrinfo *ca;
-
+
for(ca = cahead; ca; ca = canext) {
- canext = ca->ai_next;
- free(ca);
- }
-}
-
-
-#ifdef HAVE_GETADDRINFO
-/*
- * Curl_getaddrinfo_ex()
- *
- * This is a wrapper function around system's getaddrinfo(), with
- * the only difference that instead of returning a linked list of
- * addrinfo structs this one returns a linked list of Curl_addrinfo
- * ones. The memory allocated by this function *MUST* be free'd with
- * Curl_freeaddrinfo(). For each successful call to this function
- * there must be an associated call later to Curl_freeaddrinfo().
- *
- * There should be no single call to system's getaddrinfo() in the
- * whole library, any such call should be 'routed' through this one.
- */
-
-int
-Curl_getaddrinfo_ex(const char *nodename,
- const char *servname,
- const struct addrinfo *hints,
+ canext = ca->ai_next;
+ free(ca);
+ }
+}
+
+
+#ifdef HAVE_GETADDRINFO
+/*
+ * Curl_getaddrinfo_ex()
+ *
+ * This is a wrapper function around system's getaddrinfo(), with
+ * the only difference that instead of returning a linked list of
+ * addrinfo structs this one returns a linked list of Curl_addrinfo
+ * ones. The memory allocated by this function *MUST* be free'd with
+ * Curl_freeaddrinfo(). For each successful call to this function
+ * there must be an associated call later to Curl_freeaddrinfo().
+ *
+ * There should be no single call to system's getaddrinfo() in the
+ * whole library, any such call should be 'routed' through this one.
+ */
+
+int
+Curl_getaddrinfo_ex(const char *nodename,
+ const char *servname,
+ const struct addrinfo *hints,
struct Curl_addrinfo **result)
-{
- const struct addrinfo *ai;
- struct addrinfo *aihead;
+{
+ const struct addrinfo *ai;
+ struct addrinfo *aihead;
struct Curl_addrinfo *cafirst = NULL;
struct Curl_addrinfo *calast = NULL;
struct Curl_addrinfo *ca;
- size_t ss_size;
- int error;
-
- *result = NULL; /* assume failure */
-
- error = getaddrinfo(nodename, servname, hints, &aihead);
- if(error)
- return error;
-
- /* traverse the addrinfo list */
-
- for(ai = aihead; ai != NULL; ai = ai->ai_next) {
+ size_t ss_size;
+ int error;
+
+ *result = NULL; /* assume failure */
+
+ error = getaddrinfo(nodename, servname, hints, &aihead);
+ if(error)
+ return error;
+
+ /* traverse the addrinfo list */
+
+ for(ai = aihead; ai != NULL; ai = ai->ai_next) {
size_t namelen = ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0;
- /* ignore elements with unsupported address family, */
- /* settle family-specific sockaddr structure size. */
- if(ai->ai_family == AF_INET)
- ss_size = sizeof(struct sockaddr_in);
-#ifdef ENABLE_IPV6
- else if(ai->ai_family == AF_INET6)
- ss_size = sizeof(struct sockaddr_in6);
-#endif
- else
- continue;
-
- /* ignore elements without required address info */
- if((ai->ai_addr == NULL) || !(ai->ai_addrlen > 0))
- continue;
-
- /* ignore elements with bogus address size */
- if((size_t)ai->ai_addrlen < ss_size)
- continue;
-
+ /* ignore elements with unsupported address family, */
+ /* settle family-specific sockaddr structure size. */
+ if(ai->ai_family == AF_INET)
+ ss_size = sizeof(struct sockaddr_in);
+#ifdef ENABLE_IPV6
+ else if(ai->ai_family == AF_INET6)
+ ss_size = sizeof(struct sockaddr_in6);
+#endif
+ else
+ continue;
+
+ /* ignore elements without required address info */
+ if((ai->ai_addr == NULL) || !(ai->ai_addrlen > 0))
+ continue;
+
+ /* ignore elements with bogus address size */
+ if((size_t)ai->ai_addrlen < ss_size)
+ continue;
+
ca = malloc(sizeof(struct Curl_addrinfo) + ss_size + namelen);
if(!ca) {
- error = EAI_MEMORY;
- break;
- }
-
- /* copy each structure member individually, member ordering, */
- /* size, or padding might be different for each platform. */
-
- ca->ai_flags = ai->ai_flags;
- ca->ai_family = ai->ai_family;
- ca->ai_socktype = ai->ai_socktype;
- ca->ai_protocol = ai->ai_protocol;
- ca->ai_addrlen = (curl_socklen_t)ss_size;
- ca->ai_addr = NULL;
- ca->ai_canonname = NULL;
- ca->ai_next = NULL;
-
+ error = EAI_MEMORY;
+ break;
+ }
+
+ /* copy each structure member individually, member ordering, */
+ /* size, or padding might be different for each platform. */
+
+ ca->ai_flags = ai->ai_flags;
+ ca->ai_family = ai->ai_family;
+ ca->ai_socktype = ai->ai_socktype;
+ ca->ai_protocol = ai->ai_protocol;
+ ca->ai_addrlen = (curl_socklen_t)ss_size;
+ ca->ai_addr = NULL;
+ ca->ai_canonname = NULL;
+ ca->ai_next = NULL;
+
ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
- memcpy(ca->ai_addr, ai->ai_addr, ss_size);
-
+ memcpy(ca->ai_addr, ai->ai_addr, ss_size);
+
if(namelen) {
ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size);
memcpy(ca->ai_canonname, ai->ai_canonname, namelen);
- }
-
- /* if the return list is empty, this becomes the first element */
- if(!cafirst)
- cafirst = ca;
-
- /* add this element last in the return list */
- if(calast)
- calast->ai_next = ca;
- calast = ca;
-
- }
-
- /* destroy the addrinfo list */
- if(aihead)
- freeaddrinfo(aihead);
-
- /* if we failed, also destroy the Curl_addrinfo list */
- if(error) {
- Curl_freeaddrinfo(cafirst);
- cafirst = NULL;
- }
- else if(!cafirst) {
-#ifdef EAI_NONAME
- /* rfc3493 conformant */
- error = EAI_NONAME;
-#else
- /* rfc3493 obsoleted */
- error = EAI_NODATA;
-#endif
-#ifdef USE_WINSOCK
- SET_SOCKERRNO(error);
-#endif
- }
-
- *result = cafirst;
-
- /* This is not a CURLcode */
- return error;
-}
-#endif /* HAVE_GETADDRINFO */
-
-
-/*
- * Curl_he2ai()
- *
- * This function returns a pointer to the first element of a newly allocated
- * Curl_addrinfo struct linked list filled with the data of a given hostent.
- * Curl_addrinfo is meant to work like the addrinfo struct does for a IPv6
- * stack, but usable also for IPv4, all hosts and environments.
- *
- * The memory allocated by this function *MUST* be free'd later on calling
- * Curl_freeaddrinfo(). For each successful call to this function there
- * must be an associated call later to Curl_freeaddrinfo().
- *
- * Curl_addrinfo defined in "lib/curl_addrinfo.h"
- *
- * struct Curl_addrinfo {
- * int ai_flags;
- * int ai_family;
- * int ai_socktype;
- * int ai_protocol;
- * curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo *
- * char *ai_canonname;
- * struct sockaddr *ai_addr;
- * struct Curl_addrinfo *ai_next;
- * };
- *
- * hostent defined in <netdb.h>
- *
- * struct hostent {
- * char *h_name;
- * char **h_aliases;
- * int h_addrtype;
- * int h_length;
- * char **h_addr_list;
- * };
- *
- * for backward compatibility:
- *
- * #define h_addr h_addr_list[0]
- */
-
+ }
+
+ /* if the return list is empty, this becomes the first element */
+ if(!cafirst)
+ cafirst = ca;
+
+ /* add this element last in the return list */
+ if(calast)
+ calast->ai_next = ca;
+ calast = ca;
+
+ }
+
+ /* destroy the addrinfo list */
+ if(aihead)
+ freeaddrinfo(aihead);
+
+ /* if we failed, also destroy the Curl_addrinfo list */
+ if(error) {
+ Curl_freeaddrinfo(cafirst);
+ cafirst = NULL;
+ }
+ else if(!cafirst) {
+#ifdef EAI_NONAME
+ /* rfc3493 conformant */
+ error = EAI_NONAME;
+#else
+ /* rfc3493 obsoleted */
+ error = EAI_NODATA;
+#endif
+#ifdef USE_WINSOCK
+ SET_SOCKERRNO(error);
+#endif
+ }
+
+ *result = cafirst;
+
+ /* This is not a CURLcode */
+ return error;
+}
+#endif /* HAVE_GETADDRINFO */
+
+
+/*
+ * Curl_he2ai()
+ *
+ * This function returns a pointer to the first element of a newly allocated
+ * Curl_addrinfo struct linked list filled with the data of a given hostent.
+ * Curl_addrinfo is meant to work like the addrinfo struct does for a IPv6
+ * stack, but usable also for IPv4, all hosts and environments.
+ *
+ * The memory allocated by this function *MUST* be free'd later on calling
+ * Curl_freeaddrinfo(). For each successful call to this function there
+ * must be an associated call later to Curl_freeaddrinfo().
+ *
+ * Curl_addrinfo defined in "lib/curl_addrinfo.h"
+ *
+ * struct Curl_addrinfo {
+ * int ai_flags;
+ * int ai_family;
+ * int ai_socktype;
+ * int ai_protocol;
+ * curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo *
+ * char *ai_canonname;
+ * struct sockaddr *ai_addr;
+ * struct Curl_addrinfo *ai_next;
+ * };
+ *
+ * hostent defined in <netdb.h>
+ *
+ * struct hostent {
+ * char *h_name;
+ * char **h_aliases;
+ * int h_addrtype;
+ * int h_length;
+ * char **h_addr_list;
+ * };
+ *
+ * for backward compatibility:
+ *
+ * #define h_addr h_addr_list[0]
+ */
+
struct Curl_addrinfo *
-Curl_he2ai(const struct hostent *he, int port)
-{
+Curl_he2ai(const struct hostent *he, int port)
+{
struct Curl_addrinfo *ai;
struct Curl_addrinfo *prevai = NULL;
struct Curl_addrinfo *firstai = NULL;
- struct sockaddr_in *addr;
-#ifdef ENABLE_IPV6
- struct sockaddr_in6 *addr6;
-#endif
- CURLcode result = CURLE_OK;
- int i;
- char *curr;
-
- if(!he)
- /* no input == no output! */
- return NULL;
-
- DEBUGASSERT((he->h_name != NULL) && (he->h_addr_list != NULL));
-
+ struct sockaddr_in *addr;
+#ifdef ENABLE_IPV6
+ struct sockaddr_in6 *addr6;
+#endif
+ CURLcode result = CURLE_OK;
+ int i;
+ char *curr;
+
+ if(!he)
+ /* no input == no output! */
+ return NULL;
+
+ DEBUGASSERT((he->h_name != NULL) && (he->h_addr_list != NULL));
+
for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) {
- size_t ss_size;
+ size_t ss_size;
size_t namelen = strlen(he->h_name) + 1; /* include zero termination */
-#ifdef ENABLE_IPV6
- if(he->h_addrtype == AF_INET6)
+#ifdef ENABLE_IPV6
+ if(he->h_addrtype == AF_INET6)
ss_size = sizeof(struct sockaddr_in6);
- else
-#endif
+ else
+#endif
ss_size = sizeof(struct sockaddr_in);
-
+
/* allocate memory to told the struct, the address and the name */
ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + namelen);
if(!ai) {
- result = CURLE_OUT_OF_MEMORY;
- break;
- }
+ result = CURLE_OUT_OF_MEMORY;
+ break;
+ }
/* put the address after the struct */
ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
/* then put the name after the address */
ai->ai_canonname = (char *)ai->ai_addr + ss_size;
memcpy(ai->ai_canonname, he->h_name, namelen);
-
- if(!firstai)
- /* store the pointer we want to return from this function */
- firstai = ai;
-
- if(prevai)
- /* make the previous entry point to this */
- prevai->ai_next = ai;
-
- ai->ai_family = he->h_addrtype;
-
- /* we return all names as STREAM, so when using this address for TFTP
- the type must be ignored and conn->socktype be used instead! */
- ai->ai_socktype = SOCK_STREAM;
-
- ai->ai_addrlen = (curl_socklen_t)ss_size;
-
- /* leave the rest of the struct filled with zero */
-
+
+ if(!firstai)
+ /* store the pointer we want to return from this function */
+ firstai = ai;
+
+ if(prevai)
+ /* make the previous entry point to this */
+ prevai->ai_next = ai;
+
+ ai->ai_family = he->h_addrtype;
+
+ /* we return all names as STREAM, so when using this address for TFTP
+ the type must be ignored and conn->socktype be used instead! */
+ ai->ai_socktype = SOCK_STREAM;
+
+ ai->ai_addrlen = (curl_socklen_t)ss_size;
+
+ /* leave the rest of the struct filled with zero */
+
switch(ai->ai_family) {
- case AF_INET:
- addr = (void *)ai->ai_addr; /* storage area for this info */
-
- memcpy(&addr->sin_addr, curr, sizeof(struct in_addr));
+ case AF_INET:
+ addr = (void *)ai->ai_addr; /* storage area for this info */
+
+ memcpy(&addr->sin_addr, curr, sizeof(struct in_addr));
addr->sin_family = (CURL_SA_FAMILY_T)(he->h_addrtype);
- addr->sin_port = htons((unsigned short)port);
- break;
-
-#ifdef ENABLE_IPV6
- case AF_INET6:
- addr6 = (void *)ai->ai_addr; /* storage area for this info */
-
- memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr));
+ addr->sin_port = htons((unsigned short)port);
+ break;
+
+#ifdef ENABLE_IPV6
+ case AF_INET6:
+ addr6 = (void *)ai->ai_addr; /* storage area for this info */
+
+ memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr));
addr6->sin6_family = (CURL_SA_FAMILY_T)(he->h_addrtype);
- addr6->sin6_port = htons((unsigned short)port);
- break;
-#endif
- }
-
- prevai = ai;
- }
-
+ addr6->sin6_port = htons((unsigned short)port);
+ break;
+#endif
+ }
+
+ prevai = ai;
+ }
+
if(result) {
- Curl_freeaddrinfo(firstai);
- firstai = NULL;
- }
-
- return firstai;
-}
-
-
-struct namebuff {
- struct hostent hostentry;
- union {
- struct in_addr ina4;
-#ifdef ENABLE_IPV6
- struct in6_addr ina6;
-#endif
- } addrentry;
- char *h_addr_list[2];
-};
-
-
-/*
- * Curl_ip2addr()
- *
- * This function takes an internet address, in binary form, as input parameter
- * along with its address family and the string version of the address, and it
- * returns a Curl_addrinfo chain filled in correctly with information for the
- * given address/host
- */
-
+ Curl_freeaddrinfo(firstai);
+ firstai = NULL;
+ }
+
+ return firstai;
+}
+
+
+struct namebuff {
+ struct hostent hostentry;
+ union {
+ struct in_addr ina4;
+#ifdef ENABLE_IPV6
+ struct in6_addr ina6;
+#endif
+ } addrentry;
+ char *h_addr_list[2];
+};
+
+
+/*
+ * Curl_ip2addr()
+ *
+ * This function takes an internet address, in binary form, as input parameter
+ * along with its address family and the string version of the address, and it
+ * returns a Curl_addrinfo chain filled in correctly with information for the
+ * given address/host
+ */
+
struct Curl_addrinfo *
-Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port)
-{
+Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port)
+{
struct Curl_addrinfo *ai;
-
-#if defined(__VMS) && \
- defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
-#pragma pointer_size save
-#pragma pointer_size short
-#pragma message disable PTRMISMATCH
-#endif
-
- struct hostent *h;
- struct namebuff *buf;
- char *addrentry;
- char *hoststr;
- size_t addrsize;
-
- DEBUGASSERT(inaddr && hostname);
-
- buf = malloc(sizeof(struct namebuff));
- if(!buf)
- return NULL;
-
- hoststr = strdup(hostname);
- if(!hoststr) {
- free(buf);
- return NULL;
- }
-
- switch(af) {
- case AF_INET:
- addrsize = sizeof(struct in_addr);
- addrentry = (void *)&buf->addrentry.ina4;
- memcpy(addrentry, inaddr, sizeof(struct in_addr));
- break;
-#ifdef ENABLE_IPV6
- case AF_INET6:
- addrsize = sizeof(struct in6_addr);
- addrentry = (void *)&buf->addrentry.ina6;
- memcpy(addrentry, inaddr, sizeof(struct in6_addr));
- break;
-#endif
- default:
- free(hoststr);
- free(buf);
- return NULL;
- }
-
- h = &buf->hostentry;
- h->h_name = hoststr;
- h->h_aliases = NULL;
- h->h_addrtype = (short)af;
- h->h_length = (short)addrsize;
- h->h_addr_list = &buf->h_addr_list[0];
- h->h_addr_list[0] = addrentry;
- h->h_addr_list[1] = NULL; /* terminate list of entries */
-
-#if defined(__VMS) && \
- defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
-#pragma pointer_size restore
-#pragma message enable PTRMISMATCH
-#endif
-
- ai = Curl_he2ai(h, port);
-
- free(hoststr);
- free(buf);
-
- return ai;
-}
-
-/*
- * Given an IPv4 or IPv6 dotted string address, this converts it to a proper
- * allocated Curl_addrinfo struct and returns it.
- */
+
+#if defined(__VMS) && \
+ defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
+#pragma pointer_size save
+#pragma pointer_size short
+#pragma message disable PTRMISMATCH
+#endif
+
+ struct hostent *h;
+ struct namebuff *buf;
+ char *addrentry;
+ char *hoststr;
+ size_t addrsize;
+
+ DEBUGASSERT(inaddr && hostname);
+
+ buf = malloc(sizeof(struct namebuff));
+ if(!buf)
+ return NULL;
+
+ hoststr = strdup(hostname);
+ if(!hoststr) {
+ free(buf);
+ return NULL;
+ }
+
+ switch(af) {
+ case AF_INET:
+ addrsize = sizeof(struct in_addr);
+ addrentry = (void *)&buf->addrentry.ina4;
+ memcpy(addrentry, inaddr, sizeof(struct in_addr));
+ break;
+#ifdef ENABLE_IPV6
+ case AF_INET6:
+ addrsize = sizeof(struct in6_addr);
+ addrentry = (void *)&buf->addrentry.ina6;
+ memcpy(addrentry, inaddr, sizeof(struct in6_addr));
+ break;
+#endif
+ default:
+ free(hoststr);
+ free(buf);
+ return NULL;
+ }
+
+ h = &buf->hostentry;
+ h->h_name = hoststr;
+ h->h_aliases = NULL;
+ h->h_addrtype = (short)af;
+ h->h_length = (short)addrsize;
+ h->h_addr_list = &buf->h_addr_list[0];
+ h->h_addr_list[0] = addrentry;
+ h->h_addr_list[1] = NULL; /* terminate list of entries */
+
+#if defined(__VMS) && \
+ defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
+#pragma pointer_size restore
+#pragma message enable PTRMISMATCH
+#endif
+
+ ai = Curl_he2ai(h, port);
+
+ free(hoststr);
+ free(buf);
+
+ return ai;
+}
+
+/*
+ * Given an IPv4 or IPv6 dotted string address, this converts it to a proper
+ * allocated Curl_addrinfo struct and returns it.
+ */
struct Curl_addrinfo *Curl_str2addr(char *address, int port)
-{
- struct in_addr in;
- if(Curl_inet_pton(AF_INET, address, &in) > 0)
- /* This is a dotted IP address 123.123.123.123-style */
- return Curl_ip2addr(AF_INET, &in, address, port);
-#ifdef ENABLE_IPV6
+{
+ struct in_addr in;
+ if(Curl_inet_pton(AF_INET, address, &in) > 0)
+ /* This is a dotted IP address 123.123.123.123-style */
+ return Curl_ip2addr(AF_INET, &in, address, port);
+#ifdef ENABLE_IPV6
{
- struct in6_addr in6;
- if(Curl_inet_pton(AF_INET6, address, &in6) > 0)
- /* This is a dotted IPv6 address ::1-style */
- return Curl_ip2addr(AF_INET6, &in6, address, port);
- }
-#endif
- return NULL; /* bad input format */
-}
-
+ struct in6_addr in6;
+ if(Curl_inet_pton(AF_INET6, address, &in6) > 0)
+ /* This is a dotted IPv6 address ::1-style */
+ return Curl_ip2addr(AF_INET6, &in6, address, port);
+ }
+#endif
+ return NULL; /* bad input format */
+}
+
#ifdef USE_UNIX_SOCKETS
/**
* Given a path to a Unix domain socket, return a newly allocated Curl_addrinfo
@@ -509,61 +509,61 @@ struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath,
#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \
defined(HAVE_FREEADDRINFO)
-/*
+/*
* curl_dbg_freeaddrinfo()
- *
- * This is strictly for memory tracing and are using the same style as the
- * family otherwise present in memdebug.c. I put these ones here since they
- * require a bunch of structs I didn't want to include in memdebug.c
- */
-
-void
+ *
+ * This is strictly for memory tracing and are using the same style as the
+ * family otherwise present in memdebug.c. I put these ones here since they
+ * require a bunch of structs I didn't want to include in memdebug.c
+ */
+
+void
curl_dbg_freeaddrinfo(struct addrinfo *freethis,
int line, const char *source)
-{
+{
curl_dbg_log("ADDR %s:%d freeaddrinfo(%p)\n",
source, line, (void *)freethis);
#ifdef USE_LWIPSOCK
lwip_freeaddrinfo(freethis);
#else
- (freeaddrinfo)(freethis);
+ (freeaddrinfo)(freethis);
#endif
-}
-#endif /* defined(CURLDEBUG) && defined(HAVE_FREEADDRINFO) */
-
-
-#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO)
-/*
+}
+#endif /* defined(CURLDEBUG) && defined(HAVE_FREEADDRINFO) */
+
+
+#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO)
+/*
* curl_dbg_getaddrinfo()
- *
- * This is strictly for memory tracing and are using the same style as the
- * family otherwise present in memdebug.c. I put these ones here since they
- * require a bunch of structs I didn't want to include in memdebug.c
- */
-
-int
+ *
+ * This is strictly for memory tracing and are using the same style as the
+ * family otherwise present in memdebug.c. I put these ones here since they
+ * require a bunch of structs I didn't want to include in memdebug.c
+ */
+
+int
curl_dbg_getaddrinfo(const char *hostname,
const char *service,
const struct addrinfo *hints,
struct addrinfo **result,
int line, const char *source)
-{
+{
#ifdef USE_LWIPSOCK
int res = lwip_getaddrinfo(hostname, service, hints, result);
#else
int res = (getaddrinfo)(hostname, service, hints, result);
#endif
- if(0 == res)
- /* success */
+ if(0 == res)
+ /* success */
curl_dbg_log("ADDR %s:%d getaddrinfo() = %p\n",
source, line, (void *)*result);
- else
+ else
curl_dbg_log("ADDR %s:%d getaddrinfo() failed\n",
source, line);
- return res;
-}
-#endif /* defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) */
-
+ return res;
+}
+#endif /* defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) */
+
#if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS)
/*
* Work-arounds the sin6_port is always zero bug on iOS 9.3.2 and Mac OS X
diff --git a/contrib/libs/curl/lib/curl_addrinfo.h b/contrib/libs/curl/lib/curl_addrinfo.h
index 6edf71077d..73a8c1b334 100644
--- a/contrib/libs/curl/lib/curl_addrinfo.h
+++ b/contrib/libs/curl/lib/curl_addrinfo.h
@@ -1,82 +1,82 @@
-#ifndef HEADER_CURL_ADDRINFO_H
-#define HEADER_CURL_ADDRINFO_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_ADDRINFO_H
+#define HEADER_CURL_ADDRINFO_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_NETINET_IN_H
-# include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-# include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-# include <arpa/inet.h>
-#endif
-
-#ifdef __VMS
-# include <in.h>
-# include <inet.h>
-# include <stdlib.h>
-#endif
-
-/*
- * Curl_addrinfo is our internal struct definition that we use to allow
- * consistent internal handling of this data. We use this even when the
- * system provides an addrinfo structure definition. And we use this for
- * all sorts of IPv4 and IPV6 builds.
- */
-
-struct Curl_addrinfo {
- int ai_flags;
- int ai_family;
- int ai_socktype;
- int ai_protocol;
- curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */
- char *ai_canonname;
- struct sockaddr *ai_addr;
- struct Curl_addrinfo *ai_next;
-};
-
-void
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_NETINET_IN_H
+# include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+# include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+# include <arpa/inet.h>
+#endif
+
+#ifdef __VMS
+# include <in.h>
+# include <inet.h>
+# include <stdlib.h>
+#endif
+
+/*
+ * Curl_addrinfo is our internal struct definition that we use to allow
+ * consistent internal handling of this data. We use this even when the
+ * system provides an addrinfo structure definition. And we use this for
+ * all sorts of IPv4 and IPV6 builds.
+ */
+
+struct Curl_addrinfo {
+ int ai_flags;
+ int ai_family;
+ int ai_socktype;
+ int ai_protocol;
+ curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */
+ char *ai_canonname;
+ struct sockaddr *ai_addr;
+ struct Curl_addrinfo *ai_next;
+};
+
+void
Curl_freeaddrinfo(struct Curl_addrinfo *cahead);
-
-#ifdef HAVE_GETADDRINFO
-int
-Curl_getaddrinfo_ex(const char *nodename,
- const char *servname,
- const struct addrinfo *hints,
+
+#ifdef HAVE_GETADDRINFO
+int
+Curl_getaddrinfo_ex(const char *nodename,
+ const char *servname,
+ const struct addrinfo *hints,
struct Curl_addrinfo **result);
-#endif
-
+#endif
+
struct Curl_addrinfo *
-Curl_he2ai(const struct hostent *he, int port);
-
+Curl_he2ai(const struct hostent *he, int port);
+
struct Curl_addrinfo *
-Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port);
-
+Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port);
+
struct Curl_addrinfo *Curl_str2addr(char *dotted, int port);
-
+
#ifdef USE_UNIX_SOCKETS
struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath,
bool abstract);
@@ -84,17 +84,17 @@ struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath,
#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \
defined(HAVE_FREEADDRINFO)
-void
+void
curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line, const char *source);
-#endif
-
-#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO)
-int
+#endif
+
+#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO)
+int
curl_dbg_getaddrinfo(const char *hostname, const char *service,
const struct addrinfo *hints, struct addrinfo **result,
int line, const char *source);
-#endif
-
+#endif
+
#ifdef HAVE_GETADDRINFO
#ifdef USE_RESOLVE_ON_IPS
void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port);
@@ -103,4 +103,4 @@ void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port);
#endif
#endif
-#endif /* HEADER_CURL_ADDRINFO_H */
+#endif /* HEADER_CURL_ADDRINFO_H */
diff --git a/contrib/libs/curl/lib/curl_base64.h b/contrib/libs/curl/lib/curl_base64.h
index 56ac557317..d48edc4241 100644
--- a/contrib/libs/curl/lib/curl_base64.h
+++ b/contrib/libs/curl/lib/curl_base64.h
@@ -1,35 +1,35 @@
-#ifndef HEADER_CURL_BASE64_H
-#define HEADER_CURL_BASE64_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_BASE64_H
+#define HEADER_CURL_BASE64_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
CURLcode Curl_base64_encode(struct Curl_easy *data,
- const char *inputbuff, size_t insize,
- char **outptr, size_t *outlen);
+ const char *inputbuff, size_t insize,
+ char **outptr, size_t *outlen);
CURLcode Curl_base64url_encode(struct Curl_easy *data,
const char *inputbuff, size_t insize,
char **outptr, size_t *outlen);
-
-CURLcode Curl_base64_decode(const char *src,
- unsigned char **outptr, size_t *outlen);
-
-#endif /* HEADER_CURL_BASE64_H */
+
+CURLcode Curl_base64_decode(const char *src,
+ unsigned char **outptr, size_t *outlen);
+
+#endif /* HEADER_CURL_BASE64_H */
diff --git a/contrib/libs/curl/lib/curl_config.h b/contrib/libs/curl/lib/curl_config.h
index a7c8c78e1a..e58dec7079 100644
--- a/contrib/libs/curl/lib/curl_config.h
+++ b/contrib/libs/curl/lib/curl_config.h
@@ -1,5 +1,5 @@
-#pragma once
-
+#pragma once
+
#include <util/system/platform.h>
#if defined(__ANDROID__) && defined(MAPSMOBI_BUILD)
diff --git a/contrib/libs/curl/lib/curl_fnmatch.c b/contrib/libs/curl/lib/curl_fnmatch.c
index b2a33289ae..4bfa58598e 100644
--- a/contrib/libs/curl/lib/curl_fnmatch.c
+++ b/contrib/libs/curl/lib/curl_fnmatch.c
@@ -1,64 +1,64 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
#ifndef CURL_DISABLE_FTP
#include <curl/curl.h>
-#include "curl_fnmatch.h"
+#include "curl_fnmatch.h"
#include "curl_memory.h"
-
-/* The last #include file should be: */
-#include "memdebug.h"
-
+
+/* The last #include file should be: */
+#include "memdebug.h"
+
#ifndef HAVE_FNMATCH
-#define CURLFNM_CHARSET_LEN (sizeof(char) * 256)
-#define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15)
-
-#define CURLFNM_NEGATE CURLFNM_CHARSET_LEN
-
-#define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1)
-#define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2)
-#define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3)
-#define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4)
-#define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5)
-#define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6)
-#define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7)
-#define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8)
-#define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9)
-#define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10)
-
-typedef enum {
- CURLFNM_SCHS_DEFAULT = 0,
- CURLFNM_SCHS_RIGHTBR,
- CURLFNM_SCHS_RIGHTBRLEFTBR
-} setcharset_state;
-
-typedef enum {
- CURLFNM_PKW_INIT = 0,
- CURLFNM_PKW_DDOT
-} parsekey_state;
-
+#define CURLFNM_CHARSET_LEN (sizeof(char) * 256)
+#define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15)
+
+#define CURLFNM_NEGATE CURLFNM_CHARSET_LEN
+
+#define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1)
+#define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2)
+#define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3)
+#define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4)
+#define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5)
+#define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6)
+#define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7)
+#define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8)
+#define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9)
+#define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10)
+
+typedef enum {
+ CURLFNM_SCHS_DEFAULT = 0,
+ CURLFNM_SCHS_RIGHTBR,
+ CURLFNM_SCHS_RIGHTBRLEFTBR
+} setcharset_state;
+
+typedef enum {
+ CURLFNM_PKW_INIT = 0,
+ CURLFNM_PKW_DDOT
+} parsekey_state;
+
typedef enum {
CCLASS_OTHER = 0,
CCLASS_DIGIT,
@@ -66,65 +66,65 @@ typedef enum {
CCLASS_LOWER
} char_class;
-#define SETCHARSET_OK 1
-#define SETCHARSET_FAIL 0
-
-static int parsekeyword(unsigned char **pattern, unsigned char *charset)
-{
- parsekey_state state = CURLFNM_PKW_INIT;
-#define KEYLEN 10
- char keyword[KEYLEN] = { 0 };
- int found = FALSE;
- int i;
- unsigned char *p = *pattern;
- for(i = 0; !found; i++) {
- char c = *p++;
- if(i >= KEYLEN)
- return SETCHARSET_FAIL;
- switch(state) {
- case CURLFNM_PKW_INIT:
+#define SETCHARSET_OK 1
+#define SETCHARSET_FAIL 0
+
+static int parsekeyword(unsigned char **pattern, unsigned char *charset)
+{
+ parsekey_state state = CURLFNM_PKW_INIT;
+#define KEYLEN 10
+ char keyword[KEYLEN] = { 0 };
+ int found = FALSE;
+ int i;
+ unsigned char *p = *pattern;
+ for(i = 0; !found; i++) {
+ char c = *p++;
+ if(i >= KEYLEN)
+ return SETCHARSET_FAIL;
+ switch(state) {
+ case CURLFNM_PKW_INIT:
if(ISLOWER(c))
- keyword[i] = c;
- else if(c == ':')
- state = CURLFNM_PKW_DDOT;
- else
+ keyword[i] = c;
+ else if(c == ':')
+ state = CURLFNM_PKW_DDOT;
+ else
return SETCHARSET_FAIL;
- break;
- case CURLFNM_PKW_DDOT:
- if(c == ']')
- found = TRUE;
- else
- return SETCHARSET_FAIL;
- }
- }
-#undef KEYLEN
-
- *pattern = p; /* move caller's pattern pointer */
- if(strcmp(keyword, "digit") == 0)
- charset[CURLFNM_DIGIT] = 1;
- else if(strcmp(keyword, "alnum") == 0)
- charset[CURLFNM_ALNUM] = 1;
- else if(strcmp(keyword, "alpha") == 0)
- charset[CURLFNM_ALPHA] = 1;
- else if(strcmp(keyword, "xdigit") == 0)
- charset[CURLFNM_XDIGIT] = 1;
- else if(strcmp(keyword, "print") == 0)
- charset[CURLFNM_PRINT] = 1;
- else if(strcmp(keyword, "graph") == 0)
- charset[CURLFNM_GRAPH] = 1;
- else if(strcmp(keyword, "space") == 0)
- charset[CURLFNM_SPACE] = 1;
- else if(strcmp(keyword, "blank") == 0)
- charset[CURLFNM_BLANK] = 1;
- else if(strcmp(keyword, "upper") == 0)
- charset[CURLFNM_UPPER] = 1;
- else if(strcmp(keyword, "lower") == 0)
- charset[CURLFNM_LOWER] = 1;
- else
- return SETCHARSET_FAIL;
- return SETCHARSET_OK;
-}
-
+ break;
+ case CURLFNM_PKW_DDOT:
+ if(c == ']')
+ found = TRUE;
+ else
+ return SETCHARSET_FAIL;
+ }
+ }
+#undef KEYLEN
+
+ *pattern = p; /* move caller's pattern pointer */
+ if(strcmp(keyword, "digit") == 0)
+ charset[CURLFNM_DIGIT] = 1;
+ else if(strcmp(keyword, "alnum") == 0)
+ charset[CURLFNM_ALNUM] = 1;
+ else if(strcmp(keyword, "alpha") == 0)
+ charset[CURLFNM_ALPHA] = 1;
+ else if(strcmp(keyword, "xdigit") == 0)
+ charset[CURLFNM_XDIGIT] = 1;
+ else if(strcmp(keyword, "print") == 0)
+ charset[CURLFNM_PRINT] = 1;
+ else if(strcmp(keyword, "graph") == 0)
+ charset[CURLFNM_GRAPH] = 1;
+ else if(strcmp(keyword, "space") == 0)
+ charset[CURLFNM_SPACE] = 1;
+ else if(strcmp(keyword, "blank") == 0)
+ charset[CURLFNM_BLANK] = 1;
+ else if(strcmp(keyword, "upper") == 0)
+ charset[CURLFNM_UPPER] = 1;
+ else if(strcmp(keyword, "lower") == 0)
+ charset[CURLFNM_LOWER] = 1;
+ else
+ return SETCHARSET_FAIL;
+ return SETCHARSET_OK;
+}
+
/* Return the character class. */
static char_class charclass(unsigned char c)
{
@@ -159,107 +159,107 @@ static void setcharorrange(unsigned char **pp, unsigned char *charset)
}
}
-/* returns 1 (true) if pattern is OK, 0 if is bad ("p" is pattern pointer) */
-static int setcharset(unsigned char **p, unsigned char *charset)
-{
- setcharset_state state = CURLFNM_SCHS_DEFAULT;
- bool something_found = FALSE;
- unsigned char c;
+/* returns 1 (true) if pattern is OK, 0 if is bad ("p" is pattern pointer) */
+static int setcharset(unsigned char **p, unsigned char *charset)
+{
+ setcharset_state state = CURLFNM_SCHS_DEFAULT;
+ bool something_found = FALSE;
+ unsigned char c;
memset(charset, 0, CURLFNM_CHSET_SIZE);
- for(;;) {
- c = **p;
+ for(;;) {
+ c = **p;
if(!c)
return SETCHARSET_FAIL;
- switch(state) {
- case CURLFNM_SCHS_DEFAULT:
+ switch(state) {
+ case CURLFNM_SCHS_DEFAULT:
if(c == ']') {
- if(something_found)
- return SETCHARSET_OK;
+ if(something_found)
+ return SETCHARSET_OK;
something_found = TRUE;
- state = CURLFNM_SCHS_RIGHTBR;
- charset[c] = 1;
- (*p)++;
- }
- else if(c == '[') {
+ state = CURLFNM_SCHS_RIGHTBR;
+ charset[c] = 1;
+ (*p)++;
+ }
+ else if(c == '[') {
unsigned char *pp = *p + 1;
if(*pp++ == ':' && parsekeyword(&pp, charset))
*p = pp;
- else {
- charset[c] = 1;
- (*p)++;
- }
- something_found = TRUE;
- }
- else if(c == '^' || c == '!') {
- if(!something_found) {
- if(charset[CURLFNM_NEGATE]) {
- charset[c] = 1;
- something_found = TRUE;
- }
- else
- charset[CURLFNM_NEGATE] = 1; /* negate charset */
- }
- else
- charset[c] = 1;
- (*p)++;
- }
- else if(c == '\\') {
- c = *(++(*p));
+ else {
+ charset[c] = 1;
+ (*p)++;
+ }
+ something_found = TRUE;
+ }
+ else if(c == '^' || c == '!') {
+ if(!something_found) {
+ if(charset[CURLFNM_NEGATE]) {
+ charset[c] = 1;
+ something_found = TRUE;
+ }
+ else
+ charset[CURLFNM_NEGATE] = 1; /* negate charset */
+ }
+ else
+ charset[c] = 1;
+ (*p)++;
+ }
+ else if(c == '\\') {
+ c = *(++(*p));
if(c)
setcharorrange(p, charset);
- else
+ else
charset['\\'] = 1;
something_found = TRUE;
- }
- else {
+ }
+ else {
setcharorrange(p, charset);
- something_found = TRUE;
- }
- break;
- case CURLFNM_SCHS_RIGHTBR:
- if(c == '[') {
- state = CURLFNM_SCHS_RIGHTBRLEFTBR;
- charset[c] = 1;
- (*p)++;
- }
- else if(c == ']') {
- return SETCHARSET_OK;
- }
- else if(ISPRINT(c)) {
- charset[c] = 1;
- (*p)++;
- state = CURLFNM_SCHS_DEFAULT;
- }
- else
- /* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a
- * nonsense warning 'statement not reached' at end of the fnc when
- * compiling on Solaris */
- goto fail;
- break;
- case CURLFNM_SCHS_RIGHTBRLEFTBR:
+ something_found = TRUE;
+ }
+ break;
+ case CURLFNM_SCHS_RIGHTBR:
+ if(c == '[') {
+ state = CURLFNM_SCHS_RIGHTBRLEFTBR;
+ charset[c] = 1;
+ (*p)++;
+ }
+ else if(c == ']') {
+ return SETCHARSET_OK;
+ }
+ else if(ISPRINT(c)) {
+ charset[c] = 1;
+ (*p)++;
+ state = CURLFNM_SCHS_DEFAULT;
+ }
+ else
+ /* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a
+ * nonsense warning 'statement not reached' at end of the fnc when
+ * compiling on Solaris */
+ goto fail;
+ break;
+ case CURLFNM_SCHS_RIGHTBRLEFTBR:
if(c == ']')
- return SETCHARSET_OK;
+ return SETCHARSET_OK;
state = CURLFNM_SCHS_DEFAULT;
charset[c] = 1;
(*p)++;
- break;
- }
- }
-fail:
- return SETCHARSET_FAIL;
-}
-
+ break;
+ }
+ }
+fail:
+ return SETCHARSET_FAIL;
+}
+
static int loop(const unsigned char *pattern, const unsigned char *string,
int maxstars)
-{
- unsigned char *p = (unsigned char *)pattern;
- unsigned char *s = (unsigned char *)string;
- unsigned char charset[CURLFNM_CHSET_SIZE] = { 0 };
-
- for(;;) {
+{
+ unsigned char *p = (unsigned char *)pattern;
+ unsigned char *s = (unsigned char *)string;
+ unsigned char charset[CURLFNM_CHSET_SIZE] = { 0 };
+
+ for(;;) {
unsigned char *pp;
switch(*p) {
@@ -270,19 +270,19 @@ static int loop(const unsigned char *pattern, const unsigned char *string,
'*?*?*' can be expressed as '??*'. */
for(;;) {
if(*++p == '\0')
- return CURL_FNMATCH_MATCH;
+ return CURL_FNMATCH_MATCH;
if(*p == '?') {
if(!*s++)
return CURL_FNMATCH_NOMATCH;
- }
+ }
else if(*p != '*')
break;
- }
+ }
/* Skip string characters until we find a match with pattern suffix. */
for(maxstars--; *s; s++) {
if(loop(p, s, maxstars) == CURL_FNMATCH_MATCH)
- return CURL_FNMATCH_MATCH;
- }
+ return CURL_FNMATCH_MATCH;
+ }
return CURL_FNMATCH_NOMATCH;
case '?':
if(!*s)
@@ -294,7 +294,7 @@ static int loop(const unsigned char *pattern, const unsigned char *string,
return *s? CURL_FNMATCH_NOMATCH: CURL_FNMATCH_MATCH;
case '\\':
if(p[1])
- p++;
+ p++;
if(*s++ != *p++)
return CURL_FNMATCH_NOMATCH;
break;
@@ -326,39 +326,39 @@ static int loop(const unsigned char *pattern, const unsigned char *string,
found = ISBLANK(*s);
else if(charset[CURLFNM_GRAPH])
found = ISGRAPH(*s);
-
+
if(charset[CURLFNM_NEGATE])
found = !found;
-
+
if(!found)
- return CURL_FNMATCH_NOMATCH;
+ return CURL_FNMATCH_NOMATCH;
p = pp + 1;
s++;
break;
- }
+ }
/* Syntax error in set; mismatch! */
return CURL_FNMATCH_NOMATCH;
default:
if(*p++ != *s++)
return CURL_FNMATCH_NOMATCH;
- break;
- }
- }
-}
-
-/*
- * @unittest: 1307
- */
-int Curl_fnmatch(void *ptr, const char *pattern, const char *string)
-{
- (void)ptr; /* the argument is specified by the curl_fnmatch_callback
- prototype, but not used by Curl_fnmatch() */
- if(!pattern || !string) {
- return CURL_FNMATCH_FAIL;
- }
+ break;
+ }
+ }
+}
+
+/*
+ * @unittest: 1307
+ */
+int Curl_fnmatch(void *ptr, const char *pattern, const char *string)
+{
+ (void)ptr; /* the argument is specified by the curl_fnmatch_callback
+ prototype, but not used by Curl_fnmatch() */
+ if(!pattern || !string) {
+ return CURL_FNMATCH_FAIL;
+ }
return loop((unsigned char *)pattern, (unsigned char *)string, 2);
-}
+}
#else
#include <fnmatch.h>
/*
diff --git a/contrib/libs/curl/lib/curl_fnmatch.h b/contrib/libs/curl/lib/curl_fnmatch.h
index 6ae8605acd..1c80ea7793 100644
--- a/contrib/libs/curl/lib/curl_fnmatch.h
+++ b/contrib/libs/curl/lib/curl_fnmatch.h
@@ -1,44 +1,44 @@
-#ifndef HEADER_CURL_FNMATCH_H
-#define HEADER_CURL_FNMATCH_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_FNMATCH_H
+#define HEADER_CURL_FNMATCH_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#define CURL_FNMATCH_MATCH 0
-#define CURL_FNMATCH_NOMATCH 1
-#define CURL_FNMATCH_FAIL 2
-
-/* default pattern matching function
- * =================================
- * Implemented with recursive backtracking, if you want to use Curl_fnmatch,
- * please note that there is not implemented UTF/UNICODE support.
- *
- * Implemented features:
- * '?' notation, does not match UTF characters
- * '*' can also work with UTF string
- * [a-zA-Z0-9] enumeration support
- *
- * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space
- * and upper (use as "[[:alnum:]]")
- */
-int Curl_fnmatch(void *ptr, const char *pattern, const char *string);
-
-#endif /* HEADER_CURL_FNMATCH_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#define CURL_FNMATCH_MATCH 0
+#define CURL_FNMATCH_NOMATCH 1
+#define CURL_FNMATCH_FAIL 2
+
+/* default pattern matching function
+ * =================================
+ * Implemented with recursive backtracking, if you want to use Curl_fnmatch,
+ * please note that there is not implemented UTF/UNICODE support.
+ *
+ * Implemented features:
+ * '?' notation, does not match UTF characters
+ * '*' can also work with UTF string
+ * [a-zA-Z0-9] enumeration support
+ *
+ * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space
+ * and upper (use as "[[:alnum:]]")
+ */
+int Curl_fnmatch(void *ptr, const char *pattern, const char *string);
+
+#endif /* HEADER_CURL_FNMATCH_H */
diff --git a/contrib/libs/curl/lib/curl_gethostname.c b/contrib/libs/curl/lib/curl_gethostname.c
index 94b05199e2..2d5ff61cf6 100644
--- a/contrib/libs/curl/lib/curl_gethostname.c
+++ b/contrib/libs/curl/lib/curl_gethostname.c
@@ -1,100 +1,100 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "curl_gethostname.h"
-
-/*
- * Curl_gethostname() is a wrapper around gethostname() which allows
- * overriding the host name that the function would normally return.
- * This capability is used by the test suite to verify exact matching
- * of NTLM authentication, which exercises libcurl's MD4 and DES code
- * as well as by the SMTP module when a hostname is not provided.
- *
- * For libcurl debug enabled builds host name overriding takes place
- * when environment variable CURL_GETHOSTNAME is set, using the value
- * held by the variable to override returned host name.
- *
- * Note: The function always returns the un-qualified hostname rather
- * than being provider dependent.
- *
- * For libcurl shared library release builds the test suite preloads
- * another shared library named libhostname using the LD_PRELOAD
- * mechanism which intercepts, and might override, the gethostname()
- * function call. In this case a given platform must support the
- * LD_PRELOAD mechanism and additionally have environment variable
- * CURL_GETHOSTNAME set in order to override the returned host name.
- *
- * For libcurl static library release builds no overriding takes place.
- */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include "curl_gethostname.h"
+
+/*
+ * Curl_gethostname() is a wrapper around gethostname() which allows
+ * overriding the host name that the function would normally return.
+ * This capability is used by the test suite to verify exact matching
+ * of NTLM authentication, which exercises libcurl's MD4 and DES code
+ * as well as by the SMTP module when a hostname is not provided.
+ *
+ * For libcurl debug enabled builds host name overriding takes place
+ * when environment variable CURL_GETHOSTNAME is set, using the value
+ * held by the variable to override returned host name.
+ *
+ * Note: The function always returns the un-qualified hostname rather
+ * than being provider dependent.
+ *
+ * For libcurl shared library release builds the test suite preloads
+ * another shared library named libhostname using the LD_PRELOAD
+ * mechanism which intercepts, and might override, the gethostname()
+ * function call. In this case a given platform must support the
+ * LD_PRELOAD mechanism and additionally have environment variable
+ * CURL_GETHOSTNAME set in order to override the returned host name.
+ *
+ * For libcurl static library release builds no overriding takes place.
+ */
+
int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen)
{
-#ifndef HAVE_GETHOSTNAME
-
- /* Allow compilation and return failure when unavailable */
- (void) name;
- (void) namelen;
- return -1;
-
-#else
- int err;
+#ifndef HAVE_GETHOSTNAME
+
+ /* Allow compilation and return failure when unavailable */
+ (void) name;
+ (void) namelen;
+ return -1;
+
+#else
+ int err;
char *dot;
-
-#ifdef DEBUGBUILD
-
- /* Override host name when environment variable CURL_GETHOSTNAME is set */
- const char *force_hostname = getenv("CURL_GETHOSTNAME");
- if(force_hostname) {
- strncpy(name, force_hostname, namelen);
- err = 0;
- }
- else {
- name[0] = '\0';
- err = gethostname(name, namelen);
- }
-
-#else /* DEBUGBUILD */
-
- /* The call to system's gethostname() might get intercepted by the
- libhostname library when libcurl is built as a non-debug shared
- library when running the test suite. */
- name[0] = '\0';
- err = gethostname(name, namelen);
-
-#endif
-
- name[namelen - 1] = '\0';
-
- if(err)
- return err;
-
- /* Truncate domain, leave only machine name */
- dot = strchr(name, '.');
- if(dot)
- *dot = '\0';
-
- return 0;
-#endif
-
-}
+
+#ifdef DEBUGBUILD
+
+ /* Override host name when environment variable CURL_GETHOSTNAME is set */
+ const char *force_hostname = getenv("CURL_GETHOSTNAME");
+ if(force_hostname) {
+ strncpy(name, force_hostname, namelen);
+ err = 0;
+ }
+ else {
+ name[0] = '\0';
+ err = gethostname(name, namelen);
+ }
+
+#else /* DEBUGBUILD */
+
+ /* The call to system's gethostname() might get intercepted by the
+ libhostname library when libcurl is built as a non-debug shared
+ library when running the test suite. */
+ name[0] = '\0';
+ err = gethostname(name, namelen);
+
+#endif
+
+ name[namelen - 1] = '\0';
+
+ if(err)
+ return err;
+
+ /* Truncate domain, leave only machine name */
+ dot = strchr(name, '.');
+ if(dot)
+ *dot = '\0';
+
+ return 0;
+#endif
+
+}
diff --git a/contrib/libs/curl/lib/curl_gethostname.h b/contrib/libs/curl/lib/curl_gethostname.h
index 2e97e55d87..2161c40ac3 100644
--- a/contrib/libs/curl/lib/curl_gethostname.h
+++ b/contrib/libs/curl/lib/curl_gethostname.h
@@ -1,31 +1,31 @@
-#ifndef HEADER_CURL_GETHOSTNAME_H
-#define HEADER_CURL_GETHOSTNAME_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_GETHOSTNAME_H
+#define HEADER_CURL_GETHOSTNAME_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* Hostname buffer size */
-#define HOSTNAME_MAX 1024
-
-/* This returns the local machine's un-qualified hostname */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* Hostname buffer size */
+#define HOSTNAME_MAX 1024
+
+/* This returns the local machine's un-qualified hostname */
int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen);
-
-#endif /* HEADER_CURL_GETHOSTNAME_H */
+
+#endif /* HEADER_CURL_GETHOSTNAME_H */
diff --git a/contrib/libs/curl/lib/curl_gssapi.c b/contrib/libs/curl/lib/curl_gssapi.c
index 184a8479a2..f72430b26f 100644
--- a/contrib/libs/curl/lib/curl_gssapi.c
+++ b/contrib/libs/curl/lib/curl_gssapi.c
@@ -1,32 +1,32 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2011 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_GSSAPI
-
-#include "curl_gssapi.h"
-#include "sendf.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_GSSAPI
+
+#include "curl_gssapi.h"
+#include "sendf.h"
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
@@ -37,50 +37,50 @@ gss_OID_desc Curl_spnego_mech_oid = { 6, &spnego_oid_bytes };
static char krb5_oid_bytes[] = "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02";
gss_OID_desc Curl_krb5_mech_oid = { 9, &krb5_oid_bytes };
-OM_uint32 Curl_gss_init_sec_context(
+OM_uint32 Curl_gss_init_sec_context(
struct Curl_easy *data,
OM_uint32 *minor_status,
gss_ctx_id_t *context,
- gss_name_t target_name,
+ gss_name_t target_name,
gss_OID mech_type,
- gss_channel_bindings_t input_chan_bindings,
- gss_buffer_t input_token,
- gss_buffer_t output_token,
+ gss_channel_bindings_t input_chan_bindings,
+ gss_buffer_t input_token,
+ gss_buffer_t output_token,
const bool mutual_auth,
OM_uint32 *ret_flags)
-{
+{
OM_uint32 req_flags = GSS_C_REPLAY_FLAG;
-
+
if(mutual_auth)
req_flags |= GSS_C_MUTUAL_FLAG;
- if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) {
-#ifdef GSS_C_DELEG_POLICY_FLAG
- req_flags |= GSS_C_DELEG_POLICY_FLAG;
-#else
- infof(data, "warning: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not "
- "compiled in\n");
-#endif
- }
-
- if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG)
- req_flags |= GSS_C_DELEG_FLAG;
-
- return gss_init_sec_context(minor_status,
- GSS_C_NO_CREDENTIAL, /* cred_handle */
- context,
- target_name,
+ if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) {
+#ifdef GSS_C_DELEG_POLICY_FLAG
+ req_flags |= GSS_C_DELEG_POLICY_FLAG;
+#else
+ infof(data, "warning: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not "
+ "compiled in\n");
+#endif
+ }
+
+ if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG)
+ req_flags |= GSS_C_DELEG_FLAG;
+
+ return gss_init_sec_context(minor_status,
+ GSS_C_NO_CREDENTIAL, /* cred_handle */
+ context,
+ target_name,
mech_type,
- req_flags,
- 0, /* time_req */
- input_chan_bindings,
- input_token,
- NULL, /* actual_mech_type */
- output_token,
- ret_flags,
- NULL /* time_rec */);
-}
-
+ req_flags,
+ 0, /* time_req */
+ input_chan_bindings,
+ input_token,
+ NULL, /* actual_mech_type */
+ output_token,
+ ret_flags,
+ NULL /* time_rec */);
+}
+
#define GSS_LOG_BUFFER_LEN 1024
static size_t display_gss_error(OM_uint32 status, int type,
char *buf, size_t len) {
@@ -133,4 +133,4 @@ void Curl_gss_log_error(struct Curl_easy *data, const char *prefix,
infof(data, "%s%s\n", prefix, buf);
}
-#endif /* HAVE_GSSAPI */
+#endif /* HAVE_GSSAPI */
diff --git a/contrib/libs/curl/lib/curl_gssapi.h b/contrib/libs/curl/lib/curl_gssapi.h
index 095753a4c6..466d09ed0a 100644
--- a/contrib/libs/curl/lib/curl_gssapi.h
+++ b/contrib/libs/curl/lib/curl_gssapi.h
@@ -1,47 +1,47 @@
-#ifndef HEADER_CURL_GSSAPI_H
-#define HEADER_CURL_GSSAPI_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_GSSAPI_H
+#define HEADER_CURL_GSSAPI_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2011 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-#include "urldata.h"
-
-#ifdef HAVE_GSSAPI
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+#include "urldata.h"
+
+#ifdef HAVE_GSSAPI
extern gss_OID_desc Curl_spnego_mech_oid;
extern gss_OID_desc Curl_krb5_mech_oid;
-
+
/* Common method for using GSS-API */
-OM_uint32 Curl_gss_init_sec_context(
+OM_uint32 Curl_gss_init_sec_context(
struct Curl_easy *data,
OM_uint32 *minor_status,
gss_ctx_id_t *context,
- gss_name_t target_name,
+ gss_name_t target_name,
gss_OID mech_type,
- gss_channel_bindings_t input_chan_bindings,
- gss_buffer_t input_token,
- gss_buffer_t output_token,
+ gss_channel_bindings_t input_chan_bindings,
+ gss_buffer_t input_token,
+ gss_buffer_t output_token,
const bool mutual_auth,
OM_uint32 *ret_flags);
-
+
/* Helper to log a GSS-API error status */
void Curl_gss_log_error(struct Curl_easy *data, const char *prefix,
OM_uint32 major, OM_uint32 minor);
@@ -57,5 +57,5 @@ void Curl_gss_log_error(struct Curl_easy *data, const char *prefix,
#define GSSAUTH_P_INTEGRITY 2
#define GSSAUTH_P_PRIVACY 4
-#endif /* HAVE_GSSAPI */
-#endif /* HEADER_CURL_GSSAPI_H */
+#endif /* HAVE_GSSAPI */
+#endif /* HEADER_CURL_GSSAPI_H */
diff --git a/contrib/libs/curl/lib/curl_hmac.h b/contrib/libs/curl/lib/curl_hmac.h
index ec037b210f..84c73121bd 100644
--- a/contrib/libs/curl/lib/curl_hmac.h
+++ b/contrib/libs/curl/lib/curl_hmac.h
@@ -1,72 +1,72 @@
-#ifndef HEADER_CURL_HMAC_H
-#define HEADER_CURL_HMAC_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HMAC_H
+#define HEADER_CURL_HMAC_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+
#define HMAC_MD5_LENGTH 16
typedef void (* HMAC_hinit_func)(void *context);
typedef void (* HMAC_hupdate_func)(void *context,
const unsigned char *data,
- unsigned int len);
+ unsigned int len);
typedef void (* HMAC_hfinal_func)(unsigned char *result, void *context);
-
-
-/* Per-hash function HMAC parameters. */
+
+
+/* Per-hash function HMAC parameters. */
struct HMAC_params {
HMAC_hinit_func
hmac_hinit; /* Initialize context procedure. */
- HMAC_hupdate_func hmac_hupdate; /* Update context with data. */
- HMAC_hfinal_func hmac_hfinal; /* Get final result procedure. */
- unsigned int hmac_ctxtsize; /* Context structure size. */
- unsigned int hmac_maxkeylen; /* Maximum key length (bytes). */
- unsigned int hmac_resultlen; /* Result length (bytes). */
+ HMAC_hupdate_func hmac_hupdate; /* Update context with data. */
+ HMAC_hfinal_func hmac_hfinal; /* Get final result procedure. */
+ unsigned int hmac_ctxtsize; /* Context structure size. */
+ unsigned int hmac_maxkeylen; /* Maximum key length (bytes). */
+ unsigned int hmac_resultlen; /* Result length (bytes). */
};
-
-
-/* HMAC computation context. */
+
+
+/* HMAC computation context. */
struct HMAC_context {
const struct HMAC_params *hmac_hash; /* Hash function definition. */
void *hmac_hashctxt1; /* Hash function context 1. */
void *hmac_hashctxt2; /* Hash function context 2. */
};
-
-
-/* Prototypes. */
+
+
+/* Prototypes. */
struct HMAC_context *Curl_HMAC_init(const struct HMAC_params *hashparams,
const unsigned char *key,
unsigned int keylen);
int Curl_HMAC_update(struct HMAC_context *context,
const unsigned char *data,
- unsigned int len);
+ unsigned int len);
int Curl_HMAC_final(struct HMAC_context *context, unsigned char *result);
-
+
CURLcode Curl_hmacit(const struct HMAC_params *hashparams,
const unsigned char *key, const size_t keylen,
const unsigned char *data, const size_t datalen,
unsigned char *output);
-#endif
-
-#endif /* HEADER_CURL_HMAC_H */
+#endif
+
+#endif /* HEADER_CURL_HMAC_H */
diff --git a/contrib/libs/curl/lib/curl_ldap.h b/contrib/libs/curl/lib/curl_ldap.h
index 14790eb578..124e18b133 100644
--- a/contrib/libs/curl/lib/curl_ldap.h
+++ b/contrib/libs/curl/lib/curl_ldap.h
@@ -1,34 +1,34 @@
-#ifndef HEADER_CURL_LDAP_H
-#define HEADER_CURL_LDAP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_LDAP_H
+#define HEADER_CURL_LDAP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifndef CURL_DISABLE_LDAP
-extern const struct Curl_handler Curl_handler_ldap;
-
-#if !defined(CURL_DISABLE_LDAPS) && \
- ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
- (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
-extern const struct Curl_handler Curl_handler_ldaps;
-#endif
-
-#endif
-#endif /* HEADER_CURL_LDAP_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifndef CURL_DISABLE_LDAP
+extern const struct Curl_handler Curl_handler_ldap;
+
+#if !defined(CURL_DISABLE_LDAPS) && \
+ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
+ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
+extern const struct Curl_handler Curl_handler_ldaps;
+#endif
+
+#endif
+#endif /* HEADER_CURL_LDAP_H */
diff --git a/contrib/libs/curl/lib/curl_md4.h b/contrib/libs/curl/lib/curl_md4.h
index 84273d0f3e..f9dafcb53c 100644
--- a/contrib/libs/curl/lib/curl_md4.h
+++ b/contrib/libs/curl/lib/curl_md4.h
@@ -1,36 +1,36 @@
-#ifndef HEADER_CURL_MD4_H
-#define HEADER_CURL_MD4_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MD4_H
+#define HEADER_CURL_MD4_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if !defined(CURL_DISABLE_CRYPTO_AUTH)
#define MD4_DIGEST_LENGTH 16
void Curl_md4it(unsigned char *output, const unsigned char *input,
const size_t len);
-
+
#endif /* !defined(CURL_DISABLE_CRYPTO_AUTH) */
-#endif /* HEADER_CURL_MD4_H */
+#endif /* HEADER_CURL_MD4_H */
diff --git a/contrib/libs/curl/lib/curl_md5.h b/contrib/libs/curl/lib/curl_md5.h
index f142ed7833..5739c89ca4 100644
--- a/contrib/libs/curl/lib/curl_md5.h
+++ b/contrib/libs/curl/lib/curl_md5.h
@@ -1,63 +1,63 @@
-#ifndef HEADER_CURL_MD5_H
-#define HEADER_CURL_MD5_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MD5_H
+#define HEADER_CURL_MD5_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
-#include "curl_hmac.h"
-
-#define MD5_DIGEST_LEN 16
-
-typedef void (* Curl_MD5_init_func)(void *context);
-typedef void (* Curl_MD5_update_func)(void *context,
- const unsigned char *data,
- unsigned int len);
-typedef void (* Curl_MD5_final_func)(unsigned char *result, void *context);
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+#include "curl_hmac.h"
+
+#define MD5_DIGEST_LEN 16
+
+typedef void (* Curl_MD5_init_func)(void *context);
+typedef void (* Curl_MD5_update_func)(void *context,
+ const unsigned char *data,
+ unsigned int len);
+typedef void (* Curl_MD5_final_func)(unsigned char *result, void *context);
+
struct MD5_params {
- Curl_MD5_init_func md5_init_func; /* Initialize context procedure */
- Curl_MD5_update_func md5_update_func; /* Update context with data */
- Curl_MD5_final_func md5_final_func; /* Get final result procedure */
- unsigned int md5_ctxtsize; /* Context structure size */
- unsigned int md5_resultlen; /* Result length (bytes) */
+ Curl_MD5_init_func md5_init_func; /* Initialize context procedure */
+ Curl_MD5_update_func md5_update_func; /* Update context with data */
+ Curl_MD5_final_func md5_final_func; /* Get final result procedure */
+ unsigned int md5_ctxtsize; /* Context structure size */
+ unsigned int md5_resultlen; /* Result length (bytes) */
};
-
+
struct MD5_context {
const struct MD5_params *md5_hash; /* Hash function definition */
- void *md5_hashctx; /* Hash function context */
+ void *md5_hashctx; /* Hash function context */
};
-
+
extern const struct MD5_params Curl_DIGEST_MD5[1];
extern const struct HMAC_params Curl_HMAC_MD5[1];
-
+
void Curl_md5it(unsigned char *output, const unsigned char *input,
const size_t len);
-
+
struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params);
CURLcode Curl_MD5_update(struct MD5_context *context,
const unsigned char *data,
unsigned int len);
CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result);
-
-#endif
-
-#endif /* HEADER_CURL_MD5_H */
+
+#endif
+
+#endif /* HEADER_CURL_MD5_H */
diff --git a/contrib/libs/curl/lib/curl_memory.h b/contrib/libs/curl/lib/curl_memory.h
index d7f6fef1b4..5806290637 100644
--- a/contrib/libs/curl/lib/curl_memory.h
+++ b/contrib/libs/curl/lib/curl_memory.h
@@ -1,88 +1,88 @@
-#ifndef HEADER_CURL_MEMORY_H
-#define HEADER_CURL_MEMORY_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MEMORY_H
+#define HEADER_CURL_MEMORY_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * Nasty internal details ahead...
- *
- * File curl_memory.h must be included by _all_ *.c source files
- * that use memory related functions strdup, malloc, calloc, realloc
- * or free, and given source file is used to build libcurl library.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * Nasty internal details ahead...
+ *
+ * File curl_memory.h must be included by _all_ *.c source files
+ * that use memory related functions strdup, malloc, calloc, realloc
+ * or free, and given source file is used to build libcurl library.
* It should be included immediately before memdebug.h as the last files
* included to avoid undesired interaction with other memory function
* headers in dependent libraries.
- *
- * There is nearly no exception to above rule. All libcurl source
- * files in 'lib' subdirectory as well as those living deep inside
- * 'packages' subdirectories and linked together in order to build
- * libcurl library shall follow it.
- *
- * File lib/strdup.c is an exception, given that it provides a strdup
- * clone implementation while using malloc. Extra care needed inside
+ *
+ * There is nearly no exception to above rule. All libcurl source
+ * files in 'lib' subdirectory as well as those living deep inside
+ * 'packages' subdirectories and linked together in order to build
+ * libcurl library shall follow it.
+ *
+ * File lib/strdup.c is an exception, given that it provides a strdup
+ * clone implementation while using malloc. Extra care needed inside
* this one.
- *
- * The need for curl_memory.h inclusion is due to libcurl's feature
- * of allowing library user to provide memory replacement functions,
- * memory callbacks, at runtime with curl_global_init_mem()
- *
- * Any *.c source file used to build libcurl library that does not
- * include curl_memory.h and uses any memory function of the five
- * mentioned above will compile without any indication, but it will
- * trigger weird memory related issues at runtime.
- *
- * OTOH some source files from 'lib' subdirectory may additionally be
- * used directly as source code when using some curlx_ functions by
- * third party programs that don't even use libcurl at all. When using
- * these source files in this way it is necessary these are compiled
- * with CURLX_NO_MEMORY_CALLBACKS defined, in order to ensure that no
- * attempt of calling libcurl's memory callbacks is done from code
- * which can not use this machinery.
- *
- * Notice that libcurl's 'memory tracking' system works chaining into
- * the memory callback machinery. This implies that when compiling
- * 'lib' source files with CURLX_NO_MEMORY_CALLBACKS defined this file
- * disengages usage of libcurl's 'memory tracking' system, defining
- * MEMDEBUG_NODEFINES and overriding CURLDEBUG purpose.
- *
- * CURLX_NO_MEMORY_CALLBACKS takes precedence over CURLDEBUG. This is
- * done in order to allow building a 'memory tracking' enabled libcurl
- * and at the same time allow building programs which do not use it.
- *
- * Programs and libraries in 'tests' subdirectories have specific
- * purposes and needs, and as such each one will use whatever fits
+ *
+ * The need for curl_memory.h inclusion is due to libcurl's feature
+ * of allowing library user to provide memory replacement functions,
+ * memory callbacks, at runtime with curl_global_init_mem()
+ *
+ * Any *.c source file used to build libcurl library that does not
+ * include curl_memory.h and uses any memory function of the five
+ * mentioned above will compile without any indication, but it will
+ * trigger weird memory related issues at runtime.
+ *
+ * OTOH some source files from 'lib' subdirectory may additionally be
+ * used directly as source code when using some curlx_ functions by
+ * third party programs that don't even use libcurl at all. When using
+ * these source files in this way it is necessary these are compiled
+ * with CURLX_NO_MEMORY_CALLBACKS defined, in order to ensure that no
+ * attempt of calling libcurl's memory callbacks is done from code
+ * which can not use this machinery.
+ *
+ * Notice that libcurl's 'memory tracking' system works chaining into
+ * the memory callback machinery. This implies that when compiling
+ * 'lib' source files with CURLX_NO_MEMORY_CALLBACKS defined this file
+ * disengages usage of libcurl's 'memory tracking' system, defining
+ * MEMDEBUG_NODEFINES and overriding CURLDEBUG purpose.
+ *
+ * CURLX_NO_MEMORY_CALLBACKS takes precedence over CURLDEBUG. This is
+ * done in order to allow building a 'memory tracking' enabled libcurl
+ * and at the same time allow building programs which do not use it.
+ *
+ * Programs and libraries in 'tests' subdirectories have specific
+ * purposes and needs, and as such each one will use whatever fits
* best, depending additionally whether it links with libcurl or not.
- *
- * Caveat emptor. Proper curlx_* separation is a work in progress
- * the same as CURLX_NO_MEMORY_CALLBACKS usage, some adjustments may
- * still be required. IOW don't use them yet, there are sharp edges.
- */
-
-#ifdef HEADER_CURL_MEMDEBUG_H
-#error "Header memdebug.h shall not be included before curl_memory.h"
-#endif
-
-#ifndef CURLX_NO_MEMORY_CALLBACKS
-
+ *
+ * Caveat emptor. Proper curlx_* separation is a work in progress
+ * the same as CURLX_NO_MEMORY_CALLBACKS usage, some adjustments may
+ * still be required. IOW don't use them yet, there are sharp edges.
+ */
+
+#ifdef HEADER_CURL_MEMDEBUG_H
+#error "Header memdebug.h shall not be included before curl_memory.h"
+#endif
+
+#ifndef CURLX_NO_MEMORY_CALLBACKS
+
#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* only if not already done */
/*
* The following memory function replacement typedef's are COPIED from
@@ -97,60 +97,60 @@ typedef char *(*curl_strdup_callback)(const char *str);
typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size);
#define CURL_DID_MEMORY_FUNC_TYPEDEFS
#endif
-
-extern curl_malloc_callback Curl_cmalloc;
-extern curl_free_callback Curl_cfree;
-extern curl_realloc_callback Curl_crealloc;
-extern curl_strdup_callback Curl_cstrdup;
-extern curl_calloc_callback Curl_ccalloc;
-#if defined(WIN32) && defined(UNICODE)
-extern curl_wcsdup_callback Curl_cwcsdup;
-#endif
-
-#ifndef CURLDEBUG
-
-/*
- * libcurl's 'memory tracking' system defines strdup, malloc, calloc,
- * realloc and free, along with others, in memdebug.h in a different
- * way although still using memory callbacks forward declared above.
- * When using the 'memory tracking' system (CURLDEBUG defined) we do
- * not define here the five memory functions given that definitions
- * from memdebug.h are the ones that shall be used.
- */
-
-#undef strdup
-#define strdup(ptr) Curl_cstrdup(ptr)
-#undef malloc
-#define malloc(size) Curl_cmalloc(size)
-#undef calloc
-#define calloc(nbelem,size) Curl_ccalloc(nbelem, size)
-#undef realloc
-#define realloc(ptr,size) Curl_crealloc(ptr, size)
-#undef free
-#define free(ptr) Curl_cfree(ptr)
-
-#ifdef WIN32
-# ifdef UNICODE
-# undef wcsdup
-# define wcsdup(ptr) Curl_cwcsdup(ptr)
-# undef _wcsdup
-# define _wcsdup(ptr) Curl_cwcsdup(ptr)
-# undef _tcsdup
-# define _tcsdup(ptr) Curl_cwcsdup(ptr)
-# else
-# undef _tcsdup
-# define _tcsdup(ptr) Curl_cstrdup(ptr)
-# endif
-#endif
-
-#endif /* CURLDEBUG */
-
-#else /* CURLX_NO_MEMORY_CALLBACKS */
-
-#ifndef MEMDEBUG_NODEFINES
-#define MEMDEBUG_NODEFINES
-#endif
-
-#endif /* CURLX_NO_MEMORY_CALLBACKS */
-
-#endif /* HEADER_CURL_MEMORY_H */
+
+extern curl_malloc_callback Curl_cmalloc;
+extern curl_free_callback Curl_cfree;
+extern curl_realloc_callback Curl_crealloc;
+extern curl_strdup_callback Curl_cstrdup;
+extern curl_calloc_callback Curl_ccalloc;
+#if defined(WIN32) && defined(UNICODE)
+extern curl_wcsdup_callback Curl_cwcsdup;
+#endif
+
+#ifndef CURLDEBUG
+
+/*
+ * libcurl's 'memory tracking' system defines strdup, malloc, calloc,
+ * realloc and free, along with others, in memdebug.h in a different
+ * way although still using memory callbacks forward declared above.
+ * When using the 'memory tracking' system (CURLDEBUG defined) we do
+ * not define here the five memory functions given that definitions
+ * from memdebug.h are the ones that shall be used.
+ */
+
+#undef strdup
+#define strdup(ptr) Curl_cstrdup(ptr)
+#undef malloc
+#define malloc(size) Curl_cmalloc(size)
+#undef calloc
+#define calloc(nbelem,size) Curl_ccalloc(nbelem, size)
+#undef realloc
+#define realloc(ptr,size) Curl_crealloc(ptr, size)
+#undef free
+#define free(ptr) Curl_cfree(ptr)
+
+#ifdef WIN32
+# ifdef UNICODE
+# undef wcsdup
+# define wcsdup(ptr) Curl_cwcsdup(ptr)
+# undef _wcsdup
+# define _wcsdup(ptr) Curl_cwcsdup(ptr)
+# undef _tcsdup
+# define _tcsdup(ptr) Curl_cwcsdup(ptr)
+# else
+# undef _tcsdup
+# define _tcsdup(ptr) Curl_cstrdup(ptr)
+# endif
+#endif
+
+#endif /* CURLDEBUG */
+
+#else /* CURLX_NO_MEMORY_CALLBACKS */
+
+#ifndef MEMDEBUG_NODEFINES
+#define MEMDEBUG_NODEFINES
+#endif
+
+#endif /* CURLX_NO_MEMORY_CALLBACKS */
+
+#endif /* HEADER_CURL_MEMORY_H */
diff --git a/contrib/libs/curl/lib/curl_memrchr.c b/contrib/libs/curl/lib/curl_memrchr.c
index 162c82e5c8..0bd845f690 100644
--- a/contrib/libs/curl/lib/curl_memrchr.c
+++ b/contrib/libs/curl/lib/curl_memrchr.c
@@ -1,62 +1,62 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <curl/curl.h>
-#include "curl_memrchr.h"
+#include "curl_memrchr.h"
#include "curl_memory.h"
-
-/* The last #include file should be: */
-#include "memdebug.h"
-
-#ifndef HAVE_MEMRCHR
-
-/*
- * Curl_memrchr()
- *
- * Our memrchr() function clone for systems which lack this function. The
- * memrchr() function is like the memchr() function, except that it searches
- * backwards from the end of the n bytes pointed to by s instead of forward
- * from the beginning.
- */
-
-void *
-Curl_memrchr(const void *s, int c, size_t n)
-{
+
+/* The last #include file should be: */
+#include "memdebug.h"
+
+#ifndef HAVE_MEMRCHR
+
+/*
+ * Curl_memrchr()
+ *
+ * Our memrchr() function clone for systems which lack this function. The
+ * memrchr() function is like the memchr() function, except that it searches
+ * backwards from the end of the n bytes pointed to by s instead of forward
+ * from the beginning.
+ */
+
+void *
+Curl_memrchr(const void *s, int c, size_t n)
+{
if(n > 0) {
const unsigned char *p = s;
const unsigned char *q = s;
-
+
p += n - 1;
-
+
while(p >= q) {
if(*p == (unsigned char)c)
return (void *)p;
p--;
}
- }
- return NULL;
-}
-
-#endif /* HAVE_MEMRCHR */
+ }
+ return NULL;
+}
+
+#endif /* HAVE_MEMRCHR */
diff --git a/contrib/libs/curl/lib/curl_memrchr.h b/contrib/libs/curl/lib/curl_memrchr.h
index bff10d6813..c8394bb433 100644
--- a/contrib/libs/curl/lib/curl_memrchr.h
+++ b/contrib/libs/curl/lib/curl_memrchr.h
@@ -1,44 +1,44 @@
-#ifndef HEADER_CURL_MEMRCHR_H
-#define HEADER_CURL_MEMRCHR_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MEMRCHR_H
+#define HEADER_CURL_MEMRCHR_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_MEMRCHR
-
-#ifdef HAVE_STRING_H
-# include <string.h>
-#endif
-#ifdef HAVE_STRINGS_H
-# include <strings.h>
-#endif
-
-#else /* HAVE_MEMRCHR */
-
-void *Curl_memrchr(const void *s, int c, size_t n);
-
-#define memrchr(x,y,z) Curl_memrchr((x),(y),(z))
-
-#endif /* HAVE_MEMRCHR */
-
-#endif /* HEADER_CURL_MEMRCHR_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_MEMRCHR
+
+#ifdef HAVE_STRING_H
+# include <string.h>
+#endif
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif
+
+#else /* HAVE_MEMRCHR */
+
+void *Curl_memrchr(const void *s, int c, size_t n);
+
+#define memrchr(x,y,z) Curl_memrchr((x),(y),(z))
+
+#endif /* HAVE_MEMRCHR */
+
+#endif /* HEADER_CURL_MEMRCHR_H */
diff --git a/contrib/libs/curl/lib/curl_multibyte.c b/contrib/libs/curl/lib/curl_multibyte.c
index d078021e49..d327c8ba77 100644
--- a/contrib/libs/curl/lib/curl_multibyte.c
+++ b/contrib/libs/curl/lib/curl_multibyte.c
@@ -1,83 +1,83 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
/*
* This file is 'mem-include-scan' clean. See test 1132.
*/
-#include "curl_setup.h"
-
+#include "curl_setup.h"
+
#if defined(WIN32)
-
-#include "curl_multibyte.h"
-
+
+#include "curl_multibyte.h"
+
/*
* MultiByte conversions using Windows kernel32 library.
*/
-
+
wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8)
-{
- wchar_t *str_w = NULL;
-
- if(str_utf8) {
- int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
- str_utf8, -1, NULL, 0);
- if(str_w_len > 0) {
- str_w = malloc(str_w_len * sizeof(wchar_t));
- if(str_w) {
- if(MultiByteToWideChar(CP_UTF8, 0, str_utf8, -1, str_w,
- str_w_len) == 0) {
+{
+ wchar_t *str_w = NULL;
+
+ if(str_utf8) {
+ int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
+ str_utf8, -1, NULL, 0);
+ if(str_w_len > 0) {
+ str_w = malloc(str_w_len * sizeof(wchar_t));
+ if(str_w) {
+ if(MultiByteToWideChar(CP_UTF8, 0, str_utf8, -1, str_w,
+ str_w_len) == 0) {
free(str_w);
return NULL;
- }
- }
- }
- }
-
- return str_w;
-}
-
+ }
+ }
+ }
+ }
+
+ return str_w;
+}
+
char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w)
-{
- char *str_utf8 = NULL;
-
- if(str_w) {
+{
+ char *str_utf8 = NULL;
+
+ if(str_w) {
int bytes = WideCharToMultiByte(CP_UTF8, 0, str_w, -1,
NULL, 0, NULL, NULL);
if(bytes > 0) {
str_utf8 = malloc(bytes);
- if(str_utf8) {
+ if(str_utf8) {
if(WideCharToMultiByte(CP_UTF8, 0, str_w, -1, str_utf8, bytes,
NULL, NULL) == 0) {
free(str_utf8);
return NULL;
- }
- }
- }
- }
-
- return str_utf8;
-}
-
+ }
+ }
+ }
+ }
+
+ return str_utf8;
+}
+
#endif /* WIN32 */
#if defined(USE_WIN32_LARGE_FILES) || defined(USE_WIN32_SMALL_FILES)
diff --git a/contrib/libs/curl/lib/curl_multibyte.h b/contrib/libs/curl/lib/curl_multibyte.h
index 715e26580a..8adaf49784 100644
--- a/contrib/libs/curl/lib/curl_multibyte.h
+++ b/contrib/libs/curl/lib/curl_multibyte.h
@@ -1,59 +1,59 @@
-#ifndef HEADER_CURL_MULTIBYTE_H
-#define HEADER_CURL_MULTIBYTE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MULTIBYTE_H
+#define HEADER_CURL_MULTIBYTE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
#if defined(WIN32)
-
- /*
- * MultiByte conversions using Windows kernel32 library.
- */
-
+
+ /*
+ * MultiByte conversions using Windows kernel32 library.
+ */
+
wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8);
char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w);
-
+
#endif /* WIN32 */
-
-/*
+
+/*
* Macros curlx_convert_UTF8_to_tchar(), curlx_convert_tchar_to_UTF8()
* and curlx_unicodefree() main purpose is to minimize the number of
- * preprocessor conditional directives needed by code using these
- * to differentiate UNICODE from non-UNICODE builds.
- *
+ * preprocessor conditional directives needed by code using these
+ * to differentiate UNICODE from non-UNICODE builds.
+ *
* When building with UNICODE defined, these two macros
* curlx_convert_UTF8_to_tchar() and curlx_convert_tchar_to_UTF8()
- * return a pointer to a newly allocated memory area holding result.
- * When the result is no longer needed, allocated memory is intended
+ * return a pointer to a newly allocated memory area holding result.
+ * When the result is no longer needed, allocated memory is intended
* to be free'ed with curlx_unicodefree().
- *
- * When building without UNICODE defined, this macros
+ *
+ * When building without UNICODE defined, this macros
* curlx_convert_UTF8_to_tchar() and curlx_convert_tchar_to_UTF8()
* return the pointer received as argument. curlx_unicodefree() does
- * no actual free'ing of this pointer it is simply set to NULL.
- */
-
+ * no actual free'ing of this pointer it is simply set to NULL.
+ */
+
#if defined(UNICODE) && defined(WIN32)
-
+
#define curlx_convert_UTF8_to_tchar(ptr) curlx_convert_UTF8_to_wchar((ptr))
#define curlx_convert_tchar_to_UTF8(ptr) curlx_convert_wchar_to_UTF8((ptr))
#define curlx_unicodefree(ptr) \
@@ -63,28 +63,28 @@ char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w);
(ptr) = NULL; \
} \
} while(0)
-
-typedef union {
- unsigned short *tchar_ptr;
- const unsigned short *const_tchar_ptr;
- unsigned short *tbyte_ptr;
- const unsigned short *const_tbyte_ptr;
-} xcharp_u;
-
-#else
-
+
+typedef union {
+ unsigned short *tchar_ptr;
+ const unsigned short *const_tchar_ptr;
+ unsigned short *tbyte_ptr;
+ const unsigned short *const_tbyte_ptr;
+} xcharp_u;
+
+#else
+
#define curlx_convert_UTF8_to_tchar(ptr) (ptr)
#define curlx_convert_tchar_to_UTF8(ptr) (ptr)
#define curlx_unicodefree(ptr) \
do {(ptr) = NULL;} while(0)
-
-typedef union {
- char *tchar_ptr;
- const char *const_tchar_ptr;
- unsigned char *tbyte_ptr;
- const unsigned char *const_tbyte_ptr;
-} xcharp_u;
-
+
+typedef union {
+ char *tchar_ptr;
+ const char *const_tchar_ptr;
+ unsigned char *tbyte_ptr;
+ const unsigned char *const_tbyte_ptr;
+} xcharp_u;
+
#endif /* UNICODE && WIN32 */
-
-#endif /* HEADER_CURL_MULTIBYTE_H */
+
+#endif /* HEADER_CURL_MULTIBYTE_H */
diff --git a/contrib/libs/curl/lib/curl_ntlm_core.c b/contrib/libs/curl/lib/curl_ntlm_core.c
index 41c03262b1..b35b566a71 100644
--- a/contrib/libs/curl/lib/curl_ntlm_core.c
+++ b/contrib/libs/curl/lib/curl_ntlm_core.c
@@ -1,38 +1,38 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if defined(USE_CURL_NTLM_CORE)
-
-/*
- * NTLM details:
- *
+
+/*
+ * NTLM details:
+ *
* https://davenport.sourceforge.io/ntlm.html
* https://www.innovation.ch/java/ntlm.html
- */
-
+ */
+
/* Please keep the SSL backend-specific #if branches in this order:
-
+
1. USE_OPENSSL
2. USE_GNUTLS_NETTLE
3. USE_GNUTLS
@@ -62,52 +62,52 @@
# include <openssl/rand.h>
# if (defined(OPENSSL_VERSION_NUMBER) && \
(OPENSSL_VERSION_NUMBER < 0x00907001L)) && !defined(USE_WOLFSSL)
-# define DES_key_schedule des_key_schedule
-# define DES_cblock des_cblock
-# define DES_set_odd_parity des_set_odd_parity
-# define DES_set_key des_set_key
-# define DES_ecb_encrypt des_ecb_encrypt
-# define DESKEY(x) x
-# define DESKEYARG(x) x
-# else
-# define DESKEYARG(x) *x
-# define DESKEY(x) &x
-# endif
-
-#elif defined(USE_GNUTLS_NETTLE)
-
-# include <nettle/des.h>
-
-#elif defined(USE_GNUTLS)
-
-# include <gcrypt.h>
-
-#elif defined(USE_NSS)
-
-# include <nss.h>
-# include <pk11pub.h>
-# include <hasht.h>
-
+# define DES_key_schedule des_key_schedule
+# define DES_cblock des_cblock
+# define DES_set_odd_parity des_set_odd_parity
+# define DES_set_key des_set_key
+# define DES_ecb_encrypt des_ecb_encrypt
+# define DESKEY(x) x
+# define DESKEYARG(x) x
+# else
+# define DESKEYARG(x) *x
+# define DESKEY(x) &x
+# endif
+
+#elif defined(USE_GNUTLS_NETTLE)
+
+# include <nettle/des.h>
+
+#elif defined(USE_GNUTLS)
+
+# include <gcrypt.h>
+
+#elif defined(USE_NSS)
+
+# include <nss.h>
+# include <pk11pub.h>
+# include <hasht.h>
+
#elif defined(USE_MBEDTLS)
# error #include <mbedtls/des.h>
# include "curl_md4.h"
#elif defined(USE_SECTRANSP)
-
-# include <CommonCrypto/CommonCryptor.h>
-# include <CommonCrypto/CommonDigest.h>
-
+
+# include <CommonCrypto/CommonCryptor.h>
+# include <CommonCrypto/CommonDigest.h>
+
#elif defined(USE_OS400CRYPTO)
# error #include "cipher.mih" /* mih/cipher */
#elif defined(USE_WIN32_CRYPTO)
# include <wincrypt.h>
-#else
-# error "Can't compile NTLM support without a crypto library."
-#endif
-
-#include "urldata.h"
-#include "non-ascii.h"
+#else
+# error "Can't compile NTLM support without a crypto library."
+#endif
+
+#include "urldata.h"
+#include "non-ascii.h"
#include "strcase.h"
#include "curl_ntlm_core.h"
#include "curl_md5.h"
@@ -118,35 +118,35 @@
#include "curl_md4.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
+#include "curl_memory.h"
#include "memdebug.h"
-
+
#define NTLMv2_BLOB_SIGNATURE "\x01\x01\x00\x00"
#define NTLMv2_BLOB_LEN (44 -16 + ntlm->target_info_len + 4)
-
-/*
+
+/*
* Turns a 56-bit key into being 64-bit wide.
*/
static void extend_key_56_to_64(const unsigned char *key_56, char *key)
-{
- key[0] = key_56[0];
- key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1));
- key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2));
- key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3));
- key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4));
- key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5));
- key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6));
- key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF);
-}
-
+{
+ key[0] = key_56[0];
+ key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1));
+ key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2));
+ key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3));
+ key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4));
+ key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5));
+ key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6));
+ key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF);
+}
+
#if defined(USE_OPENSSL) || defined(USE_WOLFSSL)
-/*
+/*
* Turns a 56 bit key into the 64 bit, odd parity key and sets the key. The
* key schedule ks is also set.
- */
+ */
static void setup_des_key(const unsigned char *key_56,
DES_key_schedule DESKEYARG(ks))
-{
+{
DES_cblock key;
/* Expand the 56-bit key to 64-bits */
@@ -157,109 +157,109 @@ static void setup_des_key(const unsigned char *key_56,
/* Set the key */
DES_set_key(&key, ks);
-}
-
+}
+
#elif defined(USE_GNUTLS_NETTLE)
-
-static void setup_des_key(const unsigned char *key_56,
- struct des_ctx *des)
-{
- char key[8];
+
+static void setup_des_key(const unsigned char *key_56,
+ struct des_ctx *des)
+{
+ char key[8];
/* Expand the 56-bit key to 64-bits */
- extend_key_56_to_64(key_56, key);
+ extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Set the key */
des_set_key(des, (const uint8_t *) key);
-}
-
-#elif defined(USE_GNUTLS)
-
-/*
- * Turns a 56 bit key into the 64 bit, odd parity key and sets the key.
- */
-static void setup_des_key(const unsigned char *key_56,
- gcry_cipher_hd_t *des)
-{
- char key[8];
+}
+
+#elif defined(USE_GNUTLS)
+
+/*
+ * Turns a 56 bit key into the 64 bit, odd parity key and sets the key.
+ */
+static void setup_des_key(const unsigned char *key_56,
+ gcry_cipher_hd_t *des)
+{
+ char key[8];
/* Expand the 56-bit key to 64-bits */
- extend_key_56_to_64(key_56, key);
+ extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Set the key */
gcry_cipher_setkey(*des, key, sizeof(key));
-}
-
-#elif defined(USE_NSS)
-
-/*
- * Expands a 56 bit key KEY_56 to 64 bit and encrypts 64 bit of data, using
- * the expanded key. The caller is responsible for giving 64 bit of valid
- * data is IN and (at least) 64 bit large buffer as OUT.
- */
-static bool encrypt_des(const unsigned char *in, unsigned char *out,
- const unsigned char *key_56)
-{
- const CK_MECHANISM_TYPE mech = CKM_DES_ECB; /* DES cipher in ECB mode */
- char key[8]; /* expanded 64 bit key */
- SECItem key_item;
- PK11SymKey *symkey = NULL;
- SECItem *param = NULL;
- PK11Context *ctx = NULL;
- int out_len; /* not used, required by NSS */
- bool rv = FALSE;
-
- /* use internal slot for DES encryption (requires NSS to be initialized) */
+}
+
+#elif defined(USE_NSS)
+
+/*
+ * Expands a 56 bit key KEY_56 to 64 bit and encrypts 64 bit of data, using
+ * the expanded key. The caller is responsible for giving 64 bit of valid
+ * data is IN and (at least) 64 bit large buffer as OUT.
+ */
+static bool encrypt_des(const unsigned char *in, unsigned char *out,
+ const unsigned char *key_56)
+{
+ const CK_MECHANISM_TYPE mech = CKM_DES_ECB; /* DES cipher in ECB mode */
+ char key[8]; /* expanded 64 bit key */
+ SECItem key_item;
+ PK11SymKey *symkey = NULL;
+ SECItem *param = NULL;
+ PK11Context *ctx = NULL;
+ int out_len; /* not used, required by NSS */
+ bool rv = FALSE;
+
+ /* use internal slot for DES encryption (requires NSS to be initialized) */
PK11SlotInfo *slot = PK11_GetInternalKeySlot();
- if(!slot)
- return FALSE;
-
+ if(!slot)
+ return FALSE;
+
/* Expand the 56-bit key to 64-bits */
- extend_key_56_to_64(key_56, key);
+ extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Import the key */
- key_item.data = (unsigned char *)key;
+ key_item.data = (unsigned char *)key;
key_item.len = sizeof(key);
- symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap, CKA_ENCRYPT,
- &key_item, NULL);
- if(!symkey)
- goto fail;
-
+ symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap, CKA_ENCRYPT,
+ &key_item, NULL);
+ if(!symkey)
+ goto fail;
+
/* Create the DES encryption context */
- param = PK11_ParamFromIV(mech, /* no IV in ECB mode */ NULL);
- if(!param)
- goto fail;
- ctx = PK11_CreateContextBySymKey(mech, CKA_ENCRYPT, symkey, param);
- if(!ctx)
- goto fail;
-
+ param = PK11_ParamFromIV(mech, /* no IV in ECB mode */ NULL);
+ if(!param)
+ goto fail;
+ ctx = PK11_CreateContextBySymKey(mech, CKA_ENCRYPT, symkey, param);
+ if(!ctx)
+ goto fail;
+
/* Perform the encryption */
- if(SECSuccess == PK11_CipherOp(ctx, out, &out_len, /* outbuflen */ 8,
- (unsigned char *)in, /* inbuflen */ 8)
- && SECSuccess == PK11_Finalize(ctx))
- rv = /* all OK */ TRUE;
-
-fail:
- /* cleanup */
- if(ctx)
- PK11_DestroyContext(ctx, PR_TRUE);
- if(symkey)
- PK11_FreeSymKey(symkey);
- if(param)
- SECITEM_FreeItem(param, PR_TRUE);
- PK11_FreeSlot(slot);
- return rv;
-}
-
+ if(SECSuccess == PK11_CipherOp(ctx, out, &out_len, /* outbuflen */ 8,
+ (unsigned char *)in, /* inbuflen */ 8)
+ && SECSuccess == PK11_Finalize(ctx))
+ rv = /* all OK */ TRUE;
+
+fail:
+ /* cleanup */
+ if(ctx)
+ PK11_DestroyContext(ctx, PR_TRUE);
+ if(symkey)
+ PK11_FreeSymKey(symkey);
+ if(param)
+ SECITEM_FreeItem(param, PR_TRUE);
+ PK11_FreeSlot(slot);
+ return rv;
+}
+
#elif defined(USE_MBEDTLS)
static bool encrypt_des(const unsigned char *in, unsigned char *out,
@@ -281,36 +281,36 @@ static bool encrypt_des(const unsigned char *in, unsigned char *out,
}
#elif defined(USE_SECTRANSP)
-
-static bool encrypt_des(const unsigned char *in, unsigned char *out,
- const unsigned char *key_56)
-{
- char key[8];
- size_t out_len;
- CCCryptorStatus err;
-
+
+static bool encrypt_des(const unsigned char *in, unsigned char *out,
+ const unsigned char *key_56)
+{
+ char key[8];
+ size_t out_len;
+ CCCryptorStatus err;
+
/* Expand the 56-bit key to 64-bits */
- extend_key_56_to_64(key_56, key);
+ extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Perform the encryption */
- err = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key,
- kCCKeySizeDES, NULL, in, 8 /* inbuflen */, out,
- 8 /* outbuflen */, &out_len);
+ err = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key,
+ kCCKeySizeDES, NULL, in, 8 /* inbuflen */, out,
+ 8 /* outbuflen */, &out_len);
+
+ return err == kCCSuccess;
+}
- return err == kCCSuccess;
-}
-
#elif defined(USE_OS400CRYPTO)
-
+
static bool encrypt_des(const unsigned char *in, unsigned char *out,
const unsigned char *key_56)
{
char key[8];
_CIPHER_Control_T ctl;
-
+
/* Setup the cipher control structure */
ctl.Func_ID = ENCRYPT_ONLY;
ctl.Data_Len = sizeof(key);
@@ -379,141 +379,141 @@ static bool encrypt_des(const unsigned char *in, unsigned char *out,
#endif /* defined(USE_WIN32_CRYPTO) */
- /*
- * takes a 21 byte array and treats it as 3 56-bit DES keys. The
- * 8 byte plaintext is encrypted with each key and the resulting 24
- * bytes are stored in the results array.
- */
-void Curl_ntlm_core_lm_resp(const unsigned char *keys,
- const unsigned char *plaintext,
- unsigned char *results)
-{
+ /*
+ * takes a 21 byte array and treats it as 3 56-bit DES keys. The
+ * 8 byte plaintext is encrypted with each key and the resulting 24
+ * bytes are stored in the results array.
+ */
+void Curl_ntlm_core_lm_resp(const unsigned char *keys,
+ const unsigned char *plaintext,
+ unsigned char *results)
+{
#if defined(USE_OPENSSL) || defined(USE_WOLFSSL)
- DES_key_schedule ks;
-
- setup_des_key(keys, DESKEY(ks));
- DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results,
- DESKEY(ks), DES_ENCRYPT);
-
- setup_des_key(keys + 7, DESKEY(ks));
- DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8),
- DESKEY(ks), DES_ENCRYPT);
-
- setup_des_key(keys + 14, DESKEY(ks));
- DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16),
- DESKEY(ks), DES_ENCRYPT);
-#elif defined(USE_GNUTLS_NETTLE)
- struct des_ctx des;
- setup_des_key(keys, &des);
- des_encrypt(&des, 8, results, plaintext);
- setup_des_key(keys + 7, &des);
- des_encrypt(&des, 8, results + 8, plaintext);
- setup_des_key(keys + 14, &des);
- des_encrypt(&des, 8, results + 16, plaintext);
-#elif defined(USE_GNUTLS)
- gcry_cipher_hd_t des;
-
- gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
- setup_des_key(keys, &des);
- gcry_cipher_encrypt(des, results, 8, plaintext, 8);
- gcry_cipher_close(des);
-
- gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
- setup_des_key(keys + 7, &des);
- gcry_cipher_encrypt(des, results + 8, 8, plaintext, 8);
- gcry_cipher_close(des);
-
- gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
- setup_des_key(keys + 14, &des);
- gcry_cipher_encrypt(des, results + 16, 8, plaintext, 8);
- gcry_cipher_close(des);
+ DES_key_schedule ks;
+
+ setup_des_key(keys, DESKEY(ks));
+ DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results,
+ DESKEY(ks), DES_ENCRYPT);
+
+ setup_des_key(keys + 7, DESKEY(ks));
+ DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8),
+ DESKEY(ks), DES_ENCRYPT);
+
+ setup_des_key(keys + 14, DESKEY(ks));
+ DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16),
+ DESKEY(ks), DES_ENCRYPT);
+#elif defined(USE_GNUTLS_NETTLE)
+ struct des_ctx des;
+ setup_des_key(keys, &des);
+ des_encrypt(&des, 8, results, plaintext);
+ setup_des_key(keys + 7, &des);
+ des_encrypt(&des, 8, results + 8, plaintext);
+ setup_des_key(keys + 14, &des);
+ des_encrypt(&des, 8, results + 16, plaintext);
+#elif defined(USE_GNUTLS)
+ gcry_cipher_hd_t des;
+
+ gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
+ setup_des_key(keys, &des);
+ gcry_cipher_encrypt(des, results, 8, plaintext, 8);
+ gcry_cipher_close(des);
+
+ gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
+ setup_des_key(keys + 7, &des);
+ gcry_cipher_encrypt(des, results + 8, 8, plaintext, 8);
+ gcry_cipher_close(des);
+
+ gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
+ setup_des_key(keys + 14, &des);
+ gcry_cipher_encrypt(des, results + 16, 8, plaintext, 8);
+ gcry_cipher_close(des);
#elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \
|| defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
- encrypt_des(plaintext, results, keys);
- encrypt_des(plaintext, results + 8, keys + 7);
- encrypt_des(plaintext, results + 16, keys + 14);
-#endif
-}
-
-/*
- * Set up lanmanager hashed password
- */
+ encrypt_des(plaintext, results, keys);
+ encrypt_des(plaintext, results + 8, keys + 7);
+ encrypt_des(plaintext, results + 16, keys + 14);
+#endif
+}
+
+/*
+ * Set up lanmanager hashed password
+ */
CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data,
const char *password,
unsigned char *lmbuffer /* 21 bytes */)
-{
+{
CURLcode result;
- unsigned char pw[14];
- static const unsigned char magic[] = {
- 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */
- };
- size_t len = CURLMIN(strlen(password), 14);
-
- Curl_strntoupper((char *)pw, password, len);
- memset(&pw[len], 0, 14 - len);
-
- /*
- * The LanManager hashed password needs to be created using the
- * password in the network encoding not the host encoding.
- */
+ unsigned char pw[14];
+ static const unsigned char magic[] = {
+ 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */
+ };
+ size_t len = CURLMIN(strlen(password), 14);
+
+ Curl_strntoupper((char *)pw, password, len);
+ memset(&pw[len], 0, 14 - len);
+
+ /*
+ * The LanManager hashed password needs to be created using the
+ * password in the network encoding not the host encoding.
+ */
result = Curl_convert_to_network(data, (char *)pw, 14);
if(result)
return result;
-
- {
- /* Create LanManager hashed password. */
-
+
+ {
+ /* Create LanManager hashed password. */
+
#if defined(USE_OPENSSL) || defined(USE_WOLFSSL)
- DES_key_schedule ks;
-
- setup_des_key(pw, DESKEY(ks));
- DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer,
- DESKEY(ks), DES_ENCRYPT);
-
- setup_des_key(pw + 7, DESKEY(ks));
- DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8),
- DESKEY(ks), DES_ENCRYPT);
-#elif defined(USE_GNUTLS_NETTLE)
- struct des_ctx des;
- setup_des_key(pw, &des);
- des_encrypt(&des, 8, lmbuffer, magic);
- setup_des_key(pw + 7, &des);
- des_encrypt(&des, 8, lmbuffer + 8, magic);
-#elif defined(USE_GNUTLS)
- gcry_cipher_hd_t des;
-
- gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
- setup_des_key(pw, &des);
- gcry_cipher_encrypt(des, lmbuffer, 8, magic, 8);
- gcry_cipher_close(des);
-
- gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
- setup_des_key(pw + 7, &des);
- gcry_cipher_encrypt(des, lmbuffer + 8, 8, magic, 8);
- gcry_cipher_close(des);
+ DES_key_schedule ks;
+
+ setup_des_key(pw, DESKEY(ks));
+ DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer,
+ DESKEY(ks), DES_ENCRYPT);
+
+ setup_des_key(pw + 7, DESKEY(ks));
+ DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8),
+ DESKEY(ks), DES_ENCRYPT);
+#elif defined(USE_GNUTLS_NETTLE)
+ struct des_ctx des;
+ setup_des_key(pw, &des);
+ des_encrypt(&des, 8, lmbuffer, magic);
+ setup_des_key(pw + 7, &des);
+ des_encrypt(&des, 8, lmbuffer + 8, magic);
+#elif defined(USE_GNUTLS)
+ gcry_cipher_hd_t des;
+
+ gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
+ setup_des_key(pw, &des);
+ gcry_cipher_encrypt(des, lmbuffer, 8, magic, 8);
+ gcry_cipher_close(des);
+
+ gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0);
+ setup_des_key(pw + 7, &des);
+ gcry_cipher_encrypt(des, lmbuffer + 8, 8, magic, 8);
+ gcry_cipher_close(des);
#elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \
|| defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
- encrypt_des(magic, lmbuffer, pw);
- encrypt_des(magic, lmbuffer + 8, pw + 7);
-#endif
-
- memset(lmbuffer + 16, 0, 21 - 16);
- }
+ encrypt_des(magic, lmbuffer, pw);
+ encrypt_des(magic, lmbuffer + 8, pw + 7);
+#endif
+
+ memset(lmbuffer + 16, 0, 21 - 16);
+ }
return CURLE_OK;
-}
-
+}
+
#ifdef USE_NTRESPONSES
-static void ascii_to_unicode_le(unsigned char *dest, const char *src,
- size_t srclen)
-{
- size_t i;
- for(i = 0; i < srclen; i++) {
- dest[2 * i] = (unsigned char)src[i];
- dest[2 * i + 1] = '\0';
- }
-}
-
+static void ascii_to_unicode_le(unsigned char *dest, const char *src,
+ size_t srclen)
+{
+ size_t i;
+ for(i = 0; i < srclen; i++) {
+ dest[2 * i] = (unsigned char)src[i];
+ dest[2 * i + 1] = '\0';
+ }
+}
+
#if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI)
static void ascii_uppercase_to_unicode_le(unsigned char *dest,
@@ -528,42 +528,42 @@ static void ascii_uppercase_to_unicode_le(unsigned char *dest,
#endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */
-/*
- * Set up nt hashed passwords
+/*
+ * Set up nt hashed passwords
* @unittest: 1600
- */
+ */
CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data,
- const char *password,
- unsigned char *ntbuffer /* 21 bytes */)
-{
- size_t len = strlen(password);
+ const char *password,
+ unsigned char *ntbuffer /* 21 bytes */)
+{
+ size_t len = strlen(password);
unsigned char *pw;
- CURLcode result;
+ CURLcode result;
if(len > SIZE_T_MAX/2) /* avoid integer overflow */
return CURLE_OUT_OF_MEMORY;
pw = len ? malloc(len * 2) : (unsigned char *)strdup("");
- if(!pw)
- return CURLE_OUT_OF_MEMORY;
-
- ascii_to_unicode_le(pw, password, len);
-
- /*
- * The NT hashed password needs to be created using the password in the
- * network encoding not the host encoding.
- */
- result = Curl_convert_to_network(data, (char *)pw, len * 2);
- if(result)
- return result;
-
+ if(!pw)
+ return CURLE_OUT_OF_MEMORY;
+
+ ascii_to_unicode_le(pw, password, len);
+
+ /*
+ * The NT hashed password needs to be created using the password in the
+ * network encoding not the host encoding.
+ */
+ result = Curl_convert_to_network(data, (char *)pw, len * 2);
+ if(result)
+ return result;
+
/* Create NT hashed password. */
Curl_md4it(ntbuffer, pw, 2 * len);
-
+
memset(ntbuffer + 16, 0, 21 - 16);
-
- free(pw);
-
- return CURLE_OK;
-}
+
+ free(pw);
+
+ return CURLE_OK;
+}
#if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI)
@@ -736,6 +736,6 @@ CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash,
#endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */
-#endif /* USE_NTRESPONSES */
-
+#endif /* USE_NTRESPONSES */
+
#endif /* USE_CURL_NTLM_CORE */
diff --git a/contrib/libs/curl/lib/curl_ntlm_core.h b/contrib/libs/curl/lib/curl_ntlm_core.h
index 817ebe9462..0ed1b8d1e9 100644
--- a/contrib/libs/curl/lib/curl_ntlm_core.h
+++ b/contrib/libs/curl/lib/curl_ntlm_core.h
@@ -1,31 +1,31 @@
-#ifndef HEADER_CURL_NTLM_CORE_H
-#define HEADER_CURL_NTLM_CORE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_NTLM_CORE_H
+#define HEADER_CURL_NTLM_CORE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if defined(USE_CURL_NTLM_CORE)
-
+
/* If NSS is the first available SSL backend (see order in curl_ntlm_core.c)
then it must be initialized to be used by NTLM. */
#if !defined(USE_OPENSSL) && \
@@ -34,15 +34,15 @@
!defined(USE_GNUTLS) && \
defined(USE_NSS)
#define NTLM_NEEDS_NSS_INIT
-#endif
-
+#endif
+
#if defined(USE_OPENSSL) || defined(USE_WOLFSSL)
#ifdef USE_WOLFSSL
# error #include <wolfssl/options.h>
#endif
# include <openssl/ssl.h>
-#endif
-
+#endif
+
/* Define USE_NTRESPONSES in order to make the type-3 message include
* the NT response message. */
#define USE_NTRESPONSES
@@ -61,21 +61,21 @@
#define USE_NTLM_V2
#endif
-void Curl_ntlm_core_lm_resp(const unsigned char *keys,
- const unsigned char *plaintext,
- unsigned char *results);
-
+void Curl_ntlm_core_lm_resp(const unsigned char *keys,
+ const unsigned char *plaintext,
+ unsigned char *results);
+
CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data,
const char *password,
unsigned char *lmbuffer /* 21 bytes */);
-
+
#ifdef USE_NTRESPONSES
CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data,
- const char *password,
- unsigned char *ntbuffer /* 21 bytes */);
-
+ const char *password,
+ unsigned char *ntbuffer /* 21 bytes */);
+
#if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI)
-
+
CURLcode Curl_hmac_md5(const unsigned char *key, unsigned int keylen,
const unsigned char *data, unsigned int datalen,
unsigned char *output);
@@ -102,4 +102,4 @@ CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash,
#endif /* USE_CURL_NTLM_CORE */
-#endif /* HEADER_CURL_NTLM_CORE_H */
+#endif /* HEADER_CURL_NTLM_CORE_H */
diff --git a/contrib/libs/curl/lib/curl_ntlm_wb.c b/contrib/libs/curl/lib/curl_ntlm_wb.c
index b340f4c865..c11757f557 100644
--- a/contrib/libs/curl/lib/curl_ntlm_wb.c
+++ b/contrib/libs/curl/lib/curl_ntlm_wb.c
@@ -1,142 +1,142 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
-
-/*
- * NTLM details:
- *
+
+/*
+ * NTLM details:
+ *
* https://davenport.sourceforge.io/ntlm.html
* https://www.innovation.ch/java/ntlm.html
- */
-
-#define DEBUG_ME 0
-
-#ifdef HAVE_SYS_WAIT_H
-#include <sys/wait.h>
-#endif
-#ifdef HAVE_SIGNAL_H
-#include <signal.h>
-#endif
+ */
+
+#define DEBUG_ME 0
+
+#ifdef HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "select.h"
+
+#include "urldata.h"
+#include "sendf.h"
+#include "select.h"
#include "vauth/ntlm.h"
#include "curl_ntlm_core.h"
-#include "curl_ntlm_wb.h"
-#include "url.h"
-#include "strerror.h"
+#include "curl_ntlm_wb.h"
+#include "url.h"
+#include "strerror.h"
#include "strdup.h"
#include "strcase.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-#if DEBUG_ME
-# define DEBUG_OUT(x) x
-#else
-# define DEBUG_OUT(x) Curl_nop_stmt
-#endif
-
-/* Portable 'sclose_nolog' used only in child process instead of 'sclose'
- to avoid fooling the socket leak detector */
-#if defined(HAVE_CLOSESOCKET)
-# define sclose_nolog(x) closesocket((x))
-#elif defined(HAVE_CLOSESOCKET_CAMEL)
-# define sclose_nolog(x) CloseSocket((x))
-#else
-# define sclose_nolog(x) close((x))
-#endif
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#if DEBUG_ME
+# define DEBUG_OUT(x) x
+#else
+# define DEBUG_OUT(x) Curl_nop_stmt
+#endif
+
+/* Portable 'sclose_nolog' used only in child process instead of 'sclose'
+ to avoid fooling the socket leak detector */
+#if defined(HAVE_CLOSESOCKET)
+# define sclose_nolog(x) closesocket((x))
+#elif defined(HAVE_CLOSESOCKET_CAMEL)
+# define sclose_nolog(x) CloseSocket((x))
+#else
+# define sclose_nolog(x) close((x))
+#endif
+
static void ntlm_wb_cleanup(struct ntlmdata *ntlm)
-{
+{
if(ntlm->ntlm_auth_hlpr_socket != CURL_SOCKET_BAD) {
sclose(ntlm->ntlm_auth_hlpr_socket);
ntlm->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
- }
-
+ }
+
if(ntlm->ntlm_auth_hlpr_pid) {
- int i;
- for(i = 0; i < 4; i++) {
+ int i;
+ for(i = 0; i < 4; i++) {
pid_t ret = waitpid(ntlm->ntlm_auth_hlpr_pid, NULL, WNOHANG);
if(ret == ntlm->ntlm_auth_hlpr_pid || errno == ECHILD)
- break;
- switch(i) {
- case 0:
+ break;
+ switch(i) {
+ case 0:
kill(ntlm->ntlm_auth_hlpr_pid, SIGTERM);
- break;
- case 1:
- /* Give the process another moment to shut down cleanly before
- bringing down the axe */
- Curl_wait_ms(1);
- break;
- case 2:
+ break;
+ case 1:
+ /* Give the process another moment to shut down cleanly before
+ bringing down the axe */
+ Curl_wait_ms(1);
+ break;
+ case 2:
kill(ntlm->ntlm_auth_hlpr_pid, SIGKILL);
- break;
- case 3:
- break;
- }
- }
+ break;
+ case 3:
+ break;
+ }
+ }
ntlm->ntlm_auth_hlpr_pid = 0;
- }
-
+ }
+
Curl_safefree(ntlm->challenge);
Curl_safefree(ntlm->response);
-}
-
+}
+
static CURLcode ntlm_wb_init(struct Curl_easy *data, struct ntlmdata *ntlm,
const char *userp)
-{
- curl_socket_t sockfds[2];
- pid_t child_pid;
- const char *username;
- char *slash, *domain = NULL;
- const char *ntlm_auth = NULL;
- char *ntlm_auth_alloc = NULL;
+{
+ curl_socket_t sockfds[2];
+ pid_t child_pid;
+ const char *username;
+ char *slash, *domain = NULL;
+ const char *ntlm_auth = NULL;
+ char *ntlm_auth_alloc = NULL;
#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID)
struct passwd pw, *pw_res;
char pwbuf[1024];
#endif
char buffer[STRERROR_LEN];
-
+
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) data;
#endif
- /* Return if communication with ntlm_auth already set up */
+ /* Return if communication with ntlm_auth already set up */
if(ntlm->ntlm_auth_hlpr_socket != CURL_SOCKET_BAD ||
ntlm->ntlm_auth_hlpr_pid)
- return CURLE_OK;
-
- username = userp;
+ return CURLE_OK;
+
+ username = userp;
/* The real ntlm_auth really doesn't like being invoked with an
empty username. It won't make inferences for itself, and expects
the client to do so (mostly because it's really designed for
@@ -161,135 +161,135 @@ static CURLcode ntlm_wb_init(struct Curl_easy *data, struct ntlmdata *ntlm,
if(!username || !username[0])
username = userp;
}
- slash = strpbrk(username, "\\/");
- if(slash) {
+ slash = strpbrk(username, "\\/");
+ if(slash) {
domain = strdup(username);
if(!domain)
- return CURLE_OUT_OF_MEMORY;
- slash = domain + (slash - username);
- *slash = '\0';
- username = username + (slash - domain) + 1;
- }
-
- /* For testing purposes, when DEBUGBUILD is defined and environment
- variable CURL_NTLM_WB_FILE is set a fake_ntlm is used to perform
- NTLM challenge/response which only accepts commands and output
- strings pre-written in test case definitions */
-#ifdef DEBUGBUILD
- ntlm_auth_alloc = curl_getenv("CURL_NTLM_WB_FILE");
- if(ntlm_auth_alloc)
- ntlm_auth = ntlm_auth_alloc;
- else
-#endif
- ntlm_auth = NTLM_WB_FILE;
-
- if(access(ntlm_auth, X_OK) != 0) {
+ return CURLE_OUT_OF_MEMORY;
+ slash = domain + (slash - username);
+ *slash = '\0';
+ username = username + (slash - domain) + 1;
+ }
+
+ /* For testing purposes, when DEBUGBUILD is defined and environment
+ variable CURL_NTLM_WB_FILE is set a fake_ntlm is used to perform
+ NTLM challenge/response which only accepts commands and output
+ strings pre-written in test case definitions */
+#ifdef DEBUGBUILD
+ ntlm_auth_alloc = curl_getenv("CURL_NTLM_WB_FILE");
+ if(ntlm_auth_alloc)
+ ntlm_auth = ntlm_auth_alloc;
+ else
+#endif
+ ntlm_auth = NTLM_WB_FILE;
+
+ if(access(ntlm_auth, X_OK) != 0) {
failf(data, "Could not access ntlm_auth: %s errno %d: %s",
ntlm_auth, errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- goto done;
- }
-
+ goto done;
+ }
+
if(Curl_socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds)) {
failf(data, "Could not open socket pair. errno %d: %s",
errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- goto done;
- }
-
- child_pid = fork();
- if(child_pid == -1) {
- sclose(sockfds[0]);
- sclose(sockfds[1]);
+ goto done;
+ }
+
+ child_pid = fork();
+ if(child_pid == -1) {
+ sclose(sockfds[0]);
+ sclose(sockfds[1]);
failf(data, "Could not fork. errno %d: %s",
errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- goto done;
- }
- else if(!child_pid) {
- /*
- * child process
- */
-
- /* Don't use sclose in the child since it fools the socket leak detector */
- sclose_nolog(sockfds[0]);
- if(dup2(sockfds[1], STDIN_FILENO) == -1) {
+ goto done;
+ }
+ else if(!child_pid) {
+ /*
+ * child process
+ */
+
+ /* Don't use sclose in the child since it fools the socket leak detector */
+ sclose_nolog(sockfds[0]);
+ if(dup2(sockfds[1], STDIN_FILENO) == -1) {
failf(data, "Could not redirect child stdin. errno %d: %s",
errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- exit(1);
- }
-
- if(dup2(sockfds[1], STDOUT_FILENO) == -1) {
+ exit(1);
+ }
+
+ if(dup2(sockfds[1], STDOUT_FILENO) == -1) {
failf(data, "Could not redirect child stdout. errno %d: %s",
errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- exit(1);
- }
-
- if(domain)
- execl(ntlm_auth, ntlm_auth,
- "--helper-protocol", "ntlmssp-client-1",
- "--use-cached-creds",
- "--username", username,
- "--domain", domain,
- NULL);
- else
- execl(ntlm_auth, ntlm_auth,
- "--helper-protocol", "ntlmssp-client-1",
- "--use-cached-creds",
- "--username", username,
- NULL);
-
- sclose_nolog(sockfds[1]);
+ exit(1);
+ }
+
+ if(domain)
+ execl(ntlm_auth, ntlm_auth,
+ "--helper-protocol", "ntlmssp-client-1",
+ "--use-cached-creds",
+ "--username", username,
+ "--domain", domain,
+ NULL);
+ else
+ execl(ntlm_auth, ntlm_auth,
+ "--helper-protocol", "ntlmssp-client-1",
+ "--use-cached-creds",
+ "--username", username,
+ NULL);
+
+ sclose_nolog(sockfds[1]);
failf(data, "Could not execl(). errno %d: %s",
errno, Curl_strerror(errno, buffer, sizeof(buffer)));
- exit(1);
- }
-
- sclose(sockfds[1]);
+ exit(1);
+ }
+
+ sclose(sockfds[1]);
ntlm->ntlm_auth_hlpr_socket = sockfds[0];
ntlm->ntlm_auth_hlpr_pid = child_pid;
free(domain);
free(ntlm_auth_alloc);
- return CURLE_OK;
-
-done:
+ return CURLE_OK;
+
+done:
free(domain);
free(ntlm_auth_alloc);
- return CURLE_REMOTE_ACCESS_DENIED;
-}
-
+ return CURLE_REMOTE_ACCESS_DENIED;
+}
+
/* if larger than this, something is seriously wrong */
#define MAX_NTLM_WB_RESPONSE 100000
static CURLcode ntlm_wb_response(struct Curl_easy *data, struct ntlmdata *ntlm,
- const char *input, curlntlm state)
-{
+ const char *input, curlntlm state)
+{
size_t len_in = strlen(input), len_out = 0;
struct dynbuf b;
char *ptr = NULL;
unsigned char *buf = (unsigned char *)data->state.buffer;
Curl_dyn_init(&b, MAX_NTLM_WB_RESPONSE);
-
- while(len_in > 0) {
+
+ while(len_in > 0) {
ssize_t written = swrite(ntlm->ntlm_auth_hlpr_socket, input, len_in);
- if(written == -1) {
- /* Interrupted by a signal, retry it */
- if(errno == EINTR)
- continue;
- /* write failed if other errors happen */
- goto done;
- }
- input += written;
- len_in -= written;
- }
- /* Read one line */
+ if(written == -1) {
+ /* Interrupted by a signal, retry it */
+ if(errno == EINTR)
+ continue;
+ /* write failed if other errors happen */
+ goto done;
+ }
+ input += written;
+ len_in -= written;
+ }
+ /* Read one line */
while(1) {
ssize_t size =
sread(ntlm->ntlm_auth_hlpr_socket, buf, data->set.buffer_size);
- if(size == -1) {
- if(errno == EINTR)
- continue;
- goto done;
- }
- else if(size == 0)
- goto done;
+ if(size == -1) {
+ if(errno == EINTR)
+ continue;
+ goto done;
+ }
+ else if(size == 0)
+ goto done;
if(Curl_dyn_addn(&b, buf, size))
goto done;
@@ -301,34 +301,34 @@ static CURLcode ntlm_wb_response(struct Curl_easy *data, struct ntlmdata *ntlm,
break; /* done! */
}
/* loop */
- }
+ }
- /* Samba/winbind installed but not configured */
- if(state == NTLMSTATE_TYPE1 &&
+ /* Samba/winbind installed but not configured */
+ if(state == NTLMSTATE_TYPE1 &&
len_out == 3 &&
ptr[0] == 'P' && ptr[1] == 'W')
goto done;
- /* invalid response */
+ /* invalid response */
if(len_out < 4)
- goto done;
- if(state == NTLMSTATE_TYPE1 &&
+ goto done;
+ if(state == NTLMSTATE_TYPE1 &&
(ptr[0]!='Y' || ptr[1]!='R' || ptr[2]!=' '))
- goto done;
- if(state == NTLMSTATE_TYPE2 &&
+ goto done;
+ if(state == NTLMSTATE_TYPE2 &&
(ptr[0]!='K' || ptr[1]!='K' || ptr[2]!=' ') &&
(ptr[0]!='A' || ptr[1]!='F' || ptr[2]!=' '))
- goto done;
-
+ goto done;
+
ntlm->response = strdup(ptr + 3);
Curl_dyn_free(&b);
if(!ntlm->response)
return CURLE_OUT_OF_MEMORY;
- return CURLE_OK;
-done:
+ return CURLE_OK;
+done:
Curl_dyn_free(&b);
- return CURLE_REMOTE_ACCESS_DENIED;
-}
-
+ return CURLE_REMOTE_ACCESS_DENIED;
+}
+
CURLcode Curl_input_ntlm_wb(struct connectdata *conn,
bool proxy,
const char *header)
@@ -372,119 +372,119 @@ CURLcode Curl_input_ntlm_wb(struct connectdata *conn,
return CURLE_OK;
}
-/*
- * This is for creating ntlm header output by delegating challenge/response
- * to Samba's winbind daemon helper ntlm_auth.
- */
+/*
+ * This is for creating ntlm header output by delegating challenge/response
+ * to Samba's winbind daemon helper ntlm_auth.
+ */
CURLcode Curl_output_ntlm_wb(struct connectdata *conn, bool proxy)
-{
- /* point to the address of the pointer that holds the string to send to the
- server, which is for a plain host or for a HTTP proxy */
- char **allocuserpwd;
- /* point to the name and password for this */
- const char *userp;
+{
+ /* point to the address of the pointer that holds the string to send to the
+ server, which is for a plain host or for a HTTP proxy */
+ char **allocuserpwd;
+ /* point to the name and password for this */
+ const char *userp;
struct ntlmdata *ntlm;
curlntlm *state;
- struct auth *authp;
+ struct auth *authp;
struct Curl_easy *data = conn->data;
-
- CURLcode res = CURLE_OK;
-
- DEBUGASSERT(conn);
- DEBUGASSERT(conn->data);
-
- if(proxy) {
+
+ CURLcode res = CURLE_OK;
+
+ DEBUGASSERT(conn);
+ DEBUGASSERT(conn->data);
+
+ if(proxy) {
#ifndef CURL_DISABLE_PROXY
allocuserpwd = &data->state.aptr.proxyuserpwd;
userp = conn->http_proxy.user;
ntlm = &conn->proxyntlm;
state = &conn->proxy_ntlm_state;
- authp = &conn->data->state.authproxy;
+ authp = &conn->data->state.authproxy;
#else
return CURLE_NOT_BUILT_IN;
#endif
- }
- else {
+ }
+ else {
allocuserpwd = &data->state.aptr.userpwd;
- userp = conn->user;
+ userp = conn->user;
ntlm = &conn->ntlm;
state = &conn->http_ntlm_state;
- authp = &conn->data->state.authhost;
- }
- authp->done = FALSE;
-
- /* not set means empty */
- if(!userp)
+ authp = &conn->data->state.authhost;
+ }
+ authp->done = FALSE;
+
+ /* not set means empty */
+ if(!userp)
userp = "";
-
+
switch(*state) {
- case NTLMSTATE_TYPE1:
- default:
- /* Use Samba's 'winbind' daemon to support NTLM authentication,
+ case NTLMSTATE_TYPE1:
+ default:
+ /* Use Samba's 'winbind' daemon to support NTLM authentication,
* by delegating the NTLM challenge/response protocol to a helper
- * in ntlm_auth.
- * http://devel.squid-cache.org/ntlm/squid_helper_protocol.html
+ * in ntlm_auth.
+ * http://devel.squid-cache.org/ntlm/squid_helper_protocol.html
* https://www.samba.org/samba/docs/man/manpages-3/winbindd.8.html
* https://www.samba.org/samba/docs/man/manpages-3/ntlm_auth.1.html
- * Preprocessor symbol 'NTLM_WB_ENABLED' is defined when this
- * feature is enabled and 'NTLM_WB_FILE' symbol holds absolute
- * filename of ntlm_auth helper.
- * If NTLM authentication using winbind fails, go back to original
- * request handling process.
- */
- /* Create communication with ntlm_auth */
+ * Preprocessor symbol 'NTLM_WB_ENABLED' is defined when this
+ * feature is enabled and 'NTLM_WB_FILE' symbol holds absolute
+ * filename of ntlm_auth helper.
+ * If NTLM authentication using winbind fails, go back to original
+ * request handling process.
+ */
+ /* Create communication with ntlm_auth */
res = ntlm_wb_init(conn->data, ntlm, userp);
- if(res)
- return res;
+ if(res)
+ return res;
res = ntlm_wb_response(conn->data, ntlm, "YR\n", *state);
- if(res)
- return res;
-
+ if(res)
+ return res;
+
free(*allocuserpwd);
*allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n",
- proxy ? "Proxy-" : "",
+ proxy ? "Proxy-" : "",
ntlm->response);
- DEBUG_OUT(fprintf(stderr, "**** Header %s\n ", *allocuserpwd));
+ DEBUG_OUT(fprintf(stderr, "**** Header %s\n ", *allocuserpwd));
Curl_safefree(ntlm->response);
if(!*allocuserpwd)
return CURLE_OUT_OF_MEMORY;
- break;
+ break;
case NTLMSTATE_TYPE2: {
char *input = aprintf("TT %s\n", ntlm->challenge);
- if(!input)
- return CURLE_OUT_OF_MEMORY;
+ if(!input)
+ return CURLE_OUT_OF_MEMORY;
res = ntlm_wb_response(conn->data, ntlm, input, *state);
- free(input);
- if(res)
- return res;
-
+ free(input);
+ if(res)
+ return res;
+
free(*allocuserpwd);
*allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n",
- proxy ? "Proxy-" : "",
+ proxy ? "Proxy-" : "",
ntlm->response);
- DEBUG_OUT(fprintf(stderr, "**** %s\n ", *allocuserpwd));
+ DEBUG_OUT(fprintf(stderr, "**** %s\n ", *allocuserpwd));
*state = NTLMSTATE_TYPE3; /* we sent a type-3 */
- authp->done = TRUE;
+ authp->done = TRUE;
Curl_http_auth_cleanup_ntlm_wb(conn);
if(!*allocuserpwd)
return CURLE_OUT_OF_MEMORY;
- break;
+ break;
}
- case NTLMSTATE_TYPE3:
- /* connection is already authenticated,
- * don't send a header in future requests */
+ case NTLMSTATE_TYPE3:
+ /* connection is already authenticated,
+ * don't send a header in future requests */
*state = NTLMSTATE_LAST;
/* FALLTHROUGH */
case NTLMSTATE_LAST:
Curl_safefree(*allocuserpwd);
- authp->done = TRUE;
- break;
- }
-
- return CURLE_OK;
-}
-
+ authp->done = TRUE;
+ break;
+ }
+
+ return CURLE_OK;
+}
+
void Curl_http_auth_cleanup_ntlm_wb(struct connectdata *conn)
{
ntlm_wb_cleanup(&conn->ntlm);
diff --git a/contrib/libs/curl/lib/curl_ntlm_wb.h b/contrib/libs/curl/lib/curl_ntlm_wb.h
index be7b6dc199..4f847d22ca 100644
--- a/contrib/libs/curl/lib/curl_ntlm_wb.h
+++ b/contrib/libs/curl/lib/curl_ntlm_wb.h
@@ -1,41 +1,41 @@
-#ifndef HEADER_CURL_NTLM_WB_H
-#define HEADER_CURL_NTLM_WB_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_NTLM_WB_H
+#define HEADER_CURL_NTLM_WB_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
-
+
/* this is for ntlm header input */
CURLcode Curl_input_ntlm_wb(struct connectdata *conn, bool proxy,
const char *header);
/* this is for creating ntlm header output */
-CURLcode Curl_output_ntlm_wb(struct connectdata *conn, bool proxy);
-
+CURLcode Curl_output_ntlm_wb(struct connectdata *conn, bool proxy);
+
void Curl_http_auth_cleanup_ntlm_wb(struct connectdata *conn);
-
+
#endif /* !CURL_DISABLE_HTTP && USE_NTLM && NTLM_WB_ENABLED */
-
-#endif /* HEADER_CURL_NTLM_WB_H */
+
+#endif /* HEADER_CURL_NTLM_WB_H */
diff --git a/contrib/libs/curl/lib/curl_rtmp.c b/contrib/libs/curl/lib/curl_rtmp.c
index a77a4a3ff3..ba471a2a19 100644
--- a/contrib/libs/curl/lib/curl_rtmp.c
+++ b/contrib/libs/curl/lib/curl_rtmp.c
@@ -1,322 +1,322 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- * Copyright (C) 2010, Howard Chu, <hyc@highlandsun.com>
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ * Copyright (C) 2010, Howard Chu, <hyc@highlandsun.com>
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef USE_LIBRTMP
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef USE_LIBRTMP
+
#include "curl_rtmp.h"
-#include "urldata.h"
-#include "nonblock.h" /* for curlx_nonblock */
-#include "progress.h" /* for Curl_pgrsSetUploadSize */
-#include "transfer.h"
-#include "warnless.h"
-#include <curl/curl.h>
-#include <librtmp/rtmp.h>
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
+#include "urldata.h"
+#include "nonblock.h" /* for curlx_nonblock */
+#include "progress.h" /* for Curl_pgrsSetUploadSize */
+#include "transfer.h"
+#include "warnless.h"
+#include <curl/curl.h>
+#include <librtmp/rtmp.h>
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
#if defined(WIN32) && !defined(USE_LWIPSOCK)
-#define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e)
-#define SET_RCVTIMEO(tv,s) int tv = s*1000
+#define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e)
+#define SET_RCVTIMEO(tv,s) int tv = s*1000
#elif defined(LWIP_SO_SNDRCVTIMEO_NONSTANDARD)
#define SET_RCVTIMEO(tv,s) int tv = s*1000
-#else
-#define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0}
-#endif
-
-#define DEF_BUFTIME (2*60*60*1000) /* 2 hours */
-
+#else
+#define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0}
+#endif
+
+#define DEF_BUFTIME (2*60*60*1000) /* 2 hours */
+
static CURLcode rtmp_setup_connection(struct connectdata *conn);
-static CURLcode rtmp_do(struct connectdata *conn, bool *done);
-static CURLcode rtmp_done(struct connectdata *conn, CURLcode, bool premature);
-static CURLcode rtmp_connect(struct connectdata *conn, bool *done);
-static CURLcode rtmp_disconnect(struct connectdata *conn, bool dead);
-
-static Curl_recv rtmp_recv;
-static Curl_send rtmp_send;
-
-/*
+static CURLcode rtmp_do(struct connectdata *conn, bool *done);
+static CURLcode rtmp_done(struct connectdata *conn, CURLcode, bool premature);
+static CURLcode rtmp_connect(struct connectdata *conn, bool *done);
+static CURLcode rtmp_disconnect(struct connectdata *conn, bool dead);
+
+static Curl_recv rtmp_recv;
+static Curl_send rtmp_send;
+
+/*
* RTMP protocol handler.h, based on https://rtmpdump.mplayerhq.hu
- */
-
-const struct Curl_handler Curl_handler_rtmp = {
- "RTMP", /* scheme */
+ */
+
+const struct Curl_handler Curl_handler_rtmp = {
+ "RTMP", /* scheme */
rtmp_setup_connection, /* setup_connection */
- rtmp_do, /* do_it */
- rtmp_done, /* done */
- ZERO_NULL, /* do_more */
- rtmp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtmp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ rtmp_do, /* do_it */
+ rtmp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtmp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtmp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_RTMP, /* defport */
- CURLPROTO_RTMP, /* protocol */
+ PORT_RTMP, /* defport */
+ CURLPROTO_RTMP, /* protocol */
CURLPROTO_RTMP, /* family */
- PROTOPT_NONE /* flags*/
-};
-
-const struct Curl_handler Curl_handler_rtmpt = {
- "RTMPT", /* scheme */
+ PROTOPT_NONE /* flags*/
+};
+
+const struct Curl_handler Curl_handler_rtmpt = {
+ "RTMPT", /* scheme */
rtmp_setup_connection, /* setup_connection */
- rtmp_do, /* do_it */
- rtmp_done, /* done */
- ZERO_NULL, /* do_more */
- rtmp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtmp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ rtmp_do, /* do_it */
+ rtmp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtmp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtmp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_RTMPT, /* defport */
- CURLPROTO_RTMPT, /* protocol */
+ PORT_RTMPT, /* defport */
+ CURLPROTO_RTMPT, /* protocol */
CURLPROTO_RTMPT, /* family */
- PROTOPT_NONE /* flags*/
-};
-
-const struct Curl_handler Curl_handler_rtmpe = {
- "RTMPE", /* scheme */
+ PROTOPT_NONE /* flags*/
+};
+
+const struct Curl_handler Curl_handler_rtmpe = {
+ "RTMPE", /* scheme */
rtmp_setup_connection, /* setup_connection */
- rtmp_do, /* do_it */
- rtmp_done, /* done */
- ZERO_NULL, /* do_more */
- rtmp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtmp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ rtmp_do, /* do_it */
+ rtmp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtmp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtmp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_RTMP, /* defport */
- CURLPROTO_RTMPE, /* protocol */
+ PORT_RTMP, /* defport */
+ CURLPROTO_RTMPE, /* protocol */
CURLPROTO_RTMPE, /* family */
- PROTOPT_NONE /* flags*/
-};
-
-const struct Curl_handler Curl_handler_rtmpte = {
- "RTMPTE", /* scheme */
+ PROTOPT_NONE /* flags*/
+};
+
+const struct Curl_handler Curl_handler_rtmpte = {
+ "RTMPTE", /* scheme */
rtmp_setup_connection, /* setup_connection */
- rtmp_do, /* do_it */
- rtmp_done, /* done */
- ZERO_NULL, /* do_more */
- rtmp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtmp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ rtmp_do, /* do_it */
+ rtmp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtmp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtmp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_RTMPT, /* defport */
- CURLPROTO_RTMPTE, /* protocol */
+ PORT_RTMPT, /* defport */
+ CURLPROTO_RTMPTE, /* protocol */
CURLPROTO_RTMPTE, /* family */
- PROTOPT_NONE /* flags*/
-};
-
-const struct Curl_handler Curl_handler_rtmps = {
- "RTMPS", /* scheme */
+ PROTOPT_NONE /* flags*/
+};
+
+const struct Curl_handler Curl_handler_rtmps = {
+ "RTMPS", /* scheme */
rtmp_setup_connection, /* setup_connection */
- rtmp_do, /* do_it */
- rtmp_done, /* done */
- ZERO_NULL, /* do_more */
- rtmp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtmp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ rtmp_do, /* do_it */
+ rtmp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtmp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtmp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_RTMPS, /* defport */
- CURLPROTO_RTMPS, /* protocol */
+ PORT_RTMPS, /* defport */
+ CURLPROTO_RTMPS, /* protocol */
CURLPROTO_RTMP, /* family */
- PROTOPT_NONE /* flags*/
-};
-
-const struct Curl_handler Curl_handler_rtmpts = {
- "RTMPTS", /* scheme */
+ PROTOPT_NONE /* flags*/
+};
+
+const struct Curl_handler Curl_handler_rtmpts = {
+ "RTMPTS", /* scheme */
rtmp_setup_connection, /* setup_connection */
- rtmp_do, /* do_it */
- rtmp_done, /* done */
- ZERO_NULL, /* do_more */
- rtmp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtmp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ rtmp_do, /* do_it */
+ rtmp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtmp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtmp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_RTMPS, /* defport */
- CURLPROTO_RTMPTS, /* protocol */
+ PORT_RTMPS, /* defport */
+ CURLPROTO_RTMPTS, /* protocol */
CURLPROTO_RTMPT, /* family */
- PROTOPT_NONE /* flags*/
-};
-
+ PROTOPT_NONE /* flags*/
+};
+
static CURLcode rtmp_setup_connection(struct connectdata *conn)
-{
- RTMP *r = RTMP_Alloc();
- if(!r)
- return CURLE_OUT_OF_MEMORY;
-
- RTMP_Init(r);
- RTMP_SetBufferMS(r, DEF_BUFTIME);
- if(!RTMP_SetupURL(r, conn->data->change.url)) {
- RTMP_Free(r);
- return CURLE_URL_MALFORMAT;
- }
+{
+ RTMP *r = RTMP_Alloc();
+ if(!r)
+ return CURLE_OUT_OF_MEMORY;
+
+ RTMP_Init(r);
+ RTMP_SetBufferMS(r, DEF_BUFTIME);
+ if(!RTMP_SetupURL(r, conn->data->change.url)) {
+ RTMP_Free(r);
+ return CURLE_URL_MALFORMAT;
+ }
conn->proto.rtmp = r;
- return CURLE_OK;
-}
-
-static CURLcode rtmp_connect(struct connectdata *conn, bool *done)
-{
+ return CURLE_OK;
+}
+
+static CURLcode rtmp_connect(struct connectdata *conn, bool *done)
+{
RTMP *r = conn->proto.rtmp;
SET_RCVTIMEO(tv, 10);
-
+
r->m_sb.sb_socket = (int)conn->sock[FIRSTSOCKET];
-
- /* We have to know if it's a write before we send the
- * connect request packet
- */
- if(conn->data->set.upload)
- r->Link.protocol |= RTMP_FEATURE_WRITE;
-
- /* For plain streams, use the buffer toggle trick to keep data flowing */
- if(!(r->Link.lFlags & RTMP_LF_LIVE) &&
- !(r->Link.protocol & RTMP_FEATURE_HTTP))
- r->Link.lFlags |= RTMP_LF_BUFX;
-
+
+ /* We have to know if it's a write before we send the
+ * connect request packet
+ */
+ if(conn->data->set.upload)
+ r->Link.protocol |= RTMP_FEATURE_WRITE;
+
+ /* For plain streams, use the buffer toggle trick to keep data flowing */
+ if(!(r->Link.lFlags & RTMP_LF_LIVE) &&
+ !(r->Link.protocol & RTMP_FEATURE_HTTP))
+ r->Link.lFlags |= RTMP_LF_BUFX;
+
(void)curlx_nonblock(r->m_sb.sb_socket, FALSE);
- setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO,
- (char *)&tv, sizeof(tv));
-
- if(!RTMP_Connect1(r, NULL))
- return CURLE_FAILED_INIT;
-
- /* Clients must send a periodic BytesReceived report to the server */
- r->m_bSendCounter = true;
-
- *done = TRUE;
- conn->recv[FIRSTSOCKET] = rtmp_recv;
- conn->send[FIRSTSOCKET] = rtmp_send;
- return CURLE_OK;
-}
-
-static CURLcode rtmp_do(struct connectdata *conn, bool *done)
-{
+ setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO,
+ (char *)&tv, sizeof(tv));
+
+ if(!RTMP_Connect1(r, NULL))
+ return CURLE_FAILED_INIT;
+
+ /* Clients must send a periodic BytesReceived report to the server */
+ r->m_bSendCounter = true;
+
+ *done = TRUE;
+ conn->recv[FIRSTSOCKET] = rtmp_recv;
+ conn->send[FIRSTSOCKET] = rtmp_send;
+ return CURLE_OK;
+}
+
+static CURLcode rtmp_do(struct connectdata *conn, bool *done)
+{
struct Curl_easy *data = conn->data;
RTMP *r = conn->proto.rtmp;
-
- if(!RTMP_ConnectStream(r, 0))
- return CURLE_FAILED_INIT;
-
- if(conn->data->set.upload) {
+
+ if(!RTMP_ConnectStream(r, 0))
+ return CURLE_FAILED_INIT;
+
+ if(conn->data->set.upload) {
Curl_pgrsSetUploadSize(data, data->state.infilesize);
Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET);
- }
- else
+ }
+ else
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
- *done = TRUE;
- return CURLE_OK;
-}
-
-static CURLcode rtmp_done(struct connectdata *conn, CURLcode status,
- bool premature)
-{
- (void)conn; /* unused */
- (void)status; /* unused */
- (void)premature; /* unused */
-
- return CURLE_OK;
-}
-
-static CURLcode rtmp_disconnect(struct connectdata *conn,
- bool dead_connection)
-{
+ *done = TRUE;
+ return CURLE_OK;
+}
+
+static CURLcode rtmp_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
+ (void)conn; /* unused */
+ (void)status; /* unused */
+ (void)premature; /* unused */
+
+ return CURLE_OK;
+}
+
+static CURLcode rtmp_disconnect(struct connectdata *conn,
+ bool dead_connection)
+{
RTMP *r = conn->proto.rtmp;
- (void)dead_connection;
- if(r) {
+ (void)dead_connection;
+ if(r) {
conn->proto.rtmp = NULL;
- RTMP_Close(r);
- RTMP_Free(r);
- }
- return CURLE_OK;
-}
-
-static ssize_t rtmp_recv(struct connectdata *conn, int sockindex, char *buf,
- size_t len, CURLcode *err)
-{
+ RTMP_Close(r);
+ RTMP_Free(r);
+ }
+ return CURLE_OK;
+}
+
+static ssize_t rtmp_recv(struct connectdata *conn, int sockindex, char *buf,
+ size_t len, CURLcode *err)
+{
RTMP *r = conn->proto.rtmp;
- ssize_t nread;
-
- (void)sockindex; /* unused */
-
- nread = RTMP_Read(r, buf, curlx_uztosi(len));
- if(nread < 0) {
- if(r->m_read.status == RTMP_READ_COMPLETE ||
- r->m_read.status == RTMP_READ_EOF) {
- conn->data->req.size = conn->data->req.bytecount;
- nread = 0;
- }
- else
- *err = CURLE_RECV_ERROR;
- }
- return nread;
-}
-
-static ssize_t rtmp_send(struct connectdata *conn, int sockindex,
- const void *buf, size_t len, CURLcode *err)
-{
+ ssize_t nread;
+
+ (void)sockindex; /* unused */
+
+ nread = RTMP_Read(r, buf, curlx_uztosi(len));
+ if(nread < 0) {
+ if(r->m_read.status == RTMP_READ_COMPLETE ||
+ r->m_read.status == RTMP_READ_EOF) {
+ conn->data->req.size = conn->data->req.bytecount;
+ nread = 0;
+ }
+ else
+ *err = CURLE_RECV_ERROR;
+ }
+ return nread;
+}
+
+static ssize_t rtmp_send(struct connectdata *conn, int sockindex,
+ const void *buf, size_t len, CURLcode *err)
+{
RTMP *r = conn->proto.rtmp;
- ssize_t num;
-
- (void)sockindex; /* unused */
-
- num = RTMP_Write(r, (char *)buf, curlx_uztosi(len));
- if(num < 0)
- *err = CURLE_SEND_ERROR;
-
- return num;
-}
-#endif /* USE_LIBRTMP */
+ ssize_t num;
+
+ (void)sockindex; /* unused */
+
+ num = RTMP_Write(r, (char *)buf, curlx_uztosi(len));
+ if(num < 0)
+ *err = CURLE_SEND_ERROR;
+
+ return num;
+}
+#endif /* USE_LIBRTMP */
diff --git a/contrib/libs/curl/lib/curl_rtmp.h b/contrib/libs/curl/lib/curl_rtmp.h
index 1e8b4564a0..f45fa71d12 100644
--- a/contrib/libs/curl/lib/curl_rtmp.h
+++ b/contrib/libs/curl/lib/curl_rtmp.h
@@ -1,33 +1,33 @@
-#ifndef HEADER_CURL_RTMP_H
-#define HEADER_CURL_RTMP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_RTMP_H
+#define HEADER_CURL_RTMP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2010 - 2020, Howard Chu, <hyc@highlandsun.com>
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifdef USE_LIBRTMP
-extern const struct Curl_handler Curl_handler_rtmp;
-extern const struct Curl_handler Curl_handler_rtmpt;
-extern const struct Curl_handler Curl_handler_rtmpe;
-extern const struct Curl_handler Curl_handler_rtmpte;
-extern const struct Curl_handler Curl_handler_rtmps;
-extern const struct Curl_handler Curl_handler_rtmpts;
-#endif
-
-#endif /* HEADER_CURL_RTMP_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifdef USE_LIBRTMP
+extern const struct Curl_handler Curl_handler_rtmp;
+extern const struct Curl_handler Curl_handler_rtmpt;
+extern const struct Curl_handler Curl_handler_rtmpe;
+extern const struct Curl_handler Curl_handler_rtmpte;
+extern const struct Curl_handler Curl_handler_rtmps;
+extern const struct Curl_handler Curl_handler_rtmpts;
+#endif
+
+#endif /* HEADER_CURL_RTMP_H */
diff --git a/contrib/libs/curl/lib/curl_sasl.c b/contrib/libs/curl/lib/curl_sasl.c
index e4ff4c1131..94b17a1d86 100644
--- a/contrib/libs/curl/lib/curl_sasl.c
+++ b/contrib/libs/curl/lib/curl_sasl.c
@@ -1,57 +1,57 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * RFC2195 CRAM-MD5 authentication
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * RFC2195 CRAM-MD5 authentication
* RFC2617 Basic and Digest Access Authentication
- * RFC2831 DIGEST-MD5 authentication
- * RFC4422 Simple Authentication and Security Layer (SASL)
- * RFC4616 PLAIN authentication
- * RFC6749 OAuth 2.0 Authorization Framework
+ * RFC2831 DIGEST-MD5 authentication
+ * RFC4422 Simple Authentication and Security Layer (SASL)
+ * RFC4616 PLAIN authentication
+ * RFC6749 OAuth 2.0 Authorization Framework
* RFC7628 A Set of SASL Mechanisms for OAuth
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \
!defined(CURL_DISABLE_POP3)
-#include <curl/curl.h>
-#include "urldata.h"
-
-#include "curl_base64.h"
-#include "curl_md5.h"
+#include <curl/curl.h>
+#include "urldata.h"
+
+#include "curl_base64.h"
+#include "curl_md5.h"
#include "vauth/vauth.h"
#include "vtls/vtls.h"
-#include "curl_hmac.h"
-#include "curl_sasl.h"
-#include "warnless.h"
+#include "curl_hmac.h"
+#include "curl_sasl.h"
+#include "warnless.h"
#include "strtok.h"
#include "sendf.h"
#include "non-ascii.h" /* included for Curl_convert_... prototypes */
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
/* Supported mechanisms */
static const struct {
const char *name; /* Name */
@@ -69,59 +69,59 @@ static const struct {
{ "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER },
{ ZERO_NULL, 0, 0 }
};
-
-/*
+
+/*
* Curl_sasl_cleanup()
- *
+ *
* This is used to cleanup any libraries or curl modules used by the sasl
* functions.
- *
- * Parameters:
- *
+ *
+ * Parameters:
+ *
* conn [in] - The connection data.
* authused [in] - The authentication mechanism used.
- */
+ */
void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused)
-{
+{
#if defined(USE_KERBEROS5)
/* Cleanup the gssapi structure */
if(authused == SASL_MECH_GSSAPI) {
Curl_auth_cleanup_gssapi(&conn->krb5);
}
#endif
-
+
#if defined(USE_NTLM)
/* Cleanup the NTLM structure */
if(authused == SASL_MECH_NTLM) {
Curl_auth_cleanup_ntlm(&conn->ntlm);
- }
+ }
#endif
-
+
#if !defined(USE_KERBEROS5) && !defined(USE_NTLM)
/* Reserved for future use */
(void)conn;
(void)authused;
#endif
-}
-
-/*
+}
+
+/*
* Curl_sasl_decode_mech()
- *
+ *
* Convert a SASL mechanism name into a token.
- *
- * Parameters:
- *
+ *
+ * Parameters:
+ *
* ptr [in] - The mechanism string.
* maxlen [in] - Maximum mechanism string length.
* len [out] - If not NULL, effective name length.
- *
+ *
* Returns the SASL mechanism token or 0 if no match.
- */
+ */
unsigned int Curl_sasl_decode_mech(const char *ptr, size_t maxlen, size_t *len)
-{
+{
unsigned int i;
char c;
-
+
for(i = 0; mechtable[i].name; i++) {
if(maxlen >= mechtable[i].len &&
!memcmp(ptr, mechtable[i].name, mechtable[i].len)) {
@@ -134,31 +134,31 @@ unsigned int Curl_sasl_decode_mech(const char *ptr, size_t maxlen, size_t *len)
c = ptr[mechtable[i].len];
if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_')
return mechtable[i].bit;
- }
- }
-
+ }
+ }
+
return 0;
-}
-
-/*
+}
+
+/*
* Curl_sasl_parse_url_auth_option()
- *
+ *
* Parse the URL login options.
- */
+ */
CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl,
const char *value, size_t len)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
size_t mechlen;
-
+
if(!len)
return CURLE_URL_MALFORMAT;
-
+
if(sasl->resetprefs) {
sasl->resetprefs = FALSE;
sasl->prefmech = SASL_AUTH_NONE;
- }
-
+ }
+
if(!strncmp(value, "*", len))
sasl->prefmech = SASL_AUTH_DEFAULT;
else {
@@ -167,11 +167,11 @@ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl,
sasl->prefmech |= mechbit;
else
result = CURLE_URL_MALFORMAT;
- }
-
+ }
+
return result;
}
-
+
/*
* Curl_sasl_init()
*
@@ -188,7 +188,7 @@ void Curl_sasl_init(struct SASL *sasl, const struct SASLproto *params)
sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */
sasl->force_ir = FALSE; /* Respect external option */
}
-
+
/*
* state()
*
@@ -219,35 +219,35 @@ static void state(struct SASL *sasl, struct connectdata *conn,
"FINAL",
/* LAST */
};
-
+
if(sasl->state != newstate)
infof(conn->data, "SASL %p state change from %s to %s\n",
(void *)sasl, names[sasl->state], names[newstate]);
#else
(void) conn;
#endif
-
+
sasl->state = newstate;
-}
-
-/*
+}
+
+/*
* Curl_sasl_can_authenticate()
- *
+ *
* Check if we have enough auth data and capabilities to authenticate.
- */
+ */
bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn)
-{
+{
/* Have credentials been provided? */
if(conn->bits.user_passwd)
return TRUE;
-
+
/* EXTERNAL can authenticate without a user name and/or password */
if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL)
return TRUE;
-
+
return FALSE;
}
-
+
/*
* Curl_sasl_start()
*
@@ -278,23 +278,23 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
sasl->params->service;
#endif
const char *oauth_bearer = data->set.str[STRING_BEARER];
-
+
sasl->force_ir = force_ir; /* Latch for future use */
sasl->authused = 0; /* No mechanism used yet */
enabledmechs = sasl->authmechs & sasl->prefmech;
*progress = SASL_IDLE;
-
+
/* Calculate the supported authentication mechanism, by decreasing order of
security, as well as the initial response where appropriate */
if((enabledmechs & SASL_MECH_EXTERNAL) && !conn->passwd[0]) {
mech = SASL_MECH_STRING_EXTERNAL;
state1 = SASL_EXTERNAL;
sasl->authused = SASL_MECH_EXTERNAL;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_external_message(data, conn->user, &resp,
&len);
- }
+ }
else if(conn->bits.user_passwd) {
#if defined(USE_KERBEROS5)
if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() &&
@@ -304,7 +304,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
state1 = SASL_GSSAPI;
state2 = SASL_GSSAPI_TOKEN;
sasl->authused = SASL_MECH_GSSAPI;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_gssapi_user_message(data, conn->user,
conn->passwd,
@@ -336,7 +336,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
state1 = SASL_NTLM;
state2 = SASL_NTLM_TYPE2MSG;
sasl->authused = SASL_MECH_NTLM;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_ntlm_type1_message(data,
conn->user, conn->passwd,
@@ -352,7 +352,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
state1 = SASL_OAUTH2;
state2 = SASL_OAUTH2_RESP;
sasl->authused = SASL_MECH_OAUTHBEARER;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_oauth_bearer_message(data, conn->user,
hostname,
@@ -364,7 +364,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
mech = SASL_MECH_STRING_XOAUTH2;
state1 = SASL_OAUTH2;
sasl->authused = SASL_MECH_XOAUTH2;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_xoauth_bearer_message(data, conn->user,
oauth_bearer,
@@ -374,7 +374,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
mech = SASL_MECH_STRING_PLAIN;
state1 = SASL_PLAIN;
sasl->authused = SASL_MECH_PLAIN;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_plain_message(data, conn->sasl_authzid,
conn->user, conn->passwd,
@@ -385,31 +385,31 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
state1 = SASL_LOGIN;
state2 = SASL_LOGIN_PASSWD;
sasl->authused = SASL_MECH_LOGIN;
-
+
if(force_ir || data->set.sasl_ir)
result = Curl_auth_create_login_message(data, conn->user, &resp, &len);
}
}
-
+
if(!result && mech) {
if(resp && sasl->params->maxirlen &&
strlen(mech) + len > sasl->params->maxirlen) {
free(resp);
resp = NULL;
}
-
+
result = sasl->params->sendauth(conn, mech, resp);
if(!result) {
*progress = SASL_INPROGRESS;
state(sasl, conn, resp ? state2 : state1);
}
}
-
+
free(resp);
-
+
return result;
}
-
+
/*
* Curl_sasl_continue()
*
@@ -443,9 +443,9 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
#endif
size_t len = 0;
const char *oauth_bearer = data->set.str[STRING_BEARER];
-
+
*progress = SASL_INPROGRESS;
-
+
if(sasl->state == SASL_FINAL) {
if(code != sasl->params->finalcode)
result = CURLE_LOGIN_DENIED;
@@ -453,14 +453,14 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
state(sasl, conn, SASL_STOP);
return result;
}
-
+
if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP &&
code != sasl->params->contcode) {
*progress = SASL_DONE;
state(sasl, conn, SASL_STOP);
return CURLE_LOGIN_DENIED;
}
-
+
switch(sasl->state) {
case SASL_STOP:
*progress = SASL_DONE;
@@ -480,7 +480,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
case SASL_EXTERNAL:
result = Curl_auth_create_external_message(data, conn->user, &resp, &len);
break;
-
+
#ifndef CURL_DISABLE_CRYPTO_AUTH
case SASL_CRAMMD5:
sasl->params->getmessage(data->state.buffer, &serverdata);
@@ -504,7 +504,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
result = CURLE_OUT_OF_MEMORY;
break;
#endif
-
+
#ifdef USE_NTLM
case SASL_NTLM:
/* Create the type-1 message */
@@ -525,7 +525,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
&resp, &len);
break;
#endif
-
+
#if defined(USE_KERBEROS5)
case SASL_GSSAPI:
result = Curl_auth_create_gssapi_user_message(data, conn->user,
@@ -562,8 +562,8 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
&conn->krb5,
&resp, &len);
break;
-#endif
-
+#endif
+
case SASL_OAUTH2:
/* Create the authorisation message */
if(sasl->authused == SASL_MECH_OAUTHBEARER) {
@@ -572,7 +572,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
port,
oauth_bearer,
&resp, &len);
-
+
/* Failures maybe sent by the server as continuations for OAUTHBEARER */
newstate = SASL_OAUTH2_RESP;
}
@@ -581,7 +581,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
oauth_bearer,
&resp, &len);
break;
-
+
case SASL_OAUTH2_RESP:
/* The continuation is optional so check the response code */
if(code == sasl->params->finalcode) {
@@ -603,11 +603,11 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
state(sasl, conn, SASL_STOP);
return CURLE_LOGIN_DENIED;
}
-
+
case SASL_CANCEL:
/* Remove the offending mechanism from the supported list */
sasl->authmechs ^= sasl->authused;
-
+
/* Start an alternative SASL authentication */
result = Curl_sasl_start(sasl, conn, sasl->force_ir, progress);
newstate = sasl->state; /* Use state from Curl_sasl_start() */
@@ -617,7 +617,7 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */
break;
}
-
+
switch(result) {
case CURLE_BAD_CONTENT_ENCODING:
/* Cancel dialog */
@@ -633,11 +633,11 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
*progress = SASL_DONE;
break;
}
-
+
free(resp);
-
+
state(sasl, conn, newstate);
-
+
return result;
-}
+}
#endif /* protocols are enabled that use SASL */
diff --git a/contrib/libs/curl/lib/curl_sasl.h b/contrib/libs/curl/lib/curl_sasl.h
index 9e4c1b8eee..ba40ec461a 100644
--- a/contrib/libs/curl/lib/curl_sasl.h
+++ b/contrib/libs/curl/lib/curl_sasl.h
@@ -1,49 +1,49 @@
-#ifndef HEADER_CURL_SASL_H
-#define HEADER_CURL_SASL_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SASL_H
+#define HEADER_CURL_SASL_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include <curl/curl.h>
-
+
struct Curl_easy;
struct connectdata;
-
-/* Authentication mechanism flags */
-#define SASL_MECH_LOGIN (1 << 0)
-#define SASL_MECH_PLAIN (1 << 1)
-#define SASL_MECH_CRAM_MD5 (1 << 2)
-#define SASL_MECH_DIGEST_MD5 (1 << 3)
-#define SASL_MECH_GSSAPI (1 << 4)
-#define SASL_MECH_EXTERNAL (1 << 5)
-#define SASL_MECH_NTLM (1 << 6)
-#define SASL_MECH_XOAUTH2 (1 << 7)
+
+/* Authentication mechanism flags */
+#define SASL_MECH_LOGIN (1 << 0)
+#define SASL_MECH_PLAIN (1 << 1)
+#define SASL_MECH_CRAM_MD5 (1 << 2)
+#define SASL_MECH_DIGEST_MD5 (1 << 3)
+#define SASL_MECH_GSSAPI (1 << 4)
+#define SASL_MECH_EXTERNAL (1 << 5)
+#define SASL_MECH_NTLM (1 << 6)
+#define SASL_MECH_XOAUTH2 (1 << 7)
#define SASL_MECH_OAUTHBEARER (1 << 8)
-
+
/* Authentication mechanism values */
#define SASL_AUTH_NONE 0
#define SASL_AUTH_ANY ~0U
#define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & ~SASL_MECH_EXTERNAL)
-/* Authentication mechanism strings */
+/* Authentication mechanism strings */
#define SASL_MECH_STRING_LOGIN "LOGIN"
#define SASL_MECH_STRING_PLAIN "PLAIN"
#define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5"
@@ -53,7 +53,7 @@ struct connectdata;
#define SASL_MECH_STRING_NTLM "NTLM"
#define SASL_MECH_STRING_XOAUTH2 "XOAUTH2"
#define SASL_MECH_STRING_OAUTHBEARER "OAUTHBEARER"
-
+
/* SASL machine states */
typedef enum {
SASL_STOP,
@@ -109,35 +109,35 @@ struct SASL {
bool force_ir; /* Protocol always supports initial response */
};
-/* This is used to test whether the line starts with the given mechanism */
-#define sasl_mech_equal(line, wordlen, mech) \
- (wordlen == (sizeof(mech) - 1) / sizeof(char) && \
- !memcmp(line, mech, wordlen))
-
+/* This is used to test whether the line starts with the given mechanism */
+#define sasl_mech_equal(line, wordlen, mech) \
+ (wordlen == (sizeof(mech) - 1) / sizeof(char) && \
+ !memcmp(line, mech, wordlen))
+
/* This is used to cleanup any libraries or curl modules used by the sasl
functions */
void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused);
-
+
/* Convert a mechanism name to a token */
unsigned int Curl_sasl_decode_mech(const char *ptr,
size_t maxlen, size_t *len);
-
+
/* Parse the URL login options */
CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl,
const char *value, size_t len);
-
+
/* Initializes an SASL structure */
void Curl_sasl_init(struct SASL *sasl, const struct SASLproto *params);
-
+
/* Check if we have enough auth data and capabilities to authenticate */
bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn);
-
+
/* Calculate the required login details for SASL authentication */
CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
bool force_ir, saslprogress *progress);
-
+
/* Continue an SASL authentication */
CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
int code, saslprogress *progress);
-
-#endif /* HEADER_CURL_SASL_H */
+
+#endif /* HEADER_CURL_SASL_H */
diff --git a/contrib/libs/curl/lib/curl_setup.h b/contrib/libs/curl/lib/curl_setup.h
index fb152c4359..83fabb0e01 100644
--- a/contrib/libs/curl/lib/curl_setup.h
+++ b/contrib/libs/curl/lib/curl_setup.h
@@ -1,32 +1,32 @@
-#ifndef HEADER_CURL_SETUP_H
-#define HEADER_CURL_SETUP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SETUP_H
+#define HEADER_CURL_SETUP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#if defined(BUILDING_LIBCURL) && !defined(CURL_NO_OLDIES)
#define CURL_NO_OLDIES
#endif
-/*
+/*
* Disable Visual Studio warnings:
* 4127 "conditional expression is constant"
*/
@@ -35,15 +35,15 @@
#endif
/*
- * Define WIN32 when build target is Win32 API
- */
-
+ * Define WIN32 when build target is Win32 API
+ */
+
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
-#define WIN32
-#endif
-
+#define WIN32
+#endif
+
#ifdef WIN32
-/*
+/*
* Don't include unneeded stuff in Windows headers to avoid compiler
* warnings and macro clashes.
* Make sure to define this macro before including any Windows headers.
@@ -57,86 +57,86 @@
#endif
/*
- * Include configuration script results or hand-crafted
- * configuration file for platforms which lack config tool.
- */
-
-#ifdef HAVE_CONFIG_H
-
-#include "curl_config.h"
-
-#else /* HAVE_CONFIG_H */
-
-#ifdef _WIN32_WCE
-# include "config-win32ce.h"
-#else
-# ifdef WIN32
-# include "config-win32.h"
-# endif
-#endif
-
-#if defined(macintosh) && defined(__MRC__)
-# include "config-mac.h"
-#endif
-
-#ifdef __riscos__
-# include "config-riscos.h"
-#endif
-
-#ifdef __AMIGA__
-# include "config-amigaos.h"
-#endif
-
-#ifdef __OS400__
-# include "config-os400.h"
-#endif
-
-#ifdef TPF
-# include "config-tpf.h"
-#endif
-
-#ifdef __VXWORKS__
-# include "config-vxworks.h"
-#endif
-
+ * Include configuration script results or hand-crafted
+ * configuration file for platforms which lack config tool.
+ */
+
+#ifdef HAVE_CONFIG_H
+
+#include "curl_config.h"
+
+#else /* HAVE_CONFIG_H */
+
+#ifdef _WIN32_WCE
+# include "config-win32ce.h"
+#else
+# ifdef WIN32
+# include "config-win32.h"
+# endif
+#endif
+
+#if defined(macintosh) && defined(__MRC__)
+# include "config-mac.h"
+#endif
+
+#ifdef __riscos__
+# include "config-riscos.h"
+#endif
+
+#ifdef __AMIGA__
+# include "config-amigaos.h"
+#endif
+
+#ifdef __OS400__
+# include "config-os400.h"
+#endif
+
+#ifdef TPF
+# include "config-tpf.h"
+#endif
+
+#ifdef __VXWORKS__
+# include "config-vxworks.h"
+#endif
+
#ifdef __PLAN9__
# include "config-plan9.h"
#endif
-#endif /* HAVE_CONFIG_H */
-
-/* ================================================================ */
-/* Definition of preprocessor macros/symbols which modify compiler */
-/* behavior or generated code characteristics must be done here, */
-/* as appropriate, before any system header file is included. It is */
-/* also possible to have them defined in the config file included */
-/* before this point. As a result of all this we frown inclusion of */
-/* system header files in our config files, avoid this at any cost. */
-/* ================================================================ */
-
-/*
- * AIX 4.3 and newer needs _THREAD_SAFE defined to build
- * proper reentrant code. Others may also need it.
- */
-
-#ifdef NEED_THREAD_SAFE
-# ifndef _THREAD_SAFE
-# define _THREAD_SAFE
-# endif
-#endif
-
-/*
- * Tru64 needs _REENTRANT set for a few function prototypes and
- * things to appear in the system header files. Unixware needs it
- * to build proper reentrant code. Others may also need it.
- */
-
-#ifdef NEED_REENTRANT
-# ifndef _REENTRANT
-# define _REENTRANT
-# endif
-#endif
-
+#endif /* HAVE_CONFIG_H */
+
+/* ================================================================ */
+/* Definition of preprocessor macros/symbols which modify compiler */
+/* behavior or generated code characteristics must be done here, */
+/* as appropriate, before any system header file is included. It is */
+/* also possible to have them defined in the config file included */
+/* before this point. As a result of all this we frown inclusion of */
+/* system header files in our config files, avoid this at any cost. */
+/* ================================================================ */
+
+/*
+ * AIX 4.3 and newer needs _THREAD_SAFE defined to build
+ * proper reentrant code. Others may also need it.
+ */
+
+#ifdef NEED_THREAD_SAFE
+# ifndef _THREAD_SAFE
+# define _THREAD_SAFE
+# endif
+#endif
+
+/*
+ * Tru64 needs _REENTRANT set for a few function prototypes and
+ * things to appear in the system header files. Unixware needs it
+ * to build proper reentrant code. Others may also need it.
+ */
+
+#ifdef NEED_REENTRANT
+# ifndef _REENTRANT
+# define _REENTRANT
+# endif
+#endif
+
/* Solaris needs this to get a POSIX-conformant getpwuid_r */
#if defined(sun) || defined(__sun)
# ifndef _POSIX_PTHREAD_SEMANTICS
@@ -144,135 +144,135 @@
# endif
#endif
-/* ================================================================ */
-/* If you need to include a system header file for your platform, */
-/* please, do it beyond the point further indicated in this file. */
-/* ================================================================ */
-
+/* ================================================================ */
+/* If you need to include a system header file for your platform, */
+/* please, do it beyond the point further indicated in this file. */
+/* ================================================================ */
+
#include <curl/curl.h>
-
+
#define CURL_SIZEOF_CURL_OFF_T SIZEOF_CURL_OFF_T
-
-/*
- * Disable other protocols when http is the only one desired.
- */
-
-#ifdef HTTP_ONLY
-# ifndef CURL_DISABLE_TFTP
-# define CURL_DISABLE_TFTP
-# endif
-# ifndef CURL_DISABLE_FTP
-# define CURL_DISABLE_FTP
-# endif
-# ifndef CURL_DISABLE_LDAP
-# define CURL_DISABLE_LDAP
-# endif
-# ifndef CURL_DISABLE_TELNET
-# define CURL_DISABLE_TELNET
-# endif
-# ifndef CURL_DISABLE_DICT
-# define CURL_DISABLE_DICT
-# endif
-# ifndef CURL_DISABLE_FILE
-# define CURL_DISABLE_FILE
-# endif
-# ifndef CURL_DISABLE_RTSP
-# define CURL_DISABLE_RTSP
-# endif
-# ifndef CURL_DISABLE_POP3
-# define CURL_DISABLE_POP3
-# endif
-# ifndef CURL_DISABLE_IMAP
-# define CURL_DISABLE_IMAP
-# endif
-# ifndef CURL_DISABLE_SMTP
-# define CURL_DISABLE_SMTP
-# endif
-# ifndef CURL_DISABLE_GOPHER
-# define CURL_DISABLE_GOPHER
-# endif
+
+/*
+ * Disable other protocols when http is the only one desired.
+ */
+
+#ifdef HTTP_ONLY
+# ifndef CURL_DISABLE_TFTP
+# define CURL_DISABLE_TFTP
+# endif
+# ifndef CURL_DISABLE_FTP
+# define CURL_DISABLE_FTP
+# endif
+# ifndef CURL_DISABLE_LDAP
+# define CURL_DISABLE_LDAP
+# endif
+# ifndef CURL_DISABLE_TELNET
+# define CURL_DISABLE_TELNET
+# endif
+# ifndef CURL_DISABLE_DICT
+# define CURL_DISABLE_DICT
+# endif
+# ifndef CURL_DISABLE_FILE
+# define CURL_DISABLE_FILE
+# endif
+# ifndef CURL_DISABLE_RTSP
+# define CURL_DISABLE_RTSP
+# endif
+# ifndef CURL_DISABLE_POP3
+# define CURL_DISABLE_POP3
+# endif
+# ifndef CURL_DISABLE_IMAP
+# define CURL_DISABLE_IMAP
+# endif
+# ifndef CURL_DISABLE_SMTP
+# define CURL_DISABLE_SMTP
+# endif
+# ifndef CURL_DISABLE_GOPHER
+# define CURL_DISABLE_GOPHER
+# endif
# ifndef CURL_DISABLE_SMB
# define CURL_DISABLE_SMB
# endif
-#endif
-
-/*
- * When http is disabled rtsp is not supported.
- */
-
-#if defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_RTSP)
-# define CURL_DISABLE_RTSP
-#endif
-
-/* ================================================================ */
-/* No system header file shall be included in this file before this */
+#endif
+
+/*
+ * When http is disabled rtsp is not supported.
+ */
+
+#if defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_RTSP)
+# define CURL_DISABLE_RTSP
+#endif
+
+/* ================================================================ */
+/* No system header file shall be included in this file before this */
/* point. The only allowed ones are those included from curl/system.h */
-/* ================================================================ */
-
-/*
- * OS/400 setup file includes some system headers.
- */
-
-#ifdef __OS400__
-# include "setup-os400.h"
-#endif
-
-/*
- * VMS setup file includes some system headers.
- */
-
-#ifdef __VMS
-# include "setup-vms.h"
-#endif
-
-/*
+/* ================================================================ */
+
+/*
+ * OS/400 setup file includes some system headers.
+ */
+
+#ifdef __OS400__
+# include "setup-os400.h"
+#endif
+
+/*
+ * VMS setup file includes some system headers.
+ */
+
+#ifdef __VMS
+# include "setup-vms.h"
+#endif
+
+/*
* Windows setup file includes some system headers.
*/
-#ifdef HAVE_WINDOWS_H
+#ifdef HAVE_WINDOWS_H
# include "setup-win32.h"
-#endif
-
-/*
+#endif
+
+/*
* Use getaddrinfo to resolve the IPv4 address literal. If the current network
* interface doesn't support IPv4, but supports IPv6, NAT64, and DNS64,
* performing this task will result in a synthesized IPv6 address.
- */
+ */
#if defined(__APPLE__) && !defined(USE_ARES)
#define USE_RESOLVE_ON_IPS 1
-#endif
-
-#ifdef USE_LWIPSOCK
-# include <lwip/init.h>
-# include <lwip/sockets.h>
-# include <lwip/netdb.h>
-#endif
-
-#ifdef HAVE_EXTRA_STRICMP_H
-# include <extra/stricmp.h>
-#endif
-
-#ifdef HAVE_EXTRA_STRDUP_H
-# include <extra/strdup.h>
-#endif
-
-#ifdef TPF
-# include <strings.h> /* for bzero, strcasecmp, and strncasecmp */
-# include <string.h> /* for strcpy and strlen */
-# include <stdlib.h> /* for rand and srand */
-# include <sys/socket.h> /* for select and ioctl*/
-# include <netdb.h> /* for in_addr_t definition */
-# include <tpf/sysapi.h> /* for tpf_process_signals */
- /* change which select is used for libcurl */
-# define select(a,b,c,d,e) tpf_select_libcurl(a,b,c,d,e)
-#endif
-
-#ifdef __VXWORKS__
-# include <sockLib.h> /* for generic BSD socket functions */
-# include <ioLib.h> /* for basic I/O interface functions */
-#endif
-
-#ifdef __AMIGA__
+#endif
+
+#ifdef USE_LWIPSOCK
+# include <lwip/init.h>
+# include <lwip/sockets.h>
+# include <lwip/netdb.h>
+#endif
+
+#ifdef HAVE_EXTRA_STRICMP_H
+# include <extra/stricmp.h>
+#endif
+
+#ifdef HAVE_EXTRA_STRDUP_H
+# include <extra/strdup.h>
+#endif
+
+#ifdef TPF
+# include <strings.h> /* for bzero, strcasecmp, and strncasecmp */
+# include <string.h> /* for strcpy and strlen */
+# include <stdlib.h> /* for rand and srand */
+# include <sys/socket.h> /* for select and ioctl*/
+# include <netdb.h> /* for in_addr_t definition */
+# include <tpf/sysapi.h> /* for tpf_process_signals */
+ /* change which select is used for libcurl */
+# define select(a,b,c,d,e) tpf_select_libcurl(a,b,c,d,e)
+#endif
+
+#ifdef __VXWORKS__
+# include <sockLib.h> /* for generic BSD socket functions */
+# include <ioLib.h> /* for basic I/O interface functions */
+#endif
+
+#ifdef __AMIGA__
# include <exec/types.h>
# include <exec/execbase.h>
# include <proto/exec.h>
@@ -280,131 +280,131 @@
# include <unistd.h>
# ifdef HAVE_PROTO_BSDSOCKET_H
# error #include <proto/bsdsocket.h> /* ensure bsdsocket.library use */
-# define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0)
-# endif
+# define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0)
+# endif
/*
* In clib2 arpa/inet.h warns that some prototypes may clash
* with bsdsocket.library. This avoids the definition of those.
*/
# define __NO_NET_API
-#endif
-
-#include <stdio.h>
-#ifdef HAVE_ASSERT_H
-#include <assert.h>
-#endif
-
-#ifdef __TANDEM /* for nsr-tandem-nsk systems */
-#include <floss.h>
-#endif
-
-#ifndef STDC_HEADERS /* no standard C headers! */
-#include <curl/stdcheaders.h>
-#endif
-
-#ifdef __POCC__
-# include <sys/types.h>
-# include <unistd.h>
-# define sys_nerr EILSEQ
-#endif
-
-/*
- * Salford-C kludge section (mostly borrowed from wxWidgets).
- */
-#ifdef __SALFORDC__
- #pragma suppress 353 /* Possible nested comments */
- #pragma suppress 593 /* Define not used */
- #pragma suppress 61 /* enum has no name */
- #pragma suppress 106 /* unnamed, unused parameter */
- #include <clib.h>
-#endif
-
-/*
- * Large file (>2Gb) support using WIN32 functions.
- */
-
-#ifdef USE_WIN32_LARGE_FILES
-# include <io.h>
-# include <sys/types.h>
-# include <sys/stat.h>
-# undef lseek
-# define lseek(fdes,offset,whence) _lseeki64(fdes, offset, whence)
-# undef fstat
-# define fstat(fdes,stp) _fstati64(fdes, stp)
-# undef stat
+#endif
+
+#include <stdio.h>
+#ifdef HAVE_ASSERT_H
+#include <assert.h>
+#endif
+
+#ifdef __TANDEM /* for nsr-tandem-nsk systems */
+#include <floss.h>
+#endif
+
+#ifndef STDC_HEADERS /* no standard C headers! */
+#include <curl/stdcheaders.h>
+#endif
+
+#ifdef __POCC__
+# include <sys/types.h>
+# include <unistd.h>
+# define sys_nerr EILSEQ
+#endif
+
+/*
+ * Salford-C kludge section (mostly borrowed from wxWidgets).
+ */
+#ifdef __SALFORDC__
+ #pragma suppress 353 /* Possible nested comments */
+ #pragma suppress 593 /* Define not used */
+ #pragma suppress 61 /* enum has no name */
+ #pragma suppress 106 /* unnamed, unused parameter */
+ #include <clib.h>
+#endif
+
+/*
+ * Large file (>2Gb) support using WIN32 functions.
+ */
+
+#ifdef USE_WIN32_LARGE_FILES
+# include <io.h>
+# include <sys/types.h>
+# include <sys/stat.h>
+# undef lseek
+# define lseek(fdes,offset,whence) _lseeki64(fdes, offset, whence)
+# undef fstat
+# define fstat(fdes,stp) _fstati64(fdes, stp)
+# undef stat
# define stat(fname,stp) curlx_win32_stat(fname, stp)
-# define struct_stat struct _stati64
-# define LSEEK_ERROR (__int64)-1
+# define struct_stat struct _stati64
+# define LSEEK_ERROR (__int64)-1
# define fopen(fname,mode) curlx_win32_fopen(fname, mode)
# define access(fname,mode) curlx_win32_access(fname, mode)
int curlx_win32_stat(const char *path, struct_stat *buffer);
FILE *curlx_win32_fopen(const char *filename, const char *mode);
int curlx_win32_access(const char *path, int mode);
-#endif
-
-/*
- * Small file (<2Gb) support using WIN32 functions.
- */
-
-#ifdef USE_WIN32_SMALL_FILES
-# include <io.h>
-# include <sys/types.h>
-# include <sys/stat.h>
-# ifndef _WIN32_WCE
-# undef lseek
-# define lseek(fdes,offset,whence) _lseek(fdes, (long)offset, whence)
-# define fstat(fdes,stp) _fstat(fdes, stp)
+#endif
+
+/*
+ * Small file (<2Gb) support using WIN32 functions.
+ */
+
+#ifdef USE_WIN32_SMALL_FILES
+# include <io.h>
+# include <sys/types.h>
+# include <sys/stat.h>
+# ifndef _WIN32_WCE
+# undef lseek
+# define lseek(fdes,offset,whence) _lseek(fdes, (long)offset, whence)
+# define fstat(fdes,stp) _fstat(fdes, stp)
# define stat(fname,stp) curlx_win32_stat(fname, stp)
-# define struct_stat struct _stat
+# define struct_stat struct _stat
# define fopen(fname,mode) curlx_win32_fopen(fname, mode)
# define access(fname,mode) curlx_win32_access(fname, mode)
int curlx_win32_stat(const char *path, struct_stat *buffer);
FILE *curlx_win32_fopen(const char *filename, const char *mode);
int curlx_win32_access(const char *path, int mode);
-# endif
-# define LSEEK_ERROR (long)-1
-#endif
-
-#ifndef struct_stat
-# define struct_stat struct stat
-#endif
-
-#ifndef LSEEK_ERROR
-# define LSEEK_ERROR (off_t)-1
-#endif
-
+# endif
+# define LSEEK_ERROR (long)-1
+#endif
+
+#ifndef struct_stat
+# define struct_stat struct stat
+#endif
+
+#ifndef LSEEK_ERROR
+# define LSEEK_ERROR (off_t)-1
+#endif
+
#ifndef SIZEOF_TIME_T
/* assume default size of time_t to be 32 bit */
#define SIZEOF_TIME_T 4
#endif
-/*
- * Default sizeof(off_t) in case it hasn't been defined in config file.
- */
-
-#ifndef SIZEOF_OFF_T
-# if defined(__VMS) && !defined(__VAX)
-# if defined(_LARGEFILE)
-# define SIZEOF_OFF_T 8
-# endif
-# elif defined(__OS400__) && defined(__ILEC400__)
-# if defined(_LARGE_FILES)
-# define SIZEOF_OFF_T 8
-# endif
-# elif defined(__MVS__) && defined(__IBMC__)
-# if defined(_LP64) || defined(_LARGE_FILES)
-# define SIZEOF_OFF_T 8
-# endif
-# elif defined(__370__) && defined(__IBMC__)
-# if defined(_LP64) || defined(_LARGE_FILES)
-# define SIZEOF_OFF_T 8
-# endif
-# endif
-# ifndef SIZEOF_OFF_T
-# define SIZEOF_OFF_T 4
-# endif
-#endif
-
+/*
+ * Default sizeof(off_t) in case it hasn't been defined in config file.
+ */
+
+#ifndef SIZEOF_OFF_T
+# if defined(__VMS) && !defined(__VAX)
+# if defined(_LARGEFILE)
+# define SIZEOF_OFF_T 8
+# endif
+# elif defined(__OS400__) && defined(__ILEC400__)
+# if defined(_LARGE_FILES)
+# define SIZEOF_OFF_T 8
+# endif
+# elif defined(__MVS__) && defined(__IBMC__)
+# if defined(_LP64) || defined(_LARGE_FILES)
+# define SIZEOF_OFF_T 8
+# endif
+# elif defined(__370__) && defined(__IBMC__)
+# if defined(_LP64) || defined(_LARGE_FILES)
+# define SIZEOF_OFF_T 8
+# endif
+# endif
+# ifndef SIZEOF_OFF_T
+# define SIZEOF_OFF_T 4
+# endif
+#endif
+
#if (SIZEOF_CURL_OFF_T == 4)
# define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFF)
#else
@@ -440,188 +440,188 @@
#endif
#endif
-/*
- * Arg 2 type for gethostname in case it hasn't been defined in config file.
- */
-
-#ifndef GETHOSTNAME_TYPE_ARG2
-# ifdef USE_WINSOCK
-# define GETHOSTNAME_TYPE_ARG2 int
-# else
-# define GETHOSTNAME_TYPE_ARG2 size_t
-# endif
-#endif
-
-/* Below we define some functions. They should
-
- 4. set the SIGALRM signal timeout
- 5. set dir/file naming defines
- */
-
-#ifdef WIN32
-
-# define DIR_CHAR "\\"
-
-#else /* WIN32 */
-
-# ifdef MSDOS /* Watt-32 */
-
-# include <sys/ioctl.h>
-# define select(n,r,w,x,t) select_s(n,r,w,x,t)
-# define ioctl(x,y,z) ioctlsocket(x,y,(char *)(z))
-# include <tcp.h>
-# ifdef word
-# undef word
-# endif
-# ifdef byte
-# undef byte
-# endif
-
-# endif /* MSDOS */
-
-# ifdef __minix
- /* Minix 3 versions up to at least 3.1.3 are missing these prototypes */
+/*
+ * Arg 2 type for gethostname in case it hasn't been defined in config file.
+ */
+
+#ifndef GETHOSTNAME_TYPE_ARG2
+# ifdef USE_WINSOCK
+# define GETHOSTNAME_TYPE_ARG2 int
+# else
+# define GETHOSTNAME_TYPE_ARG2 size_t
+# endif
+#endif
+
+/* Below we define some functions. They should
+
+ 4. set the SIGALRM signal timeout
+ 5. set dir/file naming defines
+ */
+
+#ifdef WIN32
+
+# define DIR_CHAR "\\"
+
+#else /* WIN32 */
+
+# ifdef MSDOS /* Watt-32 */
+
+# include <sys/ioctl.h>
+# define select(n,r,w,x,t) select_s(n,r,w,x,t)
+# define ioctl(x,y,z) ioctlsocket(x,y,(char *)(z))
+# include <tcp.h>
+# ifdef word
+# undef word
+# endif
+# ifdef byte
+# undef byte
+# endif
+
+# endif /* MSDOS */
+
+# ifdef __minix
+ /* Minix 3 versions up to at least 3.1.3 are missing these prototypes */
extern char *strtok_r(char *s, const char *delim, char **last);
extern struct tm *gmtime_r(const time_t * const timep, struct tm *tmp);
-# endif
-
-# define DIR_CHAR "/"
-
-# ifndef fileno /* sunos 4 have this as a macro! */
+# endif
+
+# define DIR_CHAR "/"
+
+# ifndef fileno /* sunos 4 have this as a macro! */
int fileno(FILE *stream);
-# endif
-
-#endif /* WIN32 */
-
-/*
- * msvc 6.0 requires PSDK in order to have INET6_ADDRSTRLEN
- * defined in ws2tcpip.h as well as to provide IPv6 support.
+# endif
+
+#endif /* WIN32 */
+
+/*
+ * msvc 6.0 requires PSDK in order to have INET6_ADDRSTRLEN
+ * defined in ws2tcpip.h as well as to provide IPv6 support.
* Does not apply if lwIP is used.
- */
-
+ */
+
#if defined(_MSC_VER) && !defined(__POCC__) && !defined(USE_LWIPSOCK)
-# if !defined(HAVE_WS2TCPIP_H) || \
- ((_MSC_VER < 1300) && !defined(INET6_ADDRSTRLEN))
-# undef HAVE_GETADDRINFO_THREADSAFE
-# undef HAVE_FREEADDRINFO
-# undef HAVE_GETADDRINFO
-# undef HAVE_GETNAMEINFO
-# undef ENABLE_IPV6
-# endif
-#endif
-
-/* ---------------------------------------------------------------- */
-/* resolver specialty compile-time defines */
-/* CURLRES_* defines to use in the host*.c sources */
-/* ---------------------------------------------------------------- */
-
-/*
- * lcc-win32 doesn't have _beginthreadex(), lacks threads support.
- */
-
-#if defined(__LCC__) && defined(WIN32)
-# undef USE_THREADS_POSIX
-# undef USE_THREADS_WIN32
-#endif
-
-/*
- * MSVC threads support requires a multi-threaded runtime library.
- * _beginthreadex() is not available in single-threaded ones.
- */
-
-#if defined(_MSC_VER) && !defined(__POCC__) && !defined(_MT)
-# undef USE_THREADS_POSIX
-# undef USE_THREADS_WIN32
-#endif
-
-/*
- * Mutually exclusive CURLRES_* definitions.
- */
-
+# if !defined(HAVE_WS2TCPIP_H) || \
+ ((_MSC_VER < 1300) && !defined(INET6_ADDRSTRLEN))
+# undef HAVE_GETADDRINFO_THREADSAFE
+# undef HAVE_FREEADDRINFO
+# undef HAVE_GETADDRINFO
+# undef HAVE_GETNAMEINFO
+# undef ENABLE_IPV6
+# endif
+#endif
+
+/* ---------------------------------------------------------------- */
+/* resolver specialty compile-time defines */
+/* CURLRES_* defines to use in the host*.c sources */
+/* ---------------------------------------------------------------- */
+
+/*
+ * lcc-win32 doesn't have _beginthreadex(), lacks threads support.
+ */
+
+#if defined(__LCC__) && defined(WIN32)
+# undef USE_THREADS_POSIX
+# undef USE_THREADS_WIN32
+#endif
+
+/*
+ * MSVC threads support requires a multi-threaded runtime library.
+ * _beginthreadex() is not available in single-threaded ones.
+ */
+
+#if defined(_MSC_VER) && !defined(__POCC__) && !defined(_MT)
+# undef USE_THREADS_POSIX
+# undef USE_THREADS_WIN32
+#endif
+
+/*
+ * Mutually exclusive CURLRES_* definitions.
+ */
+
#if defined(ENABLE_IPV6) && defined(HAVE_GETADDRINFO)
# define CURLRES_IPV6
#else
# define CURLRES_IPV4
#endif
-#ifdef USE_ARES
-# define CURLRES_ASYNCH
-# define CURLRES_ARES
-/* now undef the stock libc functions just to avoid them being used */
-# undef HAVE_GETADDRINFO
+#ifdef USE_ARES
+# define CURLRES_ASYNCH
+# define CURLRES_ARES
+/* now undef the stock libc functions just to avoid them being used */
+# undef HAVE_GETADDRINFO
# undef HAVE_FREEADDRINFO
-# undef HAVE_GETHOSTBYNAME
-#elif defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
-# define CURLRES_ASYNCH
-# define CURLRES_THREADED
-#else
-# define CURLRES_SYNCH
-#endif
-
-/* ---------------------------------------------------------------- */
-
-/*
- * msvc 6.0 does not have struct sockaddr_storage and
- * does not define IPPROTO_ESP in winsock2.h. But both
- * are available if PSDK is properly installed.
- */
-
-#if defined(_MSC_VER) && !defined(__POCC__)
-# if !defined(HAVE_WINSOCK2_H) || ((_MSC_VER < 1300) && !defined(IPPROTO_ESP))
-# undef HAVE_STRUCT_SOCKADDR_STORAGE
-# endif
-#endif
-
-/*
- * Intentionally fail to build when using msvc 6.0 without PSDK installed.
- * The brave of heart can circumvent this, defining ALLOW_MSVC6_WITHOUT_PSDK
- * in lib/config-win32.h although absolutely discouraged and unsupported.
- */
-
-#if defined(_MSC_VER) && !defined(__POCC__)
-# if !defined(HAVE_WINDOWS_H) || ((_MSC_VER < 1300) && !defined(_FILETIME_))
-# if !defined(ALLOW_MSVC6_WITHOUT_PSDK)
-# error MSVC 6.0 requires "February 2003 Platform SDK" a.k.a. \
- "Windows Server 2003 PSDK"
-# else
-# define CURL_DISABLE_LDAP 1
-# endif
-# endif
-#endif
-
-#ifdef NETWARE
-int netware_init(void);
-#ifndef __NOVELL_LIBC__
-#include <sys/bsdskt.h>
-#include <sys/timeval.h>
-#endif
-#endif
-
+# undef HAVE_GETHOSTBYNAME
+#elif defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
+# define CURLRES_ASYNCH
+# define CURLRES_THREADED
+#else
+# define CURLRES_SYNCH
+#endif
+
+/* ---------------------------------------------------------------- */
+
+/*
+ * msvc 6.0 does not have struct sockaddr_storage and
+ * does not define IPPROTO_ESP in winsock2.h. But both
+ * are available if PSDK is properly installed.
+ */
+
+#if defined(_MSC_VER) && !defined(__POCC__)
+# if !defined(HAVE_WINSOCK2_H) || ((_MSC_VER < 1300) && !defined(IPPROTO_ESP))
+# undef HAVE_STRUCT_SOCKADDR_STORAGE
+# endif
+#endif
+
+/*
+ * Intentionally fail to build when using msvc 6.0 without PSDK installed.
+ * The brave of heart can circumvent this, defining ALLOW_MSVC6_WITHOUT_PSDK
+ * in lib/config-win32.h although absolutely discouraged and unsupported.
+ */
+
+#if defined(_MSC_VER) && !defined(__POCC__)
+# if !defined(HAVE_WINDOWS_H) || ((_MSC_VER < 1300) && !defined(_FILETIME_))
+# if !defined(ALLOW_MSVC6_WITHOUT_PSDK)
+# error MSVC 6.0 requires "February 2003 Platform SDK" a.k.a. \
+ "Windows Server 2003 PSDK"
+# else
+# define CURL_DISABLE_LDAP 1
+# endif
+# endif
+#endif
+
+#ifdef NETWARE
+int netware_init(void);
+#ifndef __NOVELL_LIBC__
+#include <sys/bsdskt.h>
+#include <sys/timeval.h>
+#endif
+#endif
+
#if defined(HAVE_LIBIDN2) && defined(HAVE_IDN2_H) && !defined(USE_WIN32_IDN)
/* The lib and header are present */
#define USE_LIBIDN2
-#endif
-
+#endif
+
#if defined(USE_LIBIDN2) && defined(USE_WIN32_IDN)
#error "Both libidn2 and WinIDN are enabled, choose one."
-#endif
-
-#define LIBIDN_REQUIRED_VERSION "0.4.1"
-
+#endif
+
+#define LIBIDN_REQUIRED_VERSION "0.4.1"
+
#if defined(USE_GNUTLS) || defined(USE_OPENSSL) || defined(USE_NSS) || \
defined(USE_MBEDTLS) || \
defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || \
defined(USE_SECTRANSP) || defined(USE_GSKIT) || defined(USE_MESALINK) || \
defined(USE_BEARSSL)
-#define USE_SSL /* SSL support has been enabled */
-#endif
-
+#define USE_SSL /* SSL support has been enabled */
+#endif
+
/* Single point where USE_SPNEGO definition might be defined */
#if !defined(CURL_DISABLE_CRYPTO_AUTH) && \
(defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI))
#define USE_SPNEGO
-#endif
-
+#endif
+
/* Single point where USE_KERBEROS5 definition might be defined */
#if !defined(CURL_DISABLE_CRYPTO_AUTH) && \
(defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI))
@@ -642,86 +642,86 @@ int netware_init(void);
# error #include <mbedtls/md4.h>
# endif
-#endif
+#endif
#if defined(USE_CURL_NTLM_CORE) || defined(USE_WINDOWS_SSPI)
#define USE_NTLM
-#endif
#endif
-
+#endif
+
#ifdef CURL_WANTS_CA_BUNDLE_ENV
#error "No longer supported. Set CURLOPT_CAINFO at runtime instead."
-#endif
-
+#endif
+
#if defined(USE_LIBSSH2) || defined(USE_LIBSSH) || defined(USE_WOLFSSH)
#define USE_SSH
#endif
-/*
- * Provide a mechanism to silence picky compilers, such as gcc 4.6+.
- * Parameters should of course normally not be unused, but for example when
- * we have multiple implementations of the same interface it may happen.
- */
-
-#if defined(__GNUC__) && ((__GNUC__ >= 3) || \
- ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7)))
-# define UNUSED_PARAM __attribute__((__unused__))
+/*
+ * Provide a mechanism to silence picky compilers, such as gcc 4.6+.
+ * Parameters should of course normally not be unused, but for example when
+ * we have multiple implementations of the same interface it may happen.
+ */
+
+#if defined(__GNUC__) && ((__GNUC__ >= 3) || \
+ ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7)))
+# define UNUSED_PARAM __attribute__((__unused__))
# define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
-#else
-# define UNUSED_PARAM /*NOTHING*/
+#else
+# define UNUSED_PARAM /*NOTHING*/
# define WARN_UNUSED_RESULT
-#endif
-
-/*
- * Include macros and defines that should only be processed once.
- */
-
-#ifndef HEADER_CURL_SETUP_ONCE_H
-#include "curl_setup_once.h"
-#endif
-
-/*
- * Definition of our NOP statement Object-like macro
- */
-
-#ifndef Curl_nop_stmt
+#endif
+
+/*
+ * Include macros and defines that should only be processed once.
+ */
+
+#ifndef HEADER_CURL_SETUP_ONCE_H
+#include "curl_setup_once.h"
+#endif
+
+/*
+ * Definition of our NOP statement Object-like macro
+ */
+
+#ifndef Curl_nop_stmt
# define Curl_nop_stmt do { } while(0)
-#endif
-
-/*
- * Ensure that Winsock and lwIP TCP/IP stacks are not mixed.
- */
-
+#endif
+
+/*
+ * Ensure that Winsock and lwIP TCP/IP stacks are not mixed.
+ */
+
#if defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)
-# if defined(SOCKET) || \
- defined(USE_WINSOCK) || \
- defined(HAVE_WINSOCK_H) || \
- defined(HAVE_WINSOCK2_H) || \
- defined(HAVE_WS2TCPIP_H)
+# if defined(SOCKET) || \
+ defined(USE_WINSOCK) || \
+ defined(HAVE_WINSOCK_H) || \
+ defined(HAVE_WINSOCK2_H) || \
+ defined(HAVE_WS2TCPIP_H)
# error "WinSock and lwIP TCP/IP stack definitions shall not coexist!"
-# endif
-#endif
-
-/*
- * Portable symbolic names for Winsock shutdown() mode flags.
- */
-
-#ifdef USE_WINSOCK
-# define SHUT_RD 0x00
-# define SHUT_WR 0x01
-# define SHUT_RDWR 0x02
-#endif
-
-/* Define S_ISREG if not defined by system headers, f.e. MSVC */
-#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
-#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
-#endif
-
-/* Define S_ISDIR if not defined by system headers, f.e. MSVC */
-#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
-#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
-#endif
-
+# endif
+#endif
+
+/*
+ * Portable symbolic names for Winsock shutdown() mode flags.
+ */
+
+#ifdef USE_WINSOCK
+# define SHUT_RD 0x00
+# define SHUT_WR 0x01
+# define SHUT_RDWR 0x02
+#endif
+
+/* Define S_ISREG if not defined by system headers, f.e. MSVC */
+#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
+#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
+#endif
+
+/* Define S_ISDIR if not defined by system headers, f.e. MSVC */
+#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
+#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
+#endif
+
/* In Windows the default file mode is text but an application can override it.
Therefore we specify it explicitly. https://github.com/curl/curl/pull/258
*/
@@ -798,4 +798,4 @@ int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf,
#define ENABLE_QUIC
#endif
-#endif /* HEADER_CURL_SETUP_H */
+#endif /* HEADER_CURL_SETUP_H */
diff --git a/contrib/libs/curl/lib/curl_setup_once.h b/contrib/libs/curl/lib/curl_setup_once.h
index e19c264bb4..ef60bc7ae7 100644
--- a/contrib/libs/curl/lib/curl_setup_once.h
+++ b/contrib/libs/curl/lib/curl_setup_once.h
@@ -1,499 +1,499 @@
-#ifndef HEADER_CURL_SETUP_ONCE_H
-#define HEADER_CURL_SETUP_ONCE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SETUP_ONCE_H
+#define HEADER_CURL_SETUP_ONCE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-
-/*
- * Inclusion of common header files.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdarg.h>
-#include <ctype.h>
-
-#ifdef HAVE_ERRNO_H
-#include <errno.h>
-#endif
-
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-
-#ifdef NEED_MALLOC_H
-#include <malloc.h>
-#endif
-
-#ifdef NEED_MEMORY_H
-#include <memory.h>
-#endif
-
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif
-
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#ifdef TIME_WITH_SYS_TIME
-#include <time.h>
-#endif
-#else
-#ifdef HAVE_TIME_H
-#include <time.h>
-#endif
-#endif
-
-#ifdef WIN32
-#include <io.h>
-#include <fcntl.h>
-#endif
-
-#if defined(HAVE_STDBOOL_H) && defined(HAVE_BOOL_T)
-#include <stdbool.h>
-#endif
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#ifdef __hpux
-# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL)
-# ifdef _APP32_64BIT_OFF_T
-# define OLD_APP32_64BIT_OFF_T _APP32_64BIT_OFF_T
-# undef _APP32_64BIT_OFF_T
-# else
-# undef OLD_APP32_64BIT_OFF_T
-# endif
-# endif
-#endif
-
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-
-#ifdef __hpux
-# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL)
-# ifdef OLD_APP32_64BIT_OFF_T
-# define _APP32_64BIT_OFF_T OLD_APP32_64BIT_OFF_T
-# undef OLD_APP32_64BIT_OFF_T
-# endif
-# endif
-#endif
-
-/*
- * Definition of timeval struct for platforms that don't have it.
- */
-
-#ifndef HAVE_STRUCT_TIMEVAL
-struct timeval {
- long tv_sec;
- long tv_usec;
-};
-#endif
-
-
-/*
- * If we have the MSG_NOSIGNAL define, make sure we use
- * it as the fourth argument of function send()
- */
-
-#ifdef HAVE_MSG_NOSIGNAL
-#define SEND_4TH_ARG MSG_NOSIGNAL
-#else
-#define SEND_4TH_ARG 0
-#endif
-
-
-#if defined(__minix)
-/* Minix doesn't support recv on TCP sockets */
-#define sread(x,y,z) (ssize_t)read((RECV_TYPE_ARG1)(x), \
- (RECV_TYPE_ARG2)(y), \
- (RECV_TYPE_ARG3)(z))
-
-#elif defined(HAVE_RECV)
-/*
- * The definitions for the return type and arguments types
- * of functions recv() and send() belong and come from the
- * configuration file. Do not define them in any other place.
- *
- * HAVE_RECV is defined if you have a function named recv()
- * which is used to read incoming data from sockets. If your
- * function has another name then don't define HAVE_RECV.
- *
- * If HAVE_RECV is defined then RECV_TYPE_ARG1, RECV_TYPE_ARG2,
- * RECV_TYPE_ARG3, RECV_TYPE_ARG4 and RECV_TYPE_RETV must also
- * be defined.
- *
- * HAVE_SEND is defined if you have a function named send()
- * which is used to write outgoing data on a connected socket.
- * If yours has another name then don't define HAVE_SEND.
- *
- * If HAVE_SEND is defined then SEND_TYPE_ARG1, SEND_QUAL_ARG2,
- * SEND_TYPE_ARG2, SEND_TYPE_ARG3, SEND_TYPE_ARG4 and
- * SEND_TYPE_RETV must also be defined.
- */
-
-#if !defined(RECV_TYPE_ARG1) || \
- !defined(RECV_TYPE_ARG2) || \
- !defined(RECV_TYPE_ARG3) || \
- !defined(RECV_TYPE_ARG4) || \
- !defined(RECV_TYPE_RETV)
- /* */
- Error Missing_definition_of_return_and_arguments_types_of_recv
- /* */
-#else
-#define sread(x,y,z) (ssize_t)recv((RECV_TYPE_ARG1)(x), \
- (RECV_TYPE_ARG2)(y), \
- (RECV_TYPE_ARG3)(z), \
- (RECV_TYPE_ARG4)(0))
-#endif
-#else /* HAVE_RECV */
-#ifndef sread
- /* */
- Error Missing_definition_of_macro_sread
- /* */
-#endif
-#endif /* HAVE_RECV */
-
-
-#if defined(__minix)
-/* Minix doesn't support send on TCP sockets */
-#define swrite(x,y,z) (ssize_t)write((SEND_TYPE_ARG1)(x), \
- (SEND_TYPE_ARG2)(y), \
- (SEND_TYPE_ARG3)(z))
-
-#elif defined(HAVE_SEND)
-#if !defined(SEND_TYPE_ARG1) || \
- !defined(SEND_QUAL_ARG2) || \
- !defined(SEND_TYPE_ARG2) || \
- !defined(SEND_TYPE_ARG3) || \
- !defined(SEND_TYPE_ARG4) || \
- !defined(SEND_TYPE_RETV)
- /* */
- Error Missing_definition_of_return_and_arguments_types_of_send
- /* */
-#else
-#define swrite(x,y,z) (ssize_t)send((SEND_TYPE_ARG1)(x), \
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+
+/*
+ * Inclusion of common header files.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <ctype.h>
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#ifdef NEED_MALLOC_H
+#include <malloc.h>
+#endif
+
+#ifdef NEED_MEMORY_H
+#include <memory.h>
+#endif
+
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#ifdef TIME_WITH_SYS_TIME
+#include <time.h>
+#endif
+#else
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
+#endif
+
+#ifdef WIN32
+#include <io.h>
+#include <fcntl.h>
+#endif
+
+#if defined(HAVE_STDBOOL_H) && defined(HAVE_BOOL_T)
+#include <stdbool.h>
+#endif
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef __hpux
+# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL)
+# ifdef _APP32_64BIT_OFF_T
+# define OLD_APP32_64BIT_OFF_T _APP32_64BIT_OFF_T
+# undef _APP32_64BIT_OFF_T
+# else
+# undef OLD_APP32_64BIT_OFF_T
+# endif
+# endif
+#endif
+
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#ifdef __hpux
+# if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL)
+# ifdef OLD_APP32_64BIT_OFF_T
+# define _APP32_64BIT_OFF_T OLD_APP32_64BIT_OFF_T
+# undef OLD_APP32_64BIT_OFF_T
+# endif
+# endif
+#endif
+
+/*
+ * Definition of timeval struct for platforms that don't have it.
+ */
+
+#ifndef HAVE_STRUCT_TIMEVAL
+struct timeval {
+ long tv_sec;
+ long tv_usec;
+};
+#endif
+
+
+/*
+ * If we have the MSG_NOSIGNAL define, make sure we use
+ * it as the fourth argument of function send()
+ */
+
+#ifdef HAVE_MSG_NOSIGNAL
+#define SEND_4TH_ARG MSG_NOSIGNAL
+#else
+#define SEND_4TH_ARG 0
+#endif
+
+
+#if defined(__minix)
+/* Minix doesn't support recv on TCP sockets */
+#define sread(x,y,z) (ssize_t)read((RECV_TYPE_ARG1)(x), \
+ (RECV_TYPE_ARG2)(y), \
+ (RECV_TYPE_ARG3)(z))
+
+#elif defined(HAVE_RECV)
+/*
+ * The definitions for the return type and arguments types
+ * of functions recv() and send() belong and come from the
+ * configuration file. Do not define them in any other place.
+ *
+ * HAVE_RECV is defined if you have a function named recv()
+ * which is used to read incoming data from sockets. If your
+ * function has another name then don't define HAVE_RECV.
+ *
+ * If HAVE_RECV is defined then RECV_TYPE_ARG1, RECV_TYPE_ARG2,
+ * RECV_TYPE_ARG3, RECV_TYPE_ARG4 and RECV_TYPE_RETV must also
+ * be defined.
+ *
+ * HAVE_SEND is defined if you have a function named send()
+ * which is used to write outgoing data on a connected socket.
+ * If yours has another name then don't define HAVE_SEND.
+ *
+ * If HAVE_SEND is defined then SEND_TYPE_ARG1, SEND_QUAL_ARG2,
+ * SEND_TYPE_ARG2, SEND_TYPE_ARG3, SEND_TYPE_ARG4 and
+ * SEND_TYPE_RETV must also be defined.
+ */
+
+#if !defined(RECV_TYPE_ARG1) || \
+ !defined(RECV_TYPE_ARG2) || \
+ !defined(RECV_TYPE_ARG3) || \
+ !defined(RECV_TYPE_ARG4) || \
+ !defined(RECV_TYPE_RETV)
+ /* */
+ Error Missing_definition_of_return_and_arguments_types_of_recv
+ /* */
+#else
+#define sread(x,y,z) (ssize_t)recv((RECV_TYPE_ARG1)(x), \
+ (RECV_TYPE_ARG2)(y), \
+ (RECV_TYPE_ARG3)(z), \
+ (RECV_TYPE_ARG4)(0))
+#endif
+#else /* HAVE_RECV */
+#ifndef sread
+ /* */
+ Error Missing_definition_of_macro_sread
+ /* */
+#endif
+#endif /* HAVE_RECV */
+
+
+#if defined(__minix)
+/* Minix doesn't support send on TCP sockets */
+#define swrite(x,y,z) (ssize_t)write((SEND_TYPE_ARG1)(x), \
+ (SEND_TYPE_ARG2)(y), \
+ (SEND_TYPE_ARG3)(z))
+
+#elif defined(HAVE_SEND)
+#if !defined(SEND_TYPE_ARG1) || \
+ !defined(SEND_QUAL_ARG2) || \
+ !defined(SEND_TYPE_ARG2) || \
+ !defined(SEND_TYPE_ARG3) || \
+ !defined(SEND_TYPE_ARG4) || \
+ !defined(SEND_TYPE_RETV)
+ /* */
+ Error Missing_definition_of_return_and_arguments_types_of_send
+ /* */
+#else
+#define swrite(x,y,z) (ssize_t)send((SEND_TYPE_ARG1)(x), \
(SEND_QUAL_ARG2 SEND_TYPE_ARG2)(y), \
- (SEND_TYPE_ARG3)(z), \
- (SEND_TYPE_ARG4)(SEND_4TH_ARG))
-#endif
-#else /* HAVE_SEND */
-#ifndef swrite
- /* */
- Error Missing_definition_of_macro_swrite
- /* */
-#endif
-#endif /* HAVE_SEND */
-
-
-#if 0
-#if defined(HAVE_RECVFROM)
-/*
- * Currently recvfrom is only used on udp sockets.
- */
-#if !defined(RECVFROM_TYPE_ARG1) || \
- !defined(RECVFROM_TYPE_ARG2) || \
- !defined(RECVFROM_TYPE_ARG3) || \
- !defined(RECVFROM_TYPE_ARG4) || \
- !defined(RECVFROM_TYPE_ARG5) || \
- !defined(RECVFROM_TYPE_ARG6) || \
- !defined(RECVFROM_TYPE_RETV)
- /* */
- Error Missing_definition_of_return_and_arguments_types_of_recvfrom
- /* */
-#else
-#define sreadfrom(s,b,bl,f,fl) (ssize_t)recvfrom((RECVFROM_TYPE_ARG1) (s), \
- (RECVFROM_TYPE_ARG2 *)(b), \
- (RECVFROM_TYPE_ARG3) (bl), \
- (RECVFROM_TYPE_ARG4) (0), \
- (RECVFROM_TYPE_ARG5 *)(f), \
- (RECVFROM_TYPE_ARG6 *)(fl))
-#endif
-#else /* HAVE_RECVFROM */
-#ifndef sreadfrom
- /* */
- Error Missing_definition_of_macro_sreadfrom
- /* */
-#endif
-#endif /* HAVE_RECVFROM */
-
-
-#ifdef RECVFROM_TYPE_ARG6_IS_VOID
-# define RECVFROM_ARG6_T int
-#else
-# define RECVFROM_ARG6_T RECVFROM_TYPE_ARG6
-#endif
-#endif /* if 0 */
-
-
-/*
- * Function-like macro definition used to close a socket.
- */
-
-#if defined(HAVE_CLOSESOCKET)
-# define sclose(x) closesocket((x))
-#elif defined(HAVE_CLOSESOCKET_CAMEL)
-# define sclose(x) CloseSocket((x))
-#elif defined(HAVE_CLOSE_S)
-# define sclose(x) close_s((x))
-#elif defined(USE_LWIPSOCK)
-# define sclose(x) lwip_close((x))
-#else
-# define sclose(x) close((x))
-#endif
-
-/*
- * Stack-independent version of fcntl() on sockets:
- */
-#if defined(USE_LWIPSOCK)
-# define sfcntl lwip_fcntl
-#else
-# define sfcntl fcntl
-#endif
-
-#define TOLOWER(x) (tolower((int) ((unsigned char)x)))
-
-
-/*
- * 'bool' stuff compatible with HP-UX headers.
- */
-
-#if defined(__hpux) && !defined(HAVE_BOOL_T)
- typedef int bool;
-# define false 0
-# define true 1
-# define HAVE_BOOL_T
-#endif
-
-
-/*
- * 'bool' exists on platforms with <stdbool.h>, i.e. C99 platforms.
- * On non-C99 platforms there's no bool, so define an enum for that.
- * On C99 platforms 'false' and 'true' also exist. Enum uses a
- * global namespace though, so use bool_false and bool_true.
- */
-
-#ifndef HAVE_BOOL_T
- typedef enum {
- bool_false = 0,
- bool_true = 1
- } bool;
-
-/*
- * Use a define to let 'true' and 'false' use those enums. There
- * are currently no use of true and false in libcurl proper, but
- * there are some in the examples. This will cater for any later
- * code happening to use true and false.
- */
-# define false bool_false
-# define true bool_true
-# define HAVE_BOOL_T
-#endif
-
-
-/*
- * Redefine TRUE and FALSE too, to catch current use. With this
- * change, 'bool found = 1' will give a warning on MIPSPro, but
- * 'bool found = TRUE' will not. Change tested on IRIX/MIPSPro,
- * AIX 5.1/Xlc, Tru64 5.1/cc, w/make test too.
- */
-
-#ifndef TRUE
-#define TRUE true
-#endif
-#ifndef FALSE
-#define FALSE false
-#endif
-
+ (SEND_TYPE_ARG3)(z), \
+ (SEND_TYPE_ARG4)(SEND_4TH_ARG))
+#endif
+#else /* HAVE_SEND */
+#ifndef swrite
+ /* */
+ Error Missing_definition_of_macro_swrite
+ /* */
+#endif
+#endif /* HAVE_SEND */
+
+
+#if 0
+#if defined(HAVE_RECVFROM)
+/*
+ * Currently recvfrom is only used on udp sockets.
+ */
+#if !defined(RECVFROM_TYPE_ARG1) || \
+ !defined(RECVFROM_TYPE_ARG2) || \
+ !defined(RECVFROM_TYPE_ARG3) || \
+ !defined(RECVFROM_TYPE_ARG4) || \
+ !defined(RECVFROM_TYPE_ARG5) || \
+ !defined(RECVFROM_TYPE_ARG6) || \
+ !defined(RECVFROM_TYPE_RETV)
+ /* */
+ Error Missing_definition_of_return_and_arguments_types_of_recvfrom
+ /* */
+#else
+#define sreadfrom(s,b,bl,f,fl) (ssize_t)recvfrom((RECVFROM_TYPE_ARG1) (s), \
+ (RECVFROM_TYPE_ARG2 *)(b), \
+ (RECVFROM_TYPE_ARG3) (bl), \
+ (RECVFROM_TYPE_ARG4) (0), \
+ (RECVFROM_TYPE_ARG5 *)(f), \
+ (RECVFROM_TYPE_ARG6 *)(fl))
+#endif
+#else /* HAVE_RECVFROM */
+#ifndef sreadfrom
+ /* */
+ Error Missing_definition_of_macro_sreadfrom
+ /* */
+#endif
+#endif /* HAVE_RECVFROM */
+
+
+#ifdef RECVFROM_TYPE_ARG6_IS_VOID
+# define RECVFROM_ARG6_T int
+#else
+# define RECVFROM_ARG6_T RECVFROM_TYPE_ARG6
+#endif
+#endif /* if 0 */
+
+
+/*
+ * Function-like macro definition used to close a socket.
+ */
+
+#if defined(HAVE_CLOSESOCKET)
+# define sclose(x) closesocket((x))
+#elif defined(HAVE_CLOSESOCKET_CAMEL)
+# define sclose(x) CloseSocket((x))
+#elif defined(HAVE_CLOSE_S)
+# define sclose(x) close_s((x))
+#elif defined(USE_LWIPSOCK)
+# define sclose(x) lwip_close((x))
+#else
+# define sclose(x) close((x))
+#endif
+
+/*
+ * Stack-independent version of fcntl() on sockets:
+ */
+#if defined(USE_LWIPSOCK)
+# define sfcntl lwip_fcntl
+#else
+# define sfcntl fcntl
+#endif
+
+#define TOLOWER(x) (tolower((int) ((unsigned char)x)))
+
+
+/*
+ * 'bool' stuff compatible with HP-UX headers.
+ */
+
+#if defined(__hpux) && !defined(HAVE_BOOL_T)
+ typedef int bool;
+# define false 0
+# define true 1
+# define HAVE_BOOL_T
+#endif
+
+
+/*
+ * 'bool' exists on platforms with <stdbool.h>, i.e. C99 platforms.
+ * On non-C99 platforms there's no bool, so define an enum for that.
+ * On C99 platforms 'false' and 'true' also exist. Enum uses a
+ * global namespace though, so use bool_false and bool_true.
+ */
+
+#ifndef HAVE_BOOL_T
+ typedef enum {
+ bool_false = 0,
+ bool_true = 1
+ } bool;
+
+/*
+ * Use a define to let 'true' and 'false' use those enums. There
+ * are currently no use of true and false in libcurl proper, but
+ * there are some in the examples. This will cater for any later
+ * code happening to use true and false.
+ */
+# define false bool_false
+# define true bool_true
+# define HAVE_BOOL_T
+#endif
+
+
+/*
+ * Redefine TRUE and FALSE too, to catch current use. With this
+ * change, 'bool found = 1' will give a warning on MIPSPro, but
+ * 'bool found = TRUE' will not. Change tested on IRIX/MIPSPro,
+ * AIX 5.1/Xlc, Tru64 5.1/cc, w/make test too.
+ */
+
+#ifndef TRUE
+#define TRUE true
+#endif
+#ifndef FALSE
+#define FALSE false
+#endif
+
#include "curl_ctype.h"
-
-/*
- * Typedef to 'int' if sig_atomic_t is not an available 'typedefed' type.
- */
-
-#ifndef HAVE_SIG_ATOMIC_T
-typedef int sig_atomic_t;
-#define HAVE_SIG_ATOMIC_T
-#endif
-
-
-/*
- * Convenience SIG_ATOMIC_T definition
- */
-
-#ifdef HAVE_SIG_ATOMIC_T_VOLATILE
-#define SIG_ATOMIC_T static sig_atomic_t
-#else
-#define SIG_ATOMIC_T static volatile sig_atomic_t
-#endif
-
-
-/*
- * Default return type for signal handlers.
- */
-
-#ifndef RETSIGTYPE
-#define RETSIGTYPE void
-#endif
-
-
-/*
- * Macro used to include code only in debug builds.
- */
-
-#ifdef DEBUGBUILD
-#define DEBUGF(x) x
-#else
+
+/*
+ * Typedef to 'int' if sig_atomic_t is not an available 'typedefed' type.
+ */
+
+#ifndef HAVE_SIG_ATOMIC_T
+typedef int sig_atomic_t;
+#define HAVE_SIG_ATOMIC_T
+#endif
+
+
+/*
+ * Convenience SIG_ATOMIC_T definition
+ */
+
+#ifdef HAVE_SIG_ATOMIC_T_VOLATILE
+#define SIG_ATOMIC_T static sig_atomic_t
+#else
+#define SIG_ATOMIC_T static volatile sig_atomic_t
+#endif
+
+
+/*
+ * Default return type for signal handlers.
+ */
+
+#ifndef RETSIGTYPE
+#define RETSIGTYPE void
+#endif
+
+
+/*
+ * Macro used to include code only in debug builds.
+ */
+
+#ifdef DEBUGBUILD
+#define DEBUGF(x) x
+#else
#define DEBUGF(x) do { } while(0)
-#endif
-
-
-/*
- * Macro used to include assertion code only in debug builds.
- */
-
+#endif
+
+
+/*
+ * Macro used to include assertion code only in debug builds.
+ */
+
#undef DEBUGASSERT
-#if defined(DEBUGBUILD) && defined(HAVE_ASSERT_H)
-#define DEBUGASSERT(x) assert(x)
-#else
+#if defined(DEBUGBUILD) && defined(HAVE_ASSERT_H)
+#define DEBUGASSERT(x) assert(x)
+#else
#define DEBUGASSERT(x) do { } while(0)
-#endif
-
-
-/*
- * Macro SOCKERRNO / SET_SOCKERRNO() returns / sets the *socket-related* errno
- * (or equivalent) on this platform to hide platform details to code using it.
- */
-
-#ifdef USE_WINSOCK
-#define SOCKERRNO ((int)WSAGetLastError())
-#define SET_SOCKERRNO(x) (WSASetLastError((int)(x)))
-#else
-#define SOCKERRNO (errno)
-#define SET_SOCKERRNO(x) (errno = (x))
-#endif
-
-
-/*
- * Portable error number symbolic names defined to Winsock error codes.
- */
-
-#ifdef USE_WINSOCK
-#undef EBADF /* override definition in errno.h */
-#define EBADF WSAEBADF
-#undef EINTR /* override definition in errno.h */
-#define EINTR WSAEINTR
-#undef EINVAL /* override definition in errno.h */
-#define EINVAL WSAEINVAL
-#undef EWOULDBLOCK /* override definition in errno.h */
-#define EWOULDBLOCK WSAEWOULDBLOCK
-#undef EINPROGRESS /* override definition in errno.h */
-#define EINPROGRESS WSAEINPROGRESS
-#undef EALREADY /* override definition in errno.h */
-#define EALREADY WSAEALREADY
-#undef ENOTSOCK /* override definition in errno.h */
-#define ENOTSOCK WSAENOTSOCK
-#undef EDESTADDRREQ /* override definition in errno.h */
-#define EDESTADDRREQ WSAEDESTADDRREQ
-#undef EMSGSIZE /* override definition in errno.h */
-#define EMSGSIZE WSAEMSGSIZE
-#undef EPROTOTYPE /* override definition in errno.h */
-#define EPROTOTYPE WSAEPROTOTYPE
-#undef ENOPROTOOPT /* override definition in errno.h */
-#define ENOPROTOOPT WSAENOPROTOOPT
-#undef EPROTONOSUPPORT /* override definition in errno.h */
-#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
-#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT
-#undef EOPNOTSUPP /* override definition in errno.h */
-#define EOPNOTSUPP WSAEOPNOTSUPP
-#define EPFNOSUPPORT WSAEPFNOSUPPORT
-#undef EAFNOSUPPORT /* override definition in errno.h */
-#define EAFNOSUPPORT WSAEAFNOSUPPORT
-#undef EADDRINUSE /* override definition in errno.h */
-#define EADDRINUSE WSAEADDRINUSE
-#undef EADDRNOTAVAIL /* override definition in errno.h */
-#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
-#undef ENETDOWN /* override definition in errno.h */
-#define ENETDOWN WSAENETDOWN
-#undef ENETUNREACH /* override definition in errno.h */
-#define ENETUNREACH WSAENETUNREACH
-#undef ENETRESET /* override definition in errno.h */
-#define ENETRESET WSAENETRESET
-#undef ECONNABORTED /* override definition in errno.h */
-#define ECONNABORTED WSAECONNABORTED
-#undef ECONNRESET /* override definition in errno.h */
-#define ECONNRESET WSAECONNRESET
-#undef ENOBUFS /* override definition in errno.h */
-#define ENOBUFS WSAENOBUFS
-#undef EISCONN /* override definition in errno.h */
-#define EISCONN WSAEISCONN
-#undef ENOTCONN /* override definition in errno.h */
-#define ENOTCONN WSAENOTCONN
-#define ESHUTDOWN WSAESHUTDOWN
-#define ETOOMANYREFS WSAETOOMANYREFS
-#undef ETIMEDOUT /* override definition in errno.h */
-#define ETIMEDOUT WSAETIMEDOUT
-#undef ECONNREFUSED /* override definition in errno.h */
-#define ECONNREFUSED WSAECONNREFUSED
-#undef ELOOP /* override definition in errno.h */
-#define ELOOP WSAELOOP
-#ifndef ENAMETOOLONG /* possible previous definition in errno.h */
-#define ENAMETOOLONG WSAENAMETOOLONG
-#endif
-#define EHOSTDOWN WSAEHOSTDOWN
-#undef EHOSTUNREACH /* override definition in errno.h */
-#define EHOSTUNREACH WSAEHOSTUNREACH
-#ifndef ENOTEMPTY /* possible previous definition in errno.h */
-#define ENOTEMPTY WSAENOTEMPTY
-#endif
-#define EPROCLIM WSAEPROCLIM
-#define EUSERS WSAEUSERS
-#define EDQUOT WSAEDQUOT
-#define ESTALE WSAESTALE
-#define EREMOTE WSAEREMOTE
-#endif
-
-/*
- * Macro argv_item_t hides platform details to code using it.
- */
-
-#ifdef __VMS
-#define argv_item_t __char_ptr32
+#endif
+
+
+/*
+ * Macro SOCKERRNO / SET_SOCKERRNO() returns / sets the *socket-related* errno
+ * (or equivalent) on this platform to hide platform details to code using it.
+ */
+
+#ifdef USE_WINSOCK
+#define SOCKERRNO ((int)WSAGetLastError())
+#define SET_SOCKERRNO(x) (WSASetLastError((int)(x)))
+#else
+#define SOCKERRNO (errno)
+#define SET_SOCKERRNO(x) (errno = (x))
+#endif
+
+
+/*
+ * Portable error number symbolic names defined to Winsock error codes.
+ */
+
+#ifdef USE_WINSOCK
+#undef EBADF /* override definition in errno.h */
+#define EBADF WSAEBADF
+#undef EINTR /* override definition in errno.h */
+#define EINTR WSAEINTR
+#undef EINVAL /* override definition in errno.h */
+#define EINVAL WSAEINVAL
+#undef EWOULDBLOCK /* override definition in errno.h */
+#define EWOULDBLOCK WSAEWOULDBLOCK
+#undef EINPROGRESS /* override definition in errno.h */
+#define EINPROGRESS WSAEINPROGRESS
+#undef EALREADY /* override definition in errno.h */
+#define EALREADY WSAEALREADY
+#undef ENOTSOCK /* override definition in errno.h */
+#define ENOTSOCK WSAENOTSOCK
+#undef EDESTADDRREQ /* override definition in errno.h */
+#define EDESTADDRREQ WSAEDESTADDRREQ
+#undef EMSGSIZE /* override definition in errno.h */
+#define EMSGSIZE WSAEMSGSIZE
+#undef EPROTOTYPE /* override definition in errno.h */
+#define EPROTOTYPE WSAEPROTOTYPE
+#undef ENOPROTOOPT /* override definition in errno.h */
+#define ENOPROTOOPT WSAENOPROTOOPT
+#undef EPROTONOSUPPORT /* override definition in errno.h */
+#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
+#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT
+#undef EOPNOTSUPP /* override definition in errno.h */
+#define EOPNOTSUPP WSAEOPNOTSUPP
+#define EPFNOSUPPORT WSAEPFNOSUPPORT
+#undef EAFNOSUPPORT /* override definition in errno.h */
+#define EAFNOSUPPORT WSAEAFNOSUPPORT
+#undef EADDRINUSE /* override definition in errno.h */
+#define EADDRINUSE WSAEADDRINUSE
+#undef EADDRNOTAVAIL /* override definition in errno.h */
+#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
+#undef ENETDOWN /* override definition in errno.h */
+#define ENETDOWN WSAENETDOWN
+#undef ENETUNREACH /* override definition in errno.h */
+#define ENETUNREACH WSAENETUNREACH
+#undef ENETRESET /* override definition in errno.h */
+#define ENETRESET WSAENETRESET
+#undef ECONNABORTED /* override definition in errno.h */
+#define ECONNABORTED WSAECONNABORTED
+#undef ECONNRESET /* override definition in errno.h */
+#define ECONNRESET WSAECONNRESET
+#undef ENOBUFS /* override definition in errno.h */
+#define ENOBUFS WSAENOBUFS
+#undef EISCONN /* override definition in errno.h */
+#define EISCONN WSAEISCONN
+#undef ENOTCONN /* override definition in errno.h */
+#define ENOTCONN WSAENOTCONN
+#define ESHUTDOWN WSAESHUTDOWN
+#define ETOOMANYREFS WSAETOOMANYREFS
+#undef ETIMEDOUT /* override definition in errno.h */
+#define ETIMEDOUT WSAETIMEDOUT
+#undef ECONNREFUSED /* override definition in errno.h */
+#define ECONNREFUSED WSAECONNREFUSED
+#undef ELOOP /* override definition in errno.h */
+#define ELOOP WSAELOOP
+#ifndef ENAMETOOLONG /* possible previous definition in errno.h */
+#define ENAMETOOLONG WSAENAMETOOLONG
+#endif
+#define EHOSTDOWN WSAEHOSTDOWN
+#undef EHOSTUNREACH /* override definition in errno.h */
+#define EHOSTUNREACH WSAEHOSTUNREACH
+#ifndef ENOTEMPTY /* possible previous definition in errno.h */
+#define ENOTEMPTY WSAENOTEMPTY
+#endif
+#define EPROCLIM WSAEPROCLIM
+#define EUSERS WSAEUSERS
+#define EDQUOT WSAEDQUOT
+#define ESTALE WSAESTALE
+#define EREMOTE WSAEREMOTE
+#endif
+
+/*
+ * Macro argv_item_t hides platform details to code using it.
+ */
+
+#ifdef __VMS
+#define argv_item_t __char_ptr32
#elif defined(_UNICODE)
#define argv_item_t wchar_t *
-#else
-#define argv_item_t char *
-#endif
-
-
-/*
- * We use this ZERO_NULL to avoid picky compiler warnings,
- * when assigning a NULL pointer to a function pointer var.
- */
-
-#define ZERO_NULL 0
-
-
-#endif /* HEADER_CURL_SETUP_ONCE_H */
+#else
+#define argv_item_t char *
+#endif
+
+
+/*
+ * We use this ZERO_NULL to avoid picky compiler warnings,
+ * when assigning a NULL pointer to a function pointer var.
+ */
+
+#define ZERO_NULL 0
+
+
+#endif /* HEADER_CURL_SETUP_ONCE_H */
diff --git a/contrib/libs/curl/lib/curl_sspi.c b/contrib/libs/curl/lib/curl_sspi.c
index 526e50ff8f..06841ddec6 100644
--- a/contrib/libs/curl/lib/curl_sspi.c
+++ b/contrib/libs/curl/lib/curl_sspi.c
@@ -1,129 +1,129 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef USE_WINDOWS_SSPI
-
-#include <curl/curl.h>
-#include "curl_sspi.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef USE_WINDOWS_SSPI
+
+#include <curl/curl.h>
+#include "curl_sspi.h"
#include "curl_multibyte.h"
#include "system_win32.h"
#include "version_win32.h"
#include "warnless.h"
-
+
/* The last #include files should be: */
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* We use our own typedef here since some headers might lack these */
-typedef PSecurityFunctionTable (APIENTRY *INITSECURITYINTERFACE_FN)(VOID);
-
-/* See definition of SECURITY_ENTRYPOINT in sspi.h */
-#ifdef UNICODE
-# ifdef _WIN32_WCE
-# define SECURITYENTRYPOINT L"InitSecurityInterfaceW"
-# else
-# define SECURITYENTRYPOINT "InitSecurityInterfaceW"
-# endif
-#else
-# define SECURITYENTRYPOINT "InitSecurityInterfaceA"
-#endif
-
-/* Handle of security.dll or secur32.dll, depending on Windows version */
-HMODULE s_hSecDll = NULL;
-
-/* Pointer to SSPI dispatch table */
-PSecurityFunctionTable s_pSecFn = NULL;
-
-/*
- * Curl_sspi_global_init()
- *
- * This is used to load the Security Service Provider Interface (SSPI)
- * dynamic link library portably across all Windows versions, without
- * the need to directly link libcurl, nor the application using it, at
- * build time.
- *
- * Once this function has been executed, Windows SSPI functions can be
- * called through the Security Service Provider Interface dispatch table.
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* We use our own typedef here since some headers might lack these */
+typedef PSecurityFunctionTable (APIENTRY *INITSECURITYINTERFACE_FN)(VOID);
+
+/* See definition of SECURITY_ENTRYPOINT in sspi.h */
+#ifdef UNICODE
+# ifdef _WIN32_WCE
+# define SECURITYENTRYPOINT L"InitSecurityInterfaceW"
+# else
+# define SECURITYENTRYPOINT "InitSecurityInterfaceW"
+# endif
+#else
+# define SECURITYENTRYPOINT "InitSecurityInterfaceA"
+#endif
+
+/* Handle of security.dll or secur32.dll, depending on Windows version */
+HMODULE s_hSecDll = NULL;
+
+/* Pointer to SSPI dispatch table */
+PSecurityFunctionTable s_pSecFn = NULL;
+
+/*
+ * Curl_sspi_global_init()
+ *
+ * This is used to load the Security Service Provider Interface (SSPI)
+ * dynamic link library portably across all Windows versions, without
+ * the need to directly link libcurl, nor the application using it, at
+ * build time.
+ *
+ * Once this function has been executed, Windows SSPI functions can be
+ * called through the Security Service Provider Interface dispatch table.
*
* Parameters:
*
* None.
*
* Returns CURLE_OK on success.
- */
-CURLcode Curl_sspi_global_init(void)
-{
- INITSECURITYINTERFACE_FN pInitSecurityInterface;
-
- /* If security interface is not yet initialized try to do this */
- if(!s_hSecDll) {
- /* Security Service Provider Interface (SSPI) functions are located in
- * security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP
- * have both these DLLs (security.dll forwards calls to secur32.dll) */
-
- /* Load SSPI dll into the address space of the calling process */
+ */
+CURLcode Curl_sspi_global_init(void)
+{
+ INITSECURITYINTERFACE_FN pInitSecurityInterface;
+
+ /* If security interface is not yet initialized try to do this */
+ if(!s_hSecDll) {
+ /* Security Service Provider Interface (SSPI) functions are located in
+ * security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP
+ * have both these DLLs (security.dll forwards calls to secur32.dll) */
+
+ /* Load SSPI dll into the address space of the calling process */
if(curlx_verify_windows_version(4, 0, PLATFORM_WINNT, VERSION_EQUAL))
s_hSecDll = Curl_load_library(TEXT("security.dll"));
- else
+ else
s_hSecDll = Curl_load_library(TEXT("secur32.dll"));
- if(!s_hSecDll)
- return CURLE_FAILED_INIT;
-
- /* Get address of the InitSecurityInterfaceA function from the SSPI dll */
+ if(!s_hSecDll)
+ return CURLE_FAILED_INIT;
+
+ /* Get address of the InitSecurityInterfaceA function from the SSPI dll */
pInitSecurityInterface =
CURLX_FUNCTION_CAST(INITSECURITYINTERFACE_FN,
(GetProcAddress(s_hSecDll, SECURITYENTRYPOINT)));
- if(!pInitSecurityInterface)
- return CURLE_FAILED_INIT;
-
- /* Get pointer to Security Service Provider Interface dispatch table */
- s_pSecFn = pInitSecurityInterface();
- if(!s_pSecFn)
- return CURLE_FAILED_INIT;
- }
-
- return CURLE_OK;
-}
-
-/*
- * Curl_sspi_global_cleanup()
- *
- * This deinitializes the Security Service Provider Interface from libcurl.
+ if(!pInitSecurityInterface)
+ return CURLE_FAILED_INIT;
+
+ /* Get pointer to Security Service Provider Interface dispatch table */
+ s_pSecFn = pInitSecurityInterface();
+ if(!s_pSecFn)
+ return CURLE_FAILED_INIT;
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_sspi_global_cleanup()
+ *
+ * This deinitializes the Security Service Provider Interface from libcurl.
*
* Parameters:
*
* None.
- */
-void Curl_sspi_global_cleanup(void)
-{
- if(s_hSecDll) {
- FreeLibrary(s_hSecDll);
- s_hSecDll = NULL;
- s_pSecFn = NULL;
- }
-}
-
+ */
+void Curl_sspi_global_cleanup(void)
+{
+ if(s_hSecDll) {
+ FreeLibrary(s_hSecDll);
+ s_hSecDll = NULL;
+ s_pSecFn = NULL;
+ }
+}
+
/*
* Curl_create_sspi_identity()
*
@@ -234,4 +234,4 @@ void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity)
}
}
-#endif /* USE_WINDOWS_SSPI */
+#endif /* USE_WINDOWS_SSPI */
diff --git a/contrib/libs/curl/lib/curl_sspi.h b/contrib/libs/curl/lib/curl_sspi.h
index 1d25bb6d7d..881384d4e4 100644
--- a/contrib/libs/curl/lib/curl_sspi.h
+++ b/contrib/libs/curl/lib/curl_sspi.h
@@ -1,48 +1,48 @@
-#ifndef HEADER_CURL_SSPI_H
-#define HEADER_CURL_SSPI_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SSPI_H
+#define HEADER_CURL_SSPI_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef USE_WINDOWS_SSPI
-
-#include <curl/curl.h>
-
-/*
- * When including the following three headers, it is mandatory to define either
- * SECURITY_WIN32 or SECURITY_KERNEL, indicating who is compiling the code.
- */
-
-#undef SECURITY_WIN32
-#undef SECURITY_KERNEL
-#define SECURITY_WIN32 1
-#include <security.h>
-#include <sspi.h>
-#include <rpc.h>
-
-CURLcode Curl_sspi_global_init(void);
-void Curl_sspi_global_cleanup(void);
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef USE_WINDOWS_SSPI
+
+#include <curl/curl.h>
+
+/*
+ * When including the following three headers, it is mandatory to define either
+ * SECURITY_WIN32 or SECURITY_KERNEL, indicating who is compiling the code.
+ */
+
+#undef SECURITY_WIN32
+#undef SECURITY_KERNEL
+#define SECURITY_WIN32 1
+#include <security.h>
+#include <sspi.h>
+#include <rpc.h>
+
+CURLcode Curl_sspi_global_init(void);
+void Curl_sspi_global_cleanup(void);
+
/* This is used to populate the domain in a SSPI identity structure */
CURLcode Curl_override_sspi_http_realm(const char *chlg,
SEC_WINNT_AUTH_IDENTITY *identity);
@@ -54,16 +54,16 @@ CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp,
/* This is used to free an SSPI identity structure */
void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity);
-/* Forward-declaration of global variables defined in curl_sspi.c */
-extern HMODULE s_hSecDll;
-extern PSecurityFunctionTable s_pSecFn;
-
-/* Provide some definitions missing in old headers */
+/* Forward-declaration of global variables defined in curl_sspi.c */
+extern HMODULE s_hSecDll;
+extern PSecurityFunctionTable s_pSecFn;
+
+/* Provide some definitions missing in old headers */
#define SP_NAME_DIGEST "WDigest"
#define SP_NAME_NTLM "NTLM"
#define SP_NAME_NEGOTIATE "Negotiate"
#define SP_NAME_KERBEROS "Kerberos"
-
+
#ifndef ISC_REQ_USE_HTTP_STYLE
#define ISC_REQ_USE_HTTP_STYLE 0x01000000
#endif
@@ -88,245 +88,245 @@ extern PSecurityFunctionTable s_pSecFn;
#define ISC_RET_STREAM 0x00008000
#endif
-#ifndef SEC_E_INSUFFICIENT_MEMORY
+#ifndef SEC_E_INSUFFICIENT_MEMORY
# define SEC_E_INSUFFICIENT_MEMORY ((HRESULT)0x80090300L)
-#endif
-#ifndef SEC_E_INVALID_HANDLE
+#endif
+#ifndef SEC_E_INVALID_HANDLE
# define SEC_E_INVALID_HANDLE ((HRESULT)0x80090301L)
-#endif
-#ifndef SEC_E_UNSUPPORTED_FUNCTION
+#endif
+#ifndef SEC_E_UNSUPPORTED_FUNCTION
# define SEC_E_UNSUPPORTED_FUNCTION ((HRESULT)0x80090302L)
-#endif
-#ifndef SEC_E_TARGET_UNKNOWN
+#endif
+#ifndef SEC_E_TARGET_UNKNOWN
# define SEC_E_TARGET_UNKNOWN ((HRESULT)0x80090303L)
-#endif
-#ifndef SEC_E_INTERNAL_ERROR
+#endif
+#ifndef SEC_E_INTERNAL_ERROR
# define SEC_E_INTERNAL_ERROR ((HRESULT)0x80090304L)
-#endif
-#ifndef SEC_E_SECPKG_NOT_FOUND
+#endif
+#ifndef SEC_E_SECPKG_NOT_FOUND
# define SEC_E_SECPKG_NOT_FOUND ((HRESULT)0x80090305L)
-#endif
-#ifndef SEC_E_NOT_OWNER
+#endif
+#ifndef SEC_E_NOT_OWNER
# define SEC_E_NOT_OWNER ((HRESULT)0x80090306L)
-#endif
-#ifndef SEC_E_CANNOT_INSTALL
+#endif
+#ifndef SEC_E_CANNOT_INSTALL
# define SEC_E_CANNOT_INSTALL ((HRESULT)0x80090307L)
-#endif
-#ifndef SEC_E_INVALID_TOKEN
+#endif
+#ifndef SEC_E_INVALID_TOKEN
# define SEC_E_INVALID_TOKEN ((HRESULT)0x80090308L)
-#endif
-#ifndef SEC_E_CANNOT_PACK
+#endif
+#ifndef SEC_E_CANNOT_PACK
# define SEC_E_CANNOT_PACK ((HRESULT)0x80090309L)
-#endif
-#ifndef SEC_E_QOP_NOT_SUPPORTED
+#endif
+#ifndef SEC_E_QOP_NOT_SUPPORTED
# define SEC_E_QOP_NOT_SUPPORTED ((HRESULT)0x8009030AL)
-#endif
-#ifndef SEC_E_NO_IMPERSONATION
+#endif
+#ifndef SEC_E_NO_IMPERSONATION
# define SEC_E_NO_IMPERSONATION ((HRESULT)0x8009030BL)
-#endif
-#ifndef SEC_E_LOGON_DENIED
+#endif
+#ifndef SEC_E_LOGON_DENIED
# define SEC_E_LOGON_DENIED ((HRESULT)0x8009030CL)
-#endif
-#ifndef SEC_E_UNKNOWN_CREDENTIALS
+#endif
+#ifndef SEC_E_UNKNOWN_CREDENTIALS
# define SEC_E_UNKNOWN_CREDENTIALS ((HRESULT)0x8009030DL)
-#endif
-#ifndef SEC_E_NO_CREDENTIALS
+#endif
+#ifndef SEC_E_NO_CREDENTIALS
# define SEC_E_NO_CREDENTIALS ((HRESULT)0x8009030EL)
-#endif
-#ifndef SEC_E_MESSAGE_ALTERED
+#endif
+#ifndef SEC_E_MESSAGE_ALTERED
# define SEC_E_MESSAGE_ALTERED ((HRESULT)0x8009030FL)
-#endif
-#ifndef SEC_E_OUT_OF_SEQUENCE
+#endif
+#ifndef SEC_E_OUT_OF_SEQUENCE
# define SEC_E_OUT_OF_SEQUENCE ((HRESULT)0x80090310L)
-#endif
-#ifndef SEC_E_NO_AUTHENTICATING_AUTHORITY
+#endif
+#ifndef SEC_E_NO_AUTHENTICATING_AUTHORITY
# define SEC_E_NO_AUTHENTICATING_AUTHORITY ((HRESULT)0x80090311L)
-#endif
-#ifndef SEC_E_BAD_PKGID
+#endif
+#ifndef SEC_E_BAD_PKGID
# define SEC_E_BAD_PKGID ((HRESULT)0x80090316L)
-#endif
-#ifndef SEC_E_CONTEXT_EXPIRED
+#endif
+#ifndef SEC_E_CONTEXT_EXPIRED
# define SEC_E_CONTEXT_EXPIRED ((HRESULT)0x80090317L)
-#endif
-#ifndef SEC_E_INCOMPLETE_MESSAGE
+#endif
+#ifndef SEC_E_INCOMPLETE_MESSAGE
# define SEC_E_INCOMPLETE_MESSAGE ((HRESULT)0x80090318L)
-#endif
-#ifndef SEC_E_INCOMPLETE_CREDENTIALS
+#endif
+#ifndef SEC_E_INCOMPLETE_CREDENTIALS
# define SEC_E_INCOMPLETE_CREDENTIALS ((HRESULT)0x80090320L)
-#endif
-#ifndef SEC_E_BUFFER_TOO_SMALL
+#endif
+#ifndef SEC_E_BUFFER_TOO_SMALL
# define SEC_E_BUFFER_TOO_SMALL ((HRESULT)0x80090321L)
-#endif
-#ifndef SEC_E_WRONG_PRINCIPAL
+#endif
+#ifndef SEC_E_WRONG_PRINCIPAL
# define SEC_E_WRONG_PRINCIPAL ((HRESULT)0x80090322L)
-#endif
-#ifndef SEC_E_TIME_SKEW
+#endif
+#ifndef SEC_E_TIME_SKEW
# define SEC_E_TIME_SKEW ((HRESULT)0x80090324L)
-#endif
-#ifndef SEC_E_UNTRUSTED_ROOT
+#endif
+#ifndef SEC_E_UNTRUSTED_ROOT
# define SEC_E_UNTRUSTED_ROOT ((HRESULT)0x80090325L)
-#endif
-#ifndef SEC_E_ILLEGAL_MESSAGE
+#endif
+#ifndef SEC_E_ILLEGAL_MESSAGE
# define SEC_E_ILLEGAL_MESSAGE ((HRESULT)0x80090326L)
-#endif
-#ifndef SEC_E_CERT_UNKNOWN
+#endif
+#ifndef SEC_E_CERT_UNKNOWN
# define SEC_E_CERT_UNKNOWN ((HRESULT)0x80090327L)
-#endif
-#ifndef SEC_E_CERT_EXPIRED
+#endif
+#ifndef SEC_E_CERT_EXPIRED
# define SEC_E_CERT_EXPIRED ((HRESULT)0x80090328L)
-#endif
-#ifndef SEC_E_ENCRYPT_FAILURE
+#endif
+#ifndef SEC_E_ENCRYPT_FAILURE
# define SEC_E_ENCRYPT_FAILURE ((HRESULT)0x80090329L)
-#endif
-#ifndef SEC_E_DECRYPT_FAILURE
+#endif
+#ifndef SEC_E_DECRYPT_FAILURE
# define SEC_E_DECRYPT_FAILURE ((HRESULT)0x80090330L)
-#endif
-#ifndef SEC_E_ALGORITHM_MISMATCH
+#endif
+#ifndef SEC_E_ALGORITHM_MISMATCH
# define SEC_E_ALGORITHM_MISMATCH ((HRESULT)0x80090331L)
-#endif
-#ifndef SEC_E_SECURITY_QOS_FAILED
+#endif
+#ifndef SEC_E_SECURITY_QOS_FAILED
# define SEC_E_SECURITY_QOS_FAILED ((HRESULT)0x80090332L)
-#endif
-#ifndef SEC_E_UNFINISHED_CONTEXT_DELETED
+#endif
+#ifndef SEC_E_UNFINISHED_CONTEXT_DELETED
# define SEC_E_UNFINISHED_CONTEXT_DELETED ((HRESULT)0x80090333L)
-#endif
-#ifndef SEC_E_NO_TGT_REPLY
+#endif
+#ifndef SEC_E_NO_TGT_REPLY
# define SEC_E_NO_TGT_REPLY ((HRESULT)0x80090334L)
-#endif
-#ifndef SEC_E_NO_IP_ADDRESSES
+#endif
+#ifndef SEC_E_NO_IP_ADDRESSES
# define SEC_E_NO_IP_ADDRESSES ((HRESULT)0x80090335L)
-#endif
-#ifndef SEC_E_WRONG_CREDENTIAL_HANDLE
+#endif
+#ifndef SEC_E_WRONG_CREDENTIAL_HANDLE
# define SEC_E_WRONG_CREDENTIAL_HANDLE ((HRESULT)0x80090336L)
-#endif
-#ifndef SEC_E_CRYPTO_SYSTEM_INVALID
+#endif
+#ifndef SEC_E_CRYPTO_SYSTEM_INVALID
# define SEC_E_CRYPTO_SYSTEM_INVALID ((HRESULT)0x80090337L)
-#endif
-#ifndef SEC_E_MAX_REFERRALS_EXCEEDED
+#endif
+#ifndef SEC_E_MAX_REFERRALS_EXCEEDED
# define SEC_E_MAX_REFERRALS_EXCEEDED ((HRESULT)0x80090338L)
-#endif
-#ifndef SEC_E_MUST_BE_KDC
+#endif
+#ifndef SEC_E_MUST_BE_KDC
# define SEC_E_MUST_BE_KDC ((HRESULT)0x80090339L)
-#endif
-#ifndef SEC_E_STRONG_CRYPTO_NOT_SUPPORTED
+#endif
+#ifndef SEC_E_STRONG_CRYPTO_NOT_SUPPORTED
# define SEC_E_STRONG_CRYPTO_NOT_SUPPORTED ((HRESULT)0x8009033AL)
-#endif
-#ifndef SEC_E_TOO_MANY_PRINCIPALS
+#endif
+#ifndef SEC_E_TOO_MANY_PRINCIPALS
# define SEC_E_TOO_MANY_PRINCIPALS ((HRESULT)0x8009033BL)
-#endif
-#ifndef SEC_E_NO_PA_DATA
+#endif
+#ifndef SEC_E_NO_PA_DATA
# define SEC_E_NO_PA_DATA ((HRESULT)0x8009033CL)
-#endif
-#ifndef SEC_E_PKINIT_NAME_MISMATCH
+#endif
+#ifndef SEC_E_PKINIT_NAME_MISMATCH
# define SEC_E_PKINIT_NAME_MISMATCH ((HRESULT)0x8009033DL)
-#endif
-#ifndef SEC_E_SMARTCARD_LOGON_REQUIRED
+#endif
+#ifndef SEC_E_SMARTCARD_LOGON_REQUIRED
# define SEC_E_SMARTCARD_LOGON_REQUIRED ((HRESULT)0x8009033EL)
-#endif
-#ifndef SEC_E_SHUTDOWN_IN_PROGRESS
+#endif
+#ifndef SEC_E_SHUTDOWN_IN_PROGRESS
# define SEC_E_SHUTDOWN_IN_PROGRESS ((HRESULT)0x8009033FL)
-#endif
-#ifndef SEC_E_KDC_INVALID_REQUEST
+#endif
+#ifndef SEC_E_KDC_INVALID_REQUEST
# define SEC_E_KDC_INVALID_REQUEST ((HRESULT)0x80090340L)
-#endif
-#ifndef SEC_E_KDC_UNABLE_TO_REFER
+#endif
+#ifndef SEC_E_KDC_UNABLE_TO_REFER
# define SEC_E_KDC_UNABLE_TO_REFER ((HRESULT)0x80090341L)
-#endif
-#ifndef SEC_E_KDC_UNKNOWN_ETYPE
+#endif
+#ifndef SEC_E_KDC_UNKNOWN_ETYPE
# define SEC_E_KDC_UNKNOWN_ETYPE ((HRESULT)0x80090342L)
-#endif
-#ifndef SEC_E_UNSUPPORTED_PREAUTH
+#endif
+#ifndef SEC_E_UNSUPPORTED_PREAUTH
# define SEC_E_UNSUPPORTED_PREAUTH ((HRESULT)0x80090343L)
-#endif
-#ifndef SEC_E_DELEGATION_REQUIRED
+#endif
+#ifndef SEC_E_DELEGATION_REQUIRED
# define SEC_E_DELEGATION_REQUIRED ((HRESULT)0x80090345L)
-#endif
-#ifndef SEC_E_BAD_BINDINGS
+#endif
+#ifndef SEC_E_BAD_BINDINGS
# define SEC_E_BAD_BINDINGS ((HRESULT)0x80090346L)
-#endif
-#ifndef SEC_E_MULTIPLE_ACCOUNTS
+#endif
+#ifndef SEC_E_MULTIPLE_ACCOUNTS
# define SEC_E_MULTIPLE_ACCOUNTS ((HRESULT)0x80090347L)
-#endif
-#ifndef SEC_E_NO_KERB_KEY
+#endif
+#ifndef SEC_E_NO_KERB_KEY
# define SEC_E_NO_KERB_KEY ((HRESULT)0x80090348L)
-#endif
-#ifndef SEC_E_CERT_WRONG_USAGE
+#endif
+#ifndef SEC_E_CERT_WRONG_USAGE
# define SEC_E_CERT_WRONG_USAGE ((HRESULT)0x80090349L)
-#endif
-#ifndef SEC_E_DOWNGRADE_DETECTED
+#endif
+#ifndef SEC_E_DOWNGRADE_DETECTED
# define SEC_E_DOWNGRADE_DETECTED ((HRESULT)0x80090350L)
-#endif
-#ifndef SEC_E_SMARTCARD_CERT_REVOKED
+#endif
+#ifndef SEC_E_SMARTCARD_CERT_REVOKED
# define SEC_E_SMARTCARD_CERT_REVOKED ((HRESULT)0x80090351L)
-#endif
-#ifndef SEC_E_ISSUING_CA_UNTRUSTED
+#endif
+#ifndef SEC_E_ISSUING_CA_UNTRUSTED
# define SEC_E_ISSUING_CA_UNTRUSTED ((HRESULT)0x80090352L)
-#endif
-#ifndef SEC_E_REVOCATION_OFFLINE_C
+#endif
+#ifndef SEC_E_REVOCATION_OFFLINE_C
# define SEC_E_REVOCATION_OFFLINE_C ((HRESULT)0x80090353L)
-#endif
-#ifndef SEC_E_PKINIT_CLIENT_FAILURE
+#endif
+#ifndef SEC_E_PKINIT_CLIENT_FAILURE
# define SEC_E_PKINIT_CLIENT_FAILURE ((HRESULT)0x80090354L)
-#endif
-#ifndef SEC_E_SMARTCARD_CERT_EXPIRED
+#endif
+#ifndef SEC_E_SMARTCARD_CERT_EXPIRED
# define SEC_E_SMARTCARD_CERT_EXPIRED ((HRESULT)0x80090355L)
-#endif
-#ifndef SEC_E_NO_S4U_PROT_SUPPORT
+#endif
+#ifndef SEC_E_NO_S4U_PROT_SUPPORT
# define SEC_E_NO_S4U_PROT_SUPPORT ((HRESULT)0x80090356L)
-#endif
-#ifndef SEC_E_CROSSREALM_DELEGATION_FAILURE
+#endif
+#ifndef SEC_E_CROSSREALM_DELEGATION_FAILURE
# define SEC_E_CROSSREALM_DELEGATION_FAILURE ((HRESULT)0x80090357L)
-#endif
-#ifndef SEC_E_REVOCATION_OFFLINE_KDC
+#endif
+#ifndef SEC_E_REVOCATION_OFFLINE_KDC
# define SEC_E_REVOCATION_OFFLINE_KDC ((HRESULT)0x80090358L)
-#endif
-#ifndef SEC_E_ISSUING_CA_UNTRUSTED_KDC
+#endif
+#ifndef SEC_E_ISSUING_CA_UNTRUSTED_KDC
# define SEC_E_ISSUING_CA_UNTRUSTED_KDC ((HRESULT)0x80090359L)
-#endif
-#ifndef SEC_E_KDC_CERT_EXPIRED
+#endif
+#ifndef SEC_E_KDC_CERT_EXPIRED
# define SEC_E_KDC_CERT_EXPIRED ((HRESULT)0x8009035AL)
-#endif
-#ifndef SEC_E_KDC_CERT_REVOKED
+#endif
+#ifndef SEC_E_KDC_CERT_REVOKED
# define SEC_E_KDC_CERT_REVOKED ((HRESULT)0x8009035BL)
-#endif
-#ifndef SEC_E_INVALID_PARAMETER
+#endif
+#ifndef SEC_E_INVALID_PARAMETER
# define SEC_E_INVALID_PARAMETER ((HRESULT)0x8009035DL)
-#endif
-#ifndef SEC_E_DELEGATION_POLICY
+#endif
+#ifndef SEC_E_DELEGATION_POLICY
# define SEC_E_DELEGATION_POLICY ((HRESULT)0x8009035EL)
-#endif
-#ifndef SEC_E_POLICY_NLTM_ONLY
+#endif
+#ifndef SEC_E_POLICY_NLTM_ONLY
# define SEC_E_POLICY_NLTM_ONLY ((HRESULT)0x8009035FL)
-#endif
-
-#ifndef SEC_I_CONTINUE_NEEDED
+#endif
+
+#ifndef SEC_I_CONTINUE_NEEDED
# define SEC_I_CONTINUE_NEEDED ((HRESULT)0x00090312L)
-#endif
-#ifndef SEC_I_COMPLETE_NEEDED
+#endif
+#ifndef SEC_I_COMPLETE_NEEDED
# define SEC_I_COMPLETE_NEEDED ((HRESULT)0x00090313L)
-#endif
-#ifndef SEC_I_COMPLETE_AND_CONTINUE
+#endif
+#ifndef SEC_I_COMPLETE_AND_CONTINUE
# define SEC_I_COMPLETE_AND_CONTINUE ((HRESULT)0x00090314L)
-#endif
-#ifndef SEC_I_LOCAL_LOGON
+#endif
+#ifndef SEC_I_LOCAL_LOGON
# define SEC_I_LOCAL_LOGON ((HRESULT)0x00090315L)
-#endif
-#ifndef SEC_I_CONTEXT_EXPIRED
+#endif
+#ifndef SEC_I_CONTEXT_EXPIRED
# define SEC_I_CONTEXT_EXPIRED ((HRESULT)0x00090317L)
-#endif
-#ifndef SEC_I_INCOMPLETE_CREDENTIALS
+#endif
+#ifndef SEC_I_INCOMPLETE_CREDENTIALS
# define SEC_I_INCOMPLETE_CREDENTIALS ((HRESULT)0x00090320L)
-#endif
-#ifndef SEC_I_RENEGOTIATE
+#endif
+#ifndef SEC_I_RENEGOTIATE
# define SEC_I_RENEGOTIATE ((HRESULT)0x00090321L)
-#endif
-#ifndef SEC_I_NO_LSA_CONTEXT
+#endif
+#ifndef SEC_I_NO_LSA_CONTEXT
# define SEC_I_NO_LSA_CONTEXT ((HRESULT)0x00090323L)
-#endif
-#ifndef SEC_I_SIGNATURE_NEEDED
+#endif
+#ifndef SEC_I_SIGNATURE_NEEDED
# define SEC_I_SIGNATURE_NEEDED ((HRESULT)0x0009035CL)
-#endif
-
+#endif
+
#ifndef CRYPT_E_REVOKED
# define CRYPT_E_REVOKED ((HRESULT)0x80092010L)
#endif
@@ -345,6 +345,6 @@ extern PSecurityFunctionTable s_pSecFn;
*/
#define KERB_WRAP_NO_ENCRYPT 0x80000001
-#endif /* USE_WINDOWS_SSPI */
+#endif /* USE_WINDOWS_SSPI */
-#endif /* HEADER_CURL_SSPI_H */
+#endif /* HEADER_CURL_SSPI_H */
diff --git a/contrib/libs/curl/lib/curl_threads.c b/contrib/libs/curl/lib/curl_threads.c
index f643714031..414614401d 100644
--- a/contrib/libs/curl/lib/curl_threads.c
+++ b/contrib/libs/curl/lib/curl_threads.c
@@ -1,117 +1,117 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <curl/curl.h>
-#if defined(USE_THREADS_POSIX)
-# ifdef HAVE_PTHREAD_H
-# include <pthread.h>
-# endif
-#elif defined(USE_THREADS_WIN32)
-# ifdef HAVE_PROCESS_H
-# include <process.h>
-# endif
-#endif
-
-#include "curl_threads.h"
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-#if defined(USE_THREADS_POSIX)
-
+#if defined(USE_THREADS_POSIX)
+# ifdef HAVE_PTHREAD_H
+# include <pthread.h>
+# endif
+#elif defined(USE_THREADS_WIN32)
+# ifdef HAVE_PROCESS_H
+# include <process.h>
+# endif
+#endif
+
+#include "curl_threads.h"
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+#if defined(USE_THREADS_POSIX)
+
struct Curl_actual_call {
- unsigned int (*func)(void *);
- void *arg;
-};
-
-static void *curl_thread_create_thunk(void *arg)
-{
+ unsigned int (*func)(void *);
+ void *arg;
+};
+
+static void *curl_thread_create_thunk(void *arg)
+{
struct Curl_actual_call *ac = arg;
- unsigned int (*func)(void *) = ac->func;
- void *real_arg = ac->arg;
-
- free(ac);
-
- (*func)(real_arg);
-
- return 0;
-}
-
+ unsigned int (*func)(void *) = ac->func;
+ void *real_arg = ac->arg;
+
+ free(ac);
+
+ (*func)(real_arg);
+
+ return 0;
+}
+
curl_thread_t Curl_thread_create(unsigned int (*func) (void *), void *arg)
-{
+{
curl_thread_t t = malloc(sizeof(pthread_t));
struct Curl_actual_call *ac = malloc(sizeof(struct Curl_actual_call));
if(!(ac && t))
goto err;
-
- ac->func = func;
- ac->arg = arg;
-
+
+ ac->func = func;
+ ac->arg = arg;
+
if(pthread_create(t, NULL, curl_thread_create_thunk, ac) != 0)
goto err;
-
- return t;
+
+ return t;
err:
free(t);
free(ac);
return curl_thread_t_null;
-}
-
-void Curl_thread_destroy(curl_thread_t hnd)
-{
+}
+
+void Curl_thread_destroy(curl_thread_t hnd)
+{
if(hnd != curl_thread_t_null) {
pthread_detach(*hnd);
free(hnd);
}
-}
-
-int Curl_thread_join(curl_thread_t *hnd)
-{
+}
+
+int Curl_thread_join(curl_thread_t *hnd)
+{
int ret = (pthread_join(**hnd, NULL) == 0);
-
+
free(*hnd);
- *hnd = curl_thread_t_null;
-
- return ret;
-}
-
-#elif defined(USE_THREADS_WIN32)
-
+ *hnd = curl_thread_t_null;
+
+ return ret;
+}
+
+#elif defined(USE_THREADS_WIN32)
+
/* !checksrc! disable SPACEBEFOREPAREN 1 */
curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *),
- void *arg)
-{
-#ifdef _WIN32_WCE
+ void *arg)
+{
+#ifdef _WIN32_WCE
typedef HANDLE curl_win_thread_handle_t;
#elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
typedef unsigned long curl_win_thread_handle_t;
-#else
+#else
typedef uintptr_t curl_win_thread_handle_t;
#endif
- curl_thread_t t;
+ curl_thread_t t;
curl_win_thread_handle_t thread_handle;
#ifdef _WIN32_WCE
thread_handle = CreateThread(NULL, 0, func, arg, 0, NULL);
@@ -126,30 +126,30 @@ curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *),
gle == ERROR_NOT_ENOUGH_MEMORY) ?
EACCES : EINVAL);
#endif
- return curl_thread_t_null;
+ return curl_thread_t_null;
}
- return t;
-}
-
-void Curl_thread_destroy(curl_thread_t hnd)
-{
- CloseHandle(hnd);
-}
-
-int Curl_thread_join(curl_thread_t *hnd)
-{
+ return t;
+}
+
+void Curl_thread_destroy(curl_thread_t hnd)
+{
+ CloseHandle(hnd);
+}
+
+int Curl_thread_join(curl_thread_t *hnd)
+{
#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \
(_WIN32_WINNT < _WIN32_WINNT_VISTA)
- int ret = (WaitForSingleObject(*hnd, INFINITE) == WAIT_OBJECT_0);
+ int ret = (WaitForSingleObject(*hnd, INFINITE) == WAIT_OBJECT_0);
#else
int ret = (WaitForSingleObjectEx(*hnd, INFINITE, FALSE) == WAIT_OBJECT_0);
#endif
-
- Curl_thread_destroy(*hnd);
-
- *hnd = curl_thread_t_null;
-
- return ret;
-}
-
-#endif /* USE_THREADS_* */
+
+ Curl_thread_destroy(*hnd);
+
+ *hnd = curl_thread_t_null;
+
+ return ret;
+}
+
+#endif /* USE_THREADS_* */
diff --git a/contrib/libs/curl/lib/curl_threads.h b/contrib/libs/curl/lib/curl_threads.h
index 2aa7303b7c..55fc0ac559 100644
--- a/contrib/libs/curl/lib/curl_threads.h
+++ b/contrib/libs/curl/lib/curl_threads.h
@@ -1,42 +1,42 @@
-#ifndef HEADER_CURL_THREADS_H
-#define HEADER_CURL_THREADS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_THREADS_H
+#define HEADER_CURL_THREADS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#if defined(USE_THREADS_POSIX)
-# define CURL_STDCALL
-# define curl_mutex_t pthread_mutex_t
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#if defined(USE_THREADS_POSIX)
+# define CURL_STDCALL
+# define curl_mutex_t pthread_mutex_t
# define curl_thread_t pthread_t *
# define curl_thread_t_null (pthread_t *)0
-# define Curl_mutex_init(m) pthread_mutex_init(m, NULL)
-# define Curl_mutex_acquire(m) pthread_mutex_lock(m)
-# define Curl_mutex_release(m) pthread_mutex_unlock(m)
-# define Curl_mutex_destroy(m) pthread_mutex_destroy(m)
-#elif defined(USE_THREADS_WIN32)
-# define CURL_STDCALL __stdcall
-# define curl_mutex_t CRITICAL_SECTION
-# define curl_thread_t HANDLE
-# define curl_thread_t_null (HANDLE)0
+# define Curl_mutex_init(m) pthread_mutex_init(m, NULL)
+# define Curl_mutex_acquire(m) pthread_mutex_lock(m)
+# define Curl_mutex_release(m) pthread_mutex_unlock(m)
+# define Curl_mutex_destroy(m) pthread_mutex_destroy(m)
+#elif defined(USE_THREADS_WIN32)
+# define CURL_STDCALL __stdcall
+# define curl_mutex_t CRITICAL_SECTION
+# define curl_thread_t HANDLE
+# define curl_thread_t_null (HANDLE)0
/* The Windows init macro is made to return 0 on success so that it behaves the
same as pthreads init which returns 0 on success. */
# if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \
@@ -46,21 +46,21 @@
# else
# define Curl_mutex_init(m) (!InitializeCriticalSectionEx(m, 0, 1))
# endif
-# define Curl_mutex_acquire(m) EnterCriticalSection(m)
-# define Curl_mutex_release(m) LeaveCriticalSection(m)
-# define Curl_mutex_destroy(m) DeleteCriticalSection(m)
-#endif
-
-#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
-
+# define Curl_mutex_acquire(m) EnterCriticalSection(m)
+# define Curl_mutex_release(m) LeaveCriticalSection(m)
+# define Curl_mutex_destroy(m) DeleteCriticalSection(m)
+#endif
+
+#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
+
/* !checksrc! disable SPACEBEFOREPAREN 1 */
curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *),
- void *arg);
-
-void Curl_thread_destroy(curl_thread_t hnd);
-
-int Curl_thread_join(curl_thread_t *hnd);
-
-#endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */
-
-#endif /* HEADER_CURL_THREADS_H */
+ void *arg);
+
+void Curl_thread_destroy(curl_thread_t hnd);
+
+int Curl_thread_join(curl_thread_t *hnd);
+
+#endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */
+
+#endif /* HEADER_CURL_THREADS_H */
diff --git a/contrib/libs/curl/lib/curlx.h b/contrib/libs/curl/lib/curlx.h
index 539b4cfeae..9f21f60d5f 100644
--- a/contrib/libs/curl/lib/curlx.h
+++ b/contrib/libs/curl/lib/curlx.h
@@ -1,58 +1,58 @@
-#ifndef HEADER_CURL_CURLX_H
-#define HEADER_CURL_CURLX_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_CURLX_H
+#define HEADER_CURL_CURLX_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * Defines protos and includes all header files that provide the curlx_*
- * functions. The curlx_* functions are not part of the libcurl API, but are
- * stand-alone functions whose sources can be built and linked by apps if need
- * be.
- */
-
-#include <curl/mprintf.h>
-/* this is still a public header file that provides the curl_mprintf()
- functions while they still are offered publicly. They will be made library-
- private one day */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * Defines protos and includes all header files that provide the curlx_*
+ * functions. The curlx_* functions are not part of the libcurl API, but are
+ * stand-alone functions whose sources can be built and linked by apps if need
+ * be.
+ */
+
+#include <curl/mprintf.h>
+/* this is still a public header file that provides the curl_mprintf()
+ functions while they still are offered publicly. They will be made library-
+ private one day */
+
#include "strcase.h"
/* "strcase.h" provides the strcasecompare protos */
-
-#include "strtoofft.h"
-/* "strtoofft.h" provides this function: curlx_strtoofft(), returns a
- curl_off_t number from a given string.
-*/
-
-#include "nonblock.h"
-/* "nonblock.h" provides curlx_nonblock() */
-
-#include "warnless.h"
-/* "warnless.h" provides functions:
-
- curlx_ultous()
- curlx_ultouc()
- curlx_uztosi()
-*/
-
+
+#include "strtoofft.h"
+/* "strtoofft.h" provides this function: curlx_strtoofft(), returns a
+ curl_off_t number from a given string.
+*/
+
+#include "nonblock.h"
+/* "nonblock.h" provides curlx_nonblock() */
+
+#include "warnless.h"
+/* "warnless.h" provides functions:
+
+ curlx_ultous()
+ curlx_ultouc()
+ curlx_uztosi()
+*/
+
#include "curl_multibyte.h"
/* "curl_multibyte.h" provides these functions and macros:
@@ -66,51 +66,51 @@
#include "version_win32.h"
/* "version_win32.h" provides curlx_verify_windows_version() */
-/* Now setup curlx_ * names for the functions that are to become curlx_ and
- be removed from a future libcurl official API:
- curlx_getenv
- curlx_mprintf (and its variations)
+/* Now setup curlx_ * names for the functions that are to become curlx_ and
+ be removed from a future libcurl official API:
+ curlx_getenv
+ curlx_mprintf (and its variations)
curlx_strcasecompare
curlx_strncasecompare
-
-*/
-
-#define curlx_getenv curl_getenv
-#define curlx_mvsnprintf curl_mvsnprintf
-#define curlx_msnprintf curl_msnprintf
-#define curlx_maprintf curl_maprintf
-#define curlx_mvaprintf curl_mvaprintf
-#define curlx_msprintf curl_msprintf
-#define curlx_mprintf curl_mprintf
-#define curlx_mfprintf curl_mfprintf
-#define curlx_mvsprintf curl_mvsprintf
-#define curlx_mvprintf curl_mvprintf
-#define curlx_mvfprintf curl_mvfprintf
-
-#ifdef ENABLE_CURLX_PRINTF
-/* If this define is set, we define all "standard" printf() functions to use
- the curlx_* version instead. It makes the source code transparent and
+
+*/
+
+#define curlx_getenv curl_getenv
+#define curlx_mvsnprintf curl_mvsnprintf
+#define curlx_msnprintf curl_msnprintf
+#define curlx_maprintf curl_maprintf
+#define curlx_mvaprintf curl_mvaprintf
+#define curlx_msprintf curl_msprintf
+#define curlx_mprintf curl_mprintf
+#define curlx_mfprintf curl_mfprintf
+#define curlx_mvsprintf curl_mvsprintf
+#define curlx_mvprintf curl_mvprintf
+#define curlx_mvfprintf curl_mvfprintf
+
+#ifdef ENABLE_CURLX_PRINTF
+/* If this define is set, we define all "standard" printf() functions to use
+ the curlx_* version instead. It makes the source code transparent and
easier to understand/patch. Undefine them first. */
-# undef printf
-# undef fprintf
-# undef sprintf
+# undef printf
+# undef fprintf
+# undef sprintf
# undef msnprintf
-# undef vprintf
-# undef vfprintf
-# undef vsprintf
+# undef vprintf
+# undef vfprintf
+# undef vsprintf
# undef mvsnprintf
-# undef aprintf
-# undef vaprintf
-
-# define printf curlx_mprintf
-# define fprintf curlx_mfprintf
-# define sprintf curlx_msprintf
+# undef aprintf
+# undef vaprintf
+
+# define printf curlx_mprintf
+# define fprintf curlx_mfprintf
+# define sprintf curlx_msprintf
# define msnprintf curlx_msnprintf
-# define vprintf curlx_mvprintf
-# define vfprintf curlx_mvfprintf
+# define vprintf curlx_mvprintf
+# define vfprintf curlx_mvfprintf
# define mvsnprintf curlx_mvsnprintf
-# define aprintf curlx_maprintf
-# define vaprintf curlx_mvaprintf
-#endif /* ENABLE_CURLX_PRINTF */
-
-#endif /* HEADER_CURL_CURLX_H */
+# define aprintf curlx_maprintf
+# define vaprintf curlx_mvaprintf
+#endif /* ENABLE_CURLX_PRINTF */
+
+#endif /* HEADER_CURL_CURLX_H */
diff --git a/contrib/libs/curl/lib/dict.c b/contrib/libs/curl/lib/dict.c
index 74506d3389..15d3954aa3 100644
--- a/contrib/libs/curl/lib/dict.c
+++ b/contrib/libs/curl/lib/dict.c
@@ -1,133 +1,133 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_DICT
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_DICT
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
#elif defined(HAVE_UNISTD_H)
#include <unistd.h>
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
-#include "sendf.h"
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
+#include "sendf.h"
#include "escape.h"
-#include "progress.h"
-#include "dict.h"
+#include "progress.h"
+#include "dict.h"
#include "curl_printf.h"
#include "strcase.h"
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * Forward declarations.
- */
-
-static CURLcode dict_do(struct connectdata *conn, bool *done);
-
-/*
- * DICT protocol handler.
- */
-
-const struct Curl_handler Curl_handler_dict = {
- "DICT", /* scheme */
- ZERO_NULL, /* setup_connection */
- dict_do, /* do_it */
- ZERO_NULL, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * Forward declarations.
+ */
+
+static CURLcode dict_do(struct connectdata *conn, bool *done);
+
+/*
+ * DICT protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_dict = {
+ "DICT", /* scheme */
+ ZERO_NULL, /* setup_connection */
+ dict_do, /* do_it */
+ ZERO_NULL, /* done */
+ ZERO_NULL, /* do_more */
+ ZERO_NULL, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_DICT, /* defport */
- CURLPROTO_DICT, /* protocol */
+ PORT_DICT, /* defport */
+ CURLPROTO_DICT, /* protocol */
CURLPROTO_DICT, /* family */
PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
-};
-
+};
+
static char *unescape_word(struct Curl_easy *data, const char *inputbuff)
-{
+{
char *newp = NULL;
- char *dictp;
+ char *dictp;
size_t len;
-
+
CURLcode result = Curl_urldecode(data, inputbuff, 0, &newp, &len,
REJECT_NADA);
if(!newp || result)
- return NULL;
-
+ return NULL;
+
dictp = malloc(len*2 + 1); /* add one for terminating zero */
- if(dictp) {
+ if(dictp) {
char *ptr;
char ch;
int olen = 0;
- /* According to RFC2229 section 2.2, these letters need to be escaped with
- \[letter] */
- for(ptr = newp;
+ /* According to RFC2229 section 2.2, these letters need to be escaped with
+ \[letter] */
+ for(ptr = newp;
(ch = *ptr) != 0;
- ptr++) {
+ ptr++) {
if((ch <= 32) || (ch == 127) ||
(ch == '\'') || (ch == '\"') || (ch == '\\')) {
- dictp[olen++] = '\\';
- }
+ dictp[olen++] = '\\';
+ }
dictp[olen++] = ch;
- }
+ }
dictp[olen] = 0;
- }
+ }
free(newp);
- return dictp;
-}
-
+ return dictp;
+}
+
/* sendf() sends formatted data to the server */
static CURLcode sendf(curl_socket_t sockfd, struct connectdata *conn,
const char *fmt, ...)
@@ -173,63 +173,63 @@ static CURLcode sendf(curl_socket_t sockfd, struct connectdata *conn,
return result;
}
-static CURLcode dict_do(struct connectdata *conn, bool *done)
-{
- char *word;
- char *eword;
- char *ppath;
- char *database = NULL;
- char *strategy = NULL;
- char *nthdef = NULL; /* This is not part of the protocol, but required
- by RFC 2229 */
+static CURLcode dict_do(struct connectdata *conn, bool *done)
+{
+ char *word;
+ char *eword;
+ char *ppath;
+ char *database = NULL;
+ char *strategy = NULL;
+ char *nthdef = NULL; /* This is not part of the protocol, but required
+ by RFC 2229 */
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
-
+ curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
+
char *path = data->state.up.path;
-
- *done = TRUE; /* unconditionally */
-
- if(conn->bits.user_passwd) {
- /* AUTH is missing */
- }
-
+
+ *done = TRUE; /* unconditionally */
+
+ if(conn->bits.user_passwd) {
+ /* AUTH is missing */
+ }
+
if(strncasecompare(path, DICT_MATCH, sizeof(DICT_MATCH)-1) ||
strncasecompare(path, DICT_MATCH2, sizeof(DICT_MATCH2)-1) ||
strncasecompare(path, DICT_MATCH3, sizeof(DICT_MATCH3)-1)) {
-
- word = strchr(path, ':');
- if(word) {
- word++;
- database = strchr(word, ':');
- if(database) {
- *database++ = (char)0;
- strategy = strchr(database, ':');
- if(strategy) {
- *strategy++ = (char)0;
- nthdef = strchr(strategy, ':');
- if(nthdef) {
- *nthdef = (char)0;
- }
- }
- }
- }
-
- if((word == NULL) || (*word == (char)0)) {
- infof(data, "lookup word is missing\n");
+
+ word = strchr(path, ':');
+ if(word) {
+ word++;
+ database = strchr(word, ':');
+ if(database) {
+ *database++ = (char)0;
+ strategy = strchr(database, ':');
+ if(strategy) {
+ *strategy++ = (char)0;
+ nthdef = strchr(strategy, ':');
+ if(nthdef) {
+ *nthdef = (char)0;
+ }
+ }
+ }
+ }
+
+ if((word == NULL) || (*word == (char)0)) {
+ infof(data, "lookup word is missing\n");
word = (char *)"default";
- }
- if((database == NULL) || (*database == (char)0)) {
- database = (char *)"!";
- }
- if((strategy == NULL) || (*strategy == (char)0)) {
- strategy = (char *)".";
- }
-
- eword = unescape_word(data, word);
- if(!eword)
- return CURLE_OUT_OF_MEMORY;
-
+ }
+ if((database == NULL) || (*database == (char)0)) {
+ database = (char *)"!";
+ }
+ if((strategy == NULL) || (*strategy == (char)0)) {
+ strategy = (char *)".";
+ }
+
+ eword = unescape_word(data, word);
+ if(!eword)
+ return CURLE_OUT_OF_MEMORY;
+
result = sendf(sockfd, conn,
"CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n"
"MATCH "
@@ -240,44 +240,44 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
database,
strategy,
eword);
-
- free(eword);
-
- if(result) {
- failf(data, "Failed sending DICT request");
- return result;
- }
+
+ free(eword);
+
+ if(result) {
+ failf(data, "Failed sending DICT request");
+ return result;
+ }
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); /* no upload */
- }
+ }
else if(strncasecompare(path, DICT_DEFINE, sizeof(DICT_DEFINE)-1) ||
strncasecompare(path, DICT_DEFINE2, sizeof(DICT_DEFINE2)-1) ||
strncasecompare(path, DICT_DEFINE3, sizeof(DICT_DEFINE3)-1)) {
-
- word = strchr(path, ':');
- if(word) {
- word++;
- database = strchr(word, ':');
- if(database) {
- *database++ = (char)0;
- nthdef = strchr(database, ':');
- if(nthdef) {
- *nthdef = (char)0;
- }
- }
- }
-
- if((word == NULL) || (*word == (char)0)) {
- infof(data, "lookup word is missing\n");
+
+ word = strchr(path, ':');
+ if(word) {
+ word++;
+ database = strchr(word, ':');
+ if(database) {
+ *database++ = (char)0;
+ nthdef = strchr(database, ':');
+ if(nthdef) {
+ *nthdef = (char)0;
+ }
+ }
+ }
+
+ if((word == NULL) || (*word == (char)0)) {
+ infof(data, "lookup word is missing\n");
word = (char *)"default";
- }
- if((database == NULL) || (*database == (char)0)) {
- database = (char *)"!";
- }
-
- eword = unescape_word(data, word);
- if(!eword)
- return CURLE_OUT_OF_MEMORY;
-
+ }
+ if((database == NULL) || (*database == (char)0)) {
+ database = (char *)"!";
+ }
+
+ eword = unescape_word(data, word);
+ if(!eword)
+ return CURLE_OUT_OF_MEMORY;
+
result = sendf(sockfd, conn,
"CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n"
"DEFINE "
@@ -286,39 +286,39 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
"QUIT\r\n",
database,
eword);
-
- free(eword);
-
- if(result) {
- failf(data, "Failed sending DICT request");
- return result;
- }
+
+ free(eword);
+
+ if(result) {
+ failf(data, "Failed sending DICT request");
+ return result;
+ }
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
- }
- else {
-
- ppath = strchr(path, '/');
- if(ppath) {
- int i;
-
- ppath++;
- for(i = 0; ppath[i]; i++) {
- if(ppath[i] == ':')
- ppath[i] = ' ';
- }
+ }
+ else {
+
+ ppath = strchr(path, '/');
+ if(ppath) {
+ int i;
+
+ ppath++;
+ for(i = 0; ppath[i]; i++) {
+ if(ppath[i] == ':')
+ ppath[i] = ' ';
+ }
result = sendf(sockfd, conn,
"CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n"
"%s\r\n"
"QUIT\r\n", ppath);
- if(result) {
- failf(data, "Failed sending DICT request");
- return result;
- }
-
+ if(result) {
+ failf(data, "Failed sending DICT request");
+ return result;
+ }
+
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
- }
- }
-
- return CURLE_OK;
-}
-#endif /*CURL_DISABLE_DICT*/
+ }
+ }
+
+ return CURLE_OK;
+}
+#endif /*CURL_DISABLE_DICT*/
diff --git a/contrib/libs/curl/lib/dict.h b/contrib/libs/curl/lib/dict.h
index 272fd2579b..6a6c772d13 100644
--- a/contrib/libs/curl/lib/dict.h
+++ b/contrib/libs/curl/lib/dict.h
@@ -1,29 +1,29 @@
-#ifndef HEADER_CURL_DICT_H
-#define HEADER_CURL_DICT_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_DICT_H
+#define HEADER_CURL_DICT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#ifndef CURL_DISABLE_DICT
-extern const struct Curl_handler Curl_handler_dict;
-#endif
-
-#endif /* HEADER_CURL_DICT_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#ifndef CURL_DISABLE_DICT
+extern const struct Curl_handler Curl_handler_dict;
+#endif
+
+#endif /* HEADER_CURL_DICT_H */
diff --git a/contrib/libs/curl/lib/dotdot.c b/contrib/libs/curl/lib/dotdot.c
index bb67c5ec8c..3a1435f8ec 100644
--- a/contrib/libs/curl/lib/dotdot.c
+++ b/contrib/libs/curl/lib/dotdot.c
@@ -1,182 +1,182 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <curl/curl.h>
-#include "dotdot.h"
+#include "dotdot.h"
#include "curl_memory.h"
-
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * "Remove Dot Segments"
+
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * "Remove Dot Segments"
* https://tools.ietf.org/html/rfc3986#section-5.2.4
- */
-
-/*
- * Curl_dedotdotify()
+ */
+
+/*
+ * Curl_dedotdotify()
* @unittest: 1395
- *
+ *
* This function gets a null-terminated path with dot and dotdot sequences
- * passed in and strips them off according to the rules in RFC 3986 section
- * 5.2.4.
- *
- * The function handles a query part ('?' + stuff) appended but it expects
- * that fragments ('#' + stuff) have already been cut off.
- *
- * RETURNS
- *
- * an allocated dedotdotified output string
- */
+ * passed in and strips them off according to the rules in RFC 3986 section
+ * 5.2.4.
+ *
+ * The function handles a query part ('?' + stuff) appended but it expects
+ * that fragments ('#' + stuff) have already been cut off.
+ *
+ * RETURNS
+ *
+ * an allocated dedotdotified output string
+ */
char *Curl_dedotdotify(const char *input)
-{
- size_t inlen = strlen(input);
- char *clone;
- size_t clen = inlen; /* the length of the cloned input */
+{
+ size_t inlen = strlen(input);
+ char *clone;
+ size_t clen = inlen; /* the length of the cloned input */
char *out = malloc(inlen + 1);
- char *outptr;
- char *orgclone;
- char *queryp;
- if(!out)
- return NULL; /* out of memory */
-
+ char *outptr;
+ char *orgclone;
+ char *queryp;
+ if(!out)
+ return NULL; /* out of memory */
+
*out = 0; /* null-terminates, for inputs like "./" */
- /* get a cloned copy of the input */
- clone = strdup(input);
- if(!clone) {
- free(out);
- return NULL;
- }
- orgclone = clone;
- outptr = out;
-
+ /* get a cloned copy of the input */
+ clone = strdup(input);
+ if(!clone) {
+ free(out);
+ return NULL;
+ }
+ orgclone = clone;
+ outptr = out;
+
if(!*clone) {
/* zero length string, return that */
free(out);
return clone;
}
- /*
- * To handle query-parts properly, we must find it and remove it during the
- * dotdot-operation and then append it again at the end to the output
- * string.
- */
- queryp = strchr(clone, '?');
- if(queryp)
- *queryp = 0;
-
- do {
-
- /* A. If the input buffer begins with a prefix of "../" or "./", then
- remove that prefix from the input buffer; otherwise, */
-
- if(!strncmp("./", clone, 2)) {
+ /*
+ * To handle query-parts properly, we must find it and remove it during the
+ * dotdot-operation and then append it again at the end to the output
+ * string.
+ */
+ queryp = strchr(clone, '?');
+ if(queryp)
+ *queryp = 0;
+
+ do {
+
+ /* A. If the input buffer begins with a prefix of "../" or "./", then
+ remove that prefix from the input buffer; otherwise, */
+
+ if(!strncmp("./", clone, 2)) {
clone += 2;
clen -= 2;
- }
- else if(!strncmp("../", clone, 3)) {
+ }
+ else if(!strncmp("../", clone, 3)) {
clone += 3;
clen -= 3;
- }
-
- /* B. if the input buffer begins with a prefix of "/./" or "/.", where
- "." is a complete path segment, then replace that prefix with "/" in
- the input buffer; otherwise, */
- else if(!strncmp("/./", clone, 3)) {
+ }
+
+ /* B. if the input buffer begins with a prefix of "/./" or "/.", where
+ "." is a complete path segment, then replace that prefix with "/" in
+ the input buffer; otherwise, */
+ else if(!strncmp("/./", clone, 3)) {
clone += 2;
clen -= 2;
- }
- else if(!strcmp("/.", clone)) {
- clone[1]='/';
- clone++;
+ }
+ else if(!strcmp("/.", clone)) {
+ clone[1]='/';
+ clone++;
clen -= 1;
- }
-
- /* C. if the input buffer begins with a prefix of "/../" or "/..", where
- ".." is a complete path segment, then replace that prefix with "/" in
- the input buffer and remove the last segment and its preceding "/" (if
- any) from the output buffer; otherwise, */
-
- else if(!strncmp("/../", clone, 4)) {
+ }
+
+ /* C. if the input buffer begins with a prefix of "/../" or "/..", where
+ ".." is a complete path segment, then replace that prefix with "/" in
+ the input buffer and remove the last segment and its preceding "/" (if
+ any) from the output buffer; otherwise, */
+
+ else if(!strncmp("/../", clone, 4)) {
clone += 3;
clen -= 3;
- /* remove the last segment from the output buffer */
- while(outptr > out) {
- outptr--;
- if(*outptr == '/')
- break;
- }
+ /* remove the last segment from the output buffer */
+ while(outptr > out) {
+ outptr--;
+ if(*outptr == '/')
+ break;
+ }
*outptr = 0; /* null-terminate where it stops */
- }
- else if(!strcmp("/..", clone)) {
- clone[2]='/';
+ }
+ else if(!strcmp("/..", clone)) {
+ clone[2]='/';
clone += 2;
clen -= 2;
- /* remove the last segment from the output buffer */
- while(outptr > out) {
- outptr--;
- if(*outptr == '/')
- break;
- }
+ /* remove the last segment from the output buffer */
+ while(outptr > out) {
+ outptr--;
+ if(*outptr == '/')
+ break;
+ }
*outptr = 0; /* null-terminate where it stops */
- }
-
- /* D. if the input buffer consists only of "." or "..", then remove
- that from the input buffer; otherwise, */
-
- else if(!strcmp(".", clone) || !strcmp("..", clone)) {
+ }
+
+ /* D. if the input buffer consists only of "." or "..", then remove
+ that from the input buffer; otherwise, */
+
+ else if(!strcmp(".", clone) || !strcmp("..", clone)) {
*clone = 0;
*out = 0;
- }
-
- else {
- /* E. move the first path segment in the input buffer to the end of
- the output buffer, including the initial "/" character (if any) and
- any subsequent characters up to, but not including, the next "/"
- character or the end of the input buffer. */
-
- do {
- *outptr++ = *clone++;
- clen--;
- } while(*clone && (*clone != '/'));
- *outptr = 0;
- }
-
- } while(*clone);
-
- if(queryp) {
- size_t qlen;
- /* There was a query part, append that to the output. The 'clone' string
- may now have been altered so we copy from the original input string
- from the correct index. */
- size_t oindex = queryp - orgclone;
- qlen = strlen(&input[oindex]);
+ }
+
+ else {
+ /* E. move the first path segment in the input buffer to the end of
+ the output buffer, including the initial "/" character (if any) and
+ any subsequent characters up to, but not including, the next "/"
+ character or the end of the input buffer. */
+
+ do {
+ *outptr++ = *clone++;
+ clen--;
+ } while(*clone && (*clone != '/'));
+ *outptr = 0;
+ }
+
+ } while(*clone);
+
+ if(queryp) {
+ size_t qlen;
+ /* There was a query part, append that to the output. The 'clone' string
+ may now have been altered so we copy from the original input string
+ from the correct index. */
+ size_t oindex = queryp - orgclone;
+ qlen = strlen(&input[oindex]);
memcpy(outptr, &input[oindex], qlen + 1); /* include the end zero byte */
- }
-
- free(orgclone);
- return out;
-}
+ }
+
+ free(orgclone);
+ return out;
+}
diff --git a/contrib/libs/curl/lib/dotdot.h b/contrib/libs/curl/lib/dotdot.h
index 5f8384ca40..ac1ea363e1 100644
--- a/contrib/libs/curl/lib/dotdot.h
+++ b/contrib/libs/curl/lib/dotdot.h
@@ -1,25 +1,25 @@
-#ifndef HEADER_CURL_DOTDOT_H
-#define HEADER_CURL_DOTDOT_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_DOTDOT_H
+#define HEADER_CURL_DOTDOT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
char *Curl_dedotdotify(const char *input);
#endif /* HEADER_CURL_DOTDOT_H */
diff --git a/contrib/libs/curl/lib/easy.c b/contrib/libs/curl/lib/easy.c
index 4952cbfdbf..dc790b01df 100644
--- a/contrib/libs/curl/lib/easy.c
+++ b/contrib/libs/curl/lib/easy.c
@@ -1,76 +1,76 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-/*
- * See comment in curl_memory.h for the explanation of this sanity check.
- */
-
-#ifdef CURLX_NO_MEMORY_CALLBACKS
-#error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined"
-#endif
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+/*
+ * See comment in curl_memory.h for the explanation of this sanity check.
+ */
+
+#ifdef CURLX_NO_MEMORY_CALLBACKS
+#error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined"
+#endif
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
#include "vtls/vtls.h"
-#include "url.h"
-#include "getinfo.h"
-#include "hostip.h"
-#include "share.h"
-#include "strdup.h"
-#include "progress.h"
-#include "easyif.h"
+#include "url.h"
+#include "getinfo.h"
+#include "hostip.h"
+#include "share.h"
+#include "strdup.h"
+#include "progress.h"
+#include "easyif.h"
#include "multiif.h"
-#include "select.h"
-#include "sendf.h" /* for failf function prototype */
-#include "connect.h" /* for Curl_getconnectinfo */
-#include "slist.h"
+#include "select.h"
+#include "sendf.h" /* for failf function prototype */
+#include "connect.h" /* for Curl_getconnectinfo */
+#include "slist.h"
#include "mime.h"
-#include "amigaos.h"
-#include "non-ascii.h"
-#include "warnless.h"
-#include "multiif.h"
+#include "amigaos.h"
+#include "non-ascii.h"
+#include "warnless.h"
+#include "multiif.h"
#include "sigpipe.h"
#include "vssh/ssh.h"
#include "setopt.h"
@@ -80,59 +80,59 @@
#include "dynbuf.h"
#include "altsvc.h"
#include "hsts.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-/* true globals -- for curl_global_init() and curl_global_cleanup() */
-static unsigned int initialized;
-static long init_flags;
-
-/*
- * strdup (and other memory functions) is redefined in complicated
- * ways, but at this point it must be defined as the system-supplied strdup
- * so the callback pointer is initialized correctly.
- */
-#if defined(_WIN32_WCE)
-#define system_strdup _strdup
-#elif !defined(HAVE_STRDUP)
-#define system_strdup curlx_strdup
-#else
-#define system_strdup strdup
-#endif
-
-#if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
-# pragma warning(disable:4232) /* MSVC extension, dllimport identity */
-#endif
-
-/*
- * If a memory-using function (like curl_getenv) is used before
- * curl_global_init() is called, we need to have these pointers set already.
- */
-curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
-curl_free_callback Curl_cfree = (curl_free_callback)free;
-curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
-curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
-curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
-#if defined(WIN32) && defined(UNICODE)
-curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
-#endif
-
-#if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
-# pragma warning(default:4232) /* MSVC extension, dllimport identity */
-#endif
-
-/**
+#include "memdebug.h"
+
+/* true globals -- for curl_global_init() and curl_global_cleanup() */
+static unsigned int initialized;
+static long init_flags;
+
+/*
+ * strdup (and other memory functions) is redefined in complicated
+ * ways, but at this point it must be defined as the system-supplied strdup
+ * so the callback pointer is initialized correctly.
+ */
+#if defined(_WIN32_WCE)
+#define system_strdup _strdup
+#elif !defined(HAVE_STRDUP)
+#define system_strdup curlx_strdup
+#else
+#define system_strdup strdup
+#endif
+
+#if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
+# pragma warning(disable:4232) /* MSVC extension, dllimport identity */
+#endif
+
+/*
+ * If a memory-using function (like curl_getenv) is used before
+ * curl_global_init() is called, we need to have these pointers set already.
+ */
+curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
+curl_free_callback Curl_cfree = (curl_free_callback)free;
+curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
+curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
+curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
+#if defined(WIN32) && defined(UNICODE)
+curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
+#endif
+
+#if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
+# pragma warning(default:4232) /* MSVC extension, dllimport identity */
+#endif
+
+/**
* curl_global_init() globally initializes curl given a bitwise set of the
- * different features of what to initialize.
- */
+ * different features of what to initialize.
+ */
static CURLcode global_init(long flags, bool memoryfuncs)
-{
- if(initialized++)
- return CURLE_OK;
-
+{
+ if(initialized++)
+ return CURLE_OK;
+
if(memoryfuncs) {
/* Setup the default memory functions here (again) */
Curl_cmalloc = (curl_malloc_callback)malloc;
@@ -140,41 +140,41 @@ static CURLcode global_init(long flags, bool memoryfuncs)
Curl_crealloc = (curl_realloc_callback)realloc;
Curl_cstrdup = (curl_strdup_callback)system_strdup;
Curl_ccalloc = (curl_calloc_callback)calloc;
-#if defined(WIN32) && defined(UNICODE)
+#if defined(WIN32) && defined(UNICODE)
Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
-#endif
+#endif
}
-
+
if(!Curl_ssl_init()) {
DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
goto fail;
}
-
+
#ifdef WIN32
if(Curl_win32_init(flags)) {
DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
goto fail;
}
#endif
-
-#ifdef __AMIGA__
- if(!Curl_amiga_init()) {
- DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
+
+#ifdef __AMIGA__
+ if(!Curl_amiga_init()) {
+ DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
goto fail;
- }
-#endif
-
-#ifdef NETWARE
- if(netware_init()) {
- DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n"));
- }
-#endif
-
+ }
+#endif
+
+#ifdef NETWARE
+ if(netware_init()) {
+ DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n"));
+ }
+#endif
+
if(Curl_resolver_global_init()) {
- DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
+ DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
goto fail;
- }
-
+ }
+
#if defined(USE_SSH)
if(Curl_ssh_init()) {
goto fail;
@@ -184,19 +184,19 @@ static CURLcode global_init(long flags, bool memoryfuncs)
#ifdef USE_WOLFSSH
if(WS_SUCCESS != wolfSSH_Init()) {
DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n"));
- return CURLE_FAILED_INIT;
- }
-#endif
-
+ return CURLE_FAILED_INIT;
+ }
+#endif
+
init_flags = flags;
-
+
return CURLE_OK;
fail:
initialized--; /* undo the increase */
return CURLE_FAILED_INIT;
-}
-
+}
+
/**
* curl_global_init() globally initializes curl given a bitwise set of the
@@ -207,26 +207,26 @@ CURLcode curl_global_init(long flags)
return global_init(flags, TRUE);
}
-/*
+/*
* curl_global_init_mem() globally initializes curl and also registers the
- * user provided callback routines.
- */
-CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
- curl_free_callback f, curl_realloc_callback r,
- curl_strdup_callback s, curl_calloc_callback c)
-{
- /* Invalid input, return immediately */
- if(!m || !f || !r || !s || !c)
- return CURLE_FAILED_INIT;
-
+ * user provided callback routines.
+ */
+CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
+ curl_free_callback f, curl_realloc_callback r,
+ curl_strdup_callback s, curl_calloc_callback c)
+{
+ /* Invalid input, return immediately */
+ if(!m || !f || !r || !s || !c)
+ return CURLE_FAILED_INIT;
+
if(initialized) {
/* Already initialized, don't do it again, but bump the variable anyway to
work like curl_global_init() and require the same amount of cleanup
calls. */
initialized++;
- return CURLE_OK;
- }
-
+ return CURLE_OK;
+ }
+
/* set memory functions before global_init() in case it wants memory
functions */
Curl_cmalloc = m;
@@ -237,197 +237,197 @@ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
/* Call the actual init function, but without setting */
return global_init(flags, FALSE);
-}
-
-/**
+}
+
+/**
* curl_global_cleanup() globally cleanups curl, uses the value of
- * "init_flags" to determine what needs to be cleaned up and what doesn't.
- */
-void curl_global_cleanup(void)
-{
- if(!initialized)
- return;
-
- if(--initialized)
- return;
-
+ * "init_flags" to determine what needs to be cleaned up and what doesn't.
+ */
+void curl_global_cleanup(void)
+{
+ if(!initialized)
+ return;
+
+ if(--initialized)
+ return;
+
Curl_ssl_cleanup();
- Curl_resolver_global_cleanup();
-
+ Curl_resolver_global_cleanup();
+
#ifdef WIN32
Curl_win32_cleanup(init_flags);
#endif
-
- Curl_amiga_cleanup();
-
+
+ Curl_amiga_cleanup();
+
Curl_ssh_cleanup();
-
+
#ifdef USE_WOLFSSH
(void)wolfSSH_Cleanup();
#endif
- init_flags = 0;
-}
-
-/*
- * curl_easy_init() is the external interface to alloc, setup and init an
- * easy handle that is returned. If anything goes wrong, NULL is returned.
- */
+ init_flags = 0;
+}
+
+/*
+ * curl_easy_init() is the external interface to alloc, setup and init an
+ * easy handle that is returned. If anything goes wrong, NULL is returned.
+ */
struct Curl_easy *curl_easy_init(void)
-{
+{
CURLcode result;
struct Curl_easy *data;
-
- /* Make sure we inited the global SSL stuff */
- if(!initialized) {
+
+ /* Make sure we inited the global SSL stuff */
+ if(!initialized) {
result = curl_global_init(CURL_GLOBAL_DEFAULT);
if(result) {
- /* something in the global init failed, return nothing */
- DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
- return NULL;
- }
- }
-
- /* We use curl_open() with undefined URL so far */
+ /* something in the global init failed, return nothing */
+ DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
+ return NULL;
+ }
+ }
+
+ /* We use curl_open() with undefined URL so far */
result = Curl_open(&data);
if(result) {
- DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
- return NULL;
- }
-
- return data;
-}
-
-#ifdef CURLDEBUG
-
-struct socketmonitor {
- struct socketmonitor *next; /* the next node in the list or NULL */
- struct pollfd socket; /* socket info of what to monitor */
-};
-
-struct events {
- long ms; /* timeout, run the timeout function when reached */
- bool msbump; /* set TRUE when timeout is set by callback */
- int num_sockets; /* number of nodes in the monitor list */
- struct socketmonitor *list; /* list of sockets to monitor */
- int running_handles; /* store the returned number */
-};
-
-/* events_timer
- *
- * Callback that gets called with a new value when the timeout should be
- * updated.
- */
-
+ DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
+ return NULL;
+ }
+
+ return data;
+}
+
+#ifdef CURLDEBUG
+
+struct socketmonitor {
+ struct socketmonitor *next; /* the next node in the list or NULL */
+ struct pollfd socket; /* socket info of what to monitor */
+};
+
+struct events {
+ long ms; /* timeout, run the timeout function when reached */
+ bool msbump; /* set TRUE when timeout is set by callback */
+ int num_sockets; /* number of nodes in the monitor list */
+ struct socketmonitor *list; /* list of sockets to monitor */
+ int running_handles; /* store the returned number */
+};
+
+/* events_timer
+ *
+ * Callback that gets called with a new value when the timeout should be
+ * updated.
+ */
+
static int events_timer(struct Curl_multi *multi, /* multi handle */
- long timeout_ms, /* see above */
- void *userp) /* private callback pointer */
-{
- struct events *ev = userp;
- (void)multi;
- if(timeout_ms == -1)
- /* timeout removed */
- timeout_ms = 0;
- else if(timeout_ms == 0)
- /* timeout is already reached! */
- timeout_ms = 1; /* trigger asap */
-
- ev->ms = timeout_ms;
- ev->msbump = TRUE;
- return 0;
-}
-
-
-/* poll2cselect
- *
- * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
- */
-static int poll2cselect(int pollmask)
-{
+ long timeout_ms, /* see above */
+ void *userp) /* private callback pointer */
+{
+ struct events *ev = userp;
+ (void)multi;
+ if(timeout_ms == -1)
+ /* timeout removed */
+ timeout_ms = 0;
+ else if(timeout_ms == 0)
+ /* timeout is already reached! */
+ timeout_ms = 1; /* trigger asap */
+
+ ev->ms = timeout_ms;
+ ev->msbump = TRUE;
+ return 0;
+}
+
+
+/* poll2cselect
+ *
+ * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
+ */
+static int poll2cselect(int pollmask)
+{
int omask = 0;
- if(pollmask & POLLIN)
- omask |= CURL_CSELECT_IN;
- if(pollmask & POLLOUT)
- omask |= CURL_CSELECT_OUT;
- if(pollmask & POLLERR)
- omask |= CURL_CSELECT_ERR;
- return omask;
-}
-
-
-/* socketcb2poll
- *
- * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
- */
-static short socketcb2poll(int pollmask)
-{
+ if(pollmask & POLLIN)
+ omask |= CURL_CSELECT_IN;
+ if(pollmask & POLLOUT)
+ omask |= CURL_CSELECT_OUT;
+ if(pollmask & POLLERR)
+ omask |= CURL_CSELECT_ERR;
+ return omask;
+}
+
+
+/* socketcb2poll
+ *
+ * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
+ */
+static short socketcb2poll(int pollmask)
+{
short omask = 0;
- if(pollmask & CURL_POLL_IN)
- omask |= POLLIN;
- if(pollmask & CURL_POLL_OUT)
- omask |= POLLOUT;
- return omask;
-}
-
-/* events_socket
- *
- * Callback that gets called with information about socket activity to
- * monitor.
- */
+ if(pollmask & CURL_POLL_IN)
+ omask |= POLLIN;
+ if(pollmask & CURL_POLL_OUT)
+ omask |= POLLOUT;
+ return omask;
+}
+
+/* events_socket
+ *
+ * Callback that gets called with information about socket activity to
+ * monitor.
+ */
static int events_socket(struct Curl_easy *easy, /* easy handle */
- curl_socket_t s, /* socket */
- int what, /* see above */
- void *userp, /* private callback
- pointer */
- void *socketp) /* private socket
- pointer */
-{
- struct events *ev = userp;
- struct socketmonitor *m;
+ curl_socket_t s, /* socket */
+ int what, /* see above */
+ void *userp, /* private callback
+ pointer */
+ void *socketp) /* private socket
+ pointer */
+{
+ struct events *ev = userp;
+ struct socketmonitor *m;
struct socketmonitor *prev = NULL;
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) easy;
#endif
- (void)socketp;
-
- m = ev->list;
- while(m) {
- if(m->socket.fd == s) {
-
- if(what == CURL_POLL_REMOVE) {
- struct socketmonitor *nxt = m->next;
- /* remove this node from the list of monitored sockets */
- if(prev)
- prev->next = nxt;
- else
- ev->list = nxt;
- free(m);
- m = nxt;
- infof(easy, "socket cb: socket %d REMOVED\n", s);
- }
- else {
- /* The socket 's' is already being monitored, update the activity
- mask. Convert from libcurl bitmask to the poll one. */
- m->socket.events = socketcb2poll(what);
- infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s,
+ (void)socketp;
+
+ m = ev->list;
+ while(m) {
+ if(m->socket.fd == s) {
+
+ if(what == CURL_POLL_REMOVE) {
+ struct socketmonitor *nxt = m->next;
+ /* remove this node from the list of monitored sockets */
+ if(prev)
+ prev->next = nxt;
+ else
+ ev->list = nxt;
+ free(m);
+ m = nxt;
+ infof(easy, "socket cb: socket %d REMOVED\n", s);
+ }
+ else {
+ /* The socket 's' is already being monitored, update the activity
+ mask. Convert from libcurl bitmask to the poll one. */
+ m->socket.events = socketcb2poll(what);
+ infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s,
(what&CURL_POLL_IN)?"IN":"",
(what&CURL_POLL_OUT)?"OUT":"");
- }
- break;
- }
- prev = m;
- m = m->next; /* move to next node */
- }
- if(!m) {
- if(what == CURL_POLL_REMOVE) {
- /* this happens a bit too often, libcurl fix perhaps? */
- /* fprintf(stderr,
- "%s: socket %d asked to be REMOVED but not present!\n",
- __func__, s); */
- }
- else {
- m = malloc(sizeof(struct socketmonitor));
+ }
+ break;
+ }
+ prev = m;
+ m = m->next; /* move to next node */
+ }
+ if(!m) {
+ if(what == CURL_POLL_REMOVE) {
+ /* this happens a bit too often, libcurl fix perhaps? */
+ /* fprintf(stderr,
+ "%s: socket %d asked to be REMOVED but not present!\n",
+ __func__, s); */
+ }
+ else {
+ m = malloc(sizeof(struct socketmonitor));
if(m) {
m->next = ev->list;
m->socket.fd = s;
@@ -440,96 +440,96 @@ static int events_socket(struct Curl_easy *easy, /* easy handle */
}
else
return CURLE_OUT_OF_MEMORY;
- }
- }
-
- return 0;
-}
-
-
-/*
- * events_setup()
- *
- * Do the multi handle setups that only event-based transfers need.
- */
+ }
+ }
+
+ return 0;
+}
+
+
+/*
+ * events_setup()
+ *
+ * Do the multi handle setups that only event-based transfers need.
+ */
static void events_setup(struct Curl_multi *multi, struct events *ev)
-{
- /* timer callback */
- curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
- curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
-
- /* socket callback */
- curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
- curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
-}
-
-
-/* wait_or_timeout()
- *
- * waits for activity on any of the given sockets, or the timeout to trigger.
- */
-
-static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
-{
- bool done = FALSE;
+{
+ /* timer callback */
+ curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
+ curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
+
+ /* socket callback */
+ curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
+ curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
+}
+
+
+/* wait_or_timeout()
+ *
+ * waits for activity on any of the given sockets, or the timeout to trigger.
+ */
+
+static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
+{
+ bool done = FALSE;
CURLMcode mcode = CURLM_OK;
CURLcode result = CURLE_OK;
-
- while(!done) {
- CURLMsg *msg;
- struct socketmonitor *m;
- struct pollfd *f;
- struct pollfd fds[4];
+
+ while(!done) {
+ CURLMsg *msg;
+ struct socketmonitor *m;
+ struct pollfd *f;
+ struct pollfd fds[4];
int numfds = 0;
- int pollrc;
- int i;
+ int pollrc;
+ int i;
struct curltime before;
struct curltime after;
-
- /* populate the fds[] array */
+
+ /* populate the fds[] array */
for(m = ev->list, f = &fds[0]; m; m = m->next) {
- f->fd = m->socket.fd;
- f->events = m->socket.events;
- f->revents = 0;
- /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
- f++;
- numfds++;
- }
-
- /* get the time stamp to use to figure out how long poll takes */
+ f->fd = m->socket.fd;
+ f->events = m->socket.events;
+ f->revents = 0;
+ /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
+ f++;
+ numfds++;
+ }
+
+ /* get the time stamp to use to figure out how long poll takes */
before = Curl_now();
-
- /* wait for activity or timeout */
+
+ /* wait for activity or timeout */
pollrc = Curl_poll(fds, numfds, ev->ms);
-
+
after = Curl_now();
-
- ev->msbump = FALSE; /* reset here */
-
- if(0 == pollrc) {
- /* timeout! */
- ev->ms = 0;
+
+ ev->msbump = FALSE; /* reset here */
+
+ if(0 == pollrc) {
+ /* timeout! */
+ ev->ms = 0;
/* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */
- mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
- &ev->running_handles);
- }
- else if(pollrc > 0) {
- /* loop over the monitored sockets to see which ones had activity */
- for(i = 0; i< numfds; i++) {
- if(fds[i].revents) {
- /* socket activity, tell libcurl */
- int act = poll2cselect(fds[i].revents); /* convert */
+ mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
+ &ev->running_handles);
+ }
+ else if(pollrc > 0) {
+ /* loop over the monitored sockets to see which ones had activity */
+ for(i = 0; i< numfds; i++) {
+ if(fds[i].revents) {
+ /* socket activity, tell libcurl */
+ int act = poll2cselect(fds[i].revents); /* convert */
infof(multi->easyp, "call curl_multi_socket_action(socket %d)\n",
- fds[i].fd);
- mcode = curl_multi_socket_action(multi, fds[i].fd, act,
- &ev->running_handles);
- }
- }
-
+ fds[i].fd);
+ mcode = curl_multi_socket_action(multi, fds[i].fd, act,
+ &ev->running_handles);
+ }
+ }
+
if(!ev->msbump) {
- /* If nothing updated the timeout, we decrease it by the spent time.
- * If it was updated, it has the new timeout time stored already.
- */
+ /* If nothing updated the timeout, we decrease it by the spent time.
+ * If it was updated, it has the new timeout time stored already.
+ */
timediff_t timediff = Curl_timediff(after, before);
if(timediff > 0) {
if(timediff > ev->ms)
@@ -541,67 +541,67 @@ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
}
else
return CURLE_RECV_ERROR;
-
- if(mcode)
+
+ if(mcode)
return CURLE_URL_MALFORMAT;
-
- /* we don't really care about the "msgs_in_queue" value returned in the
- second argument */
- msg = curl_multi_info_read(multi, &pollrc);
- if(msg) {
+
+ /* we don't really care about the "msgs_in_queue" value returned in the
+ second argument */
+ msg = curl_multi_info_read(multi, &pollrc);
+ if(msg) {
result = msg->data.result;
- done = TRUE;
- }
- }
-
+ done = TRUE;
+ }
+ }
+
return result;
-}
-
-
-/* easy_events()
- *
- * Runs a transfer in a blocking manner using the events-based API
- */
+}
+
+
+/* easy_events()
+ *
+ * Runs a transfer in a blocking manner using the events-based API
+ */
static CURLcode easy_events(struct Curl_multi *multi)
-{
+{
/* this struct is made static to allow it to be used after this function
returns and curl_multi_remove_handle() is called */
static struct events evs = {2, FALSE, 0, NULL, 0};
-
- /* if running event-based, do some further multi inits */
- events_setup(multi, &evs);
-
- return wait_or_timeout(multi, &evs);
-}
-#else /* CURLDEBUG */
-/* when not built with debug, this function doesn't exist */
-#define easy_events(x) CURLE_NOT_BUILT_IN
-#endif
-
+
+ /* if running event-based, do some further multi inits */
+ events_setup(multi, &evs);
+
+ return wait_or_timeout(multi, &evs);
+}
+#else /* CURLDEBUG */
+/* when not built with debug, this function doesn't exist */
+#define easy_events(x) CURLE_NOT_BUILT_IN
+#endif
+
static CURLcode easy_transfer(struct Curl_multi *multi)
-{
- bool done = FALSE;
- CURLMcode mcode = CURLM_OK;
+{
+ bool done = FALSE;
+ CURLMcode mcode = CURLM_OK;
CURLcode result = CURLE_OK;
-
- while(!done && !mcode) {
+
+ while(!done && !mcode) {
int still_running = 0;
-
+
mcode = curl_multi_poll(multi, NULL, 0, 1000, NULL);
-
+
if(!mcode)
- mcode = curl_multi_perform(multi, &still_running);
-
- /* only read 'still_running' if curl_multi_perform() return OK */
+ mcode = curl_multi_perform(multi, &still_running);
+
+ /* only read 'still_running' if curl_multi_perform() return OK */
if(!mcode && !still_running) {
- int rc;
- CURLMsg *msg = curl_multi_info_read(multi, &rc);
- if(msg) {
+ int rc;
+ CURLMsg *msg = curl_multi_info_read(multi, &rc);
+ if(msg) {
result = msg->data.result;
- done = TRUE;
- }
- }
- }
+ done = TRUE;
+ }
+ }
+ }
/* Make sure to return some kind of error if there was a multi problem */
if(mcode) {
@@ -612,144 +612,144 @@ static CURLcode easy_transfer(struct Curl_multi *multi)
}
return result;
-}
-
-
-/*
- * easy_perform() is the external interface that performs a blocking
- * transfer as previously setup.
- *
- * CONCEPT: This function creates a multi handle, adds the easy handle to it,
- * runs curl_multi_perform() until the transfer is done, then detaches the
- * easy handle, destroys the multi handle and returns the easy handle's return
- * code.
- *
- * REALITY: it can't just create and destroy the multi handle that easily. It
- * needs to keep it around since if this easy handle is used again by this
- * function, the same multi handle must be re-used so that the same pools and
- * caches can be used.
- *
- * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
- * instead of curl_multi_perform() and use curl_multi_socket_action().
- */
+}
+
+
+/*
+ * easy_perform() is the external interface that performs a blocking
+ * transfer as previously setup.
+ *
+ * CONCEPT: This function creates a multi handle, adds the easy handle to it,
+ * runs curl_multi_perform() until the transfer is done, then detaches the
+ * easy handle, destroys the multi handle and returns the easy handle's return
+ * code.
+ *
+ * REALITY: it can't just create and destroy the multi handle that easily. It
+ * needs to keep it around since if this easy handle is used again by this
+ * function, the same multi handle must be re-used so that the same pools and
+ * caches can be used.
+ *
+ * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
+ * instead of curl_multi_perform() and use curl_multi_socket_action().
+ */
static CURLcode easy_perform(struct Curl_easy *data, bool events)
-{
+{
struct Curl_multi *multi;
- CURLMcode mcode;
+ CURLMcode mcode;
CURLcode result = CURLE_OK;
- SIGPIPE_VARIABLE(pipe_st);
-
- if(!data)
- return CURLE_BAD_FUNCTION_ARGUMENT;
-
+ SIGPIPE_VARIABLE(pipe_st);
+
+ if(!data)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
if(data->set.errorbuffer)
/* clear this as early as possible */
data->set.errorbuffer[0] = 0;
- if(data->multi) {
+ if(data->multi) {
failf(data, "easy handle already used in multi handle");
- return CURLE_FAILED_INIT;
- }
-
- if(data->multi_easy)
- multi = data->multi_easy;
- else {
- /* this multi handle will only ever have a single easy handled attached
- to it, so make it use minimal hashes */
- multi = Curl_multi_handle(1, 3);
- if(!multi)
- return CURLE_OUT_OF_MEMORY;
- data->multi_easy = multi;
- }
-
+ return CURLE_FAILED_INIT;
+ }
+
+ if(data->multi_easy)
+ multi = data->multi_easy;
+ else {
+ /* this multi handle will only ever have a single easy handled attached
+ to it, so make it use minimal hashes */
+ multi = Curl_multi_handle(1, 3);
+ if(!multi)
+ return CURLE_OUT_OF_MEMORY;
+ data->multi_easy = multi;
+ }
+
if(multi->in_callback)
return CURLE_RECURSIVE_API_CALL;
- /* Copy the MAXCONNECTS option to the multi handle */
- curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
-
- mcode = curl_multi_add_handle(multi, data);
- if(mcode) {
- curl_multi_cleanup(multi);
+ /* Copy the MAXCONNECTS option to the multi handle */
+ curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
+
+ mcode = curl_multi_add_handle(multi, data);
+ if(mcode) {
+ curl_multi_cleanup(multi);
data->multi_easy = NULL;
- if(mcode == CURLM_OUT_OF_MEMORY)
- return CURLE_OUT_OF_MEMORY;
+ if(mcode == CURLM_OUT_OF_MEMORY)
+ return CURLE_OUT_OF_MEMORY;
return CURLE_FAILED_INIT;
- }
-
- sigpipe_ignore(data, &pipe_st);
-
- /* run the transfer */
+ }
+
+ sigpipe_ignore(data, &pipe_st);
+
+ /* run the transfer */
result = events ? easy_events(multi) : easy_transfer(multi);
-
- /* ignoring the return code isn't nice, but atm we can't really handle
- a failure here, room for future improvement! */
- (void)curl_multi_remove_handle(multi, data);
-
- sigpipe_restore(&pipe_st);
-
- /* The multi handle is kept alive, owned by the easy handle */
+
+ /* ignoring the return code isn't nice, but atm we can't really handle
+ a failure here, room for future improvement! */
+ (void)curl_multi_remove_handle(multi, data);
+
+ sigpipe_restore(&pipe_st);
+
+ /* The multi handle is kept alive, owned by the easy handle */
return result;
-}
-
-
-/*
- * curl_easy_perform() is the external interface that performs a blocking
- * transfer as previously setup.
- */
+}
+
+
+/*
+ * curl_easy_perform() is the external interface that performs a blocking
+ * transfer as previously setup.
+ */
CURLcode curl_easy_perform(struct Curl_easy *data)
-{
+{
return easy_perform(data, FALSE);
-}
-
-#ifdef CURLDEBUG
-/*
- * curl_easy_perform_ev() is the external interface that performs a blocking
- * transfer using the event-based API internally.
- */
+}
+
+#ifdef CURLDEBUG
+/*
+ * curl_easy_perform_ev() is the external interface that performs a blocking
+ * transfer using the event-based API internally.
+ */
CURLcode curl_easy_perform_ev(struct Curl_easy *data)
-{
+{
return easy_perform(data, TRUE);
-}
-
-#endif
-
-/*
- * curl_easy_cleanup() is the external interface to cleaning/freeing the given
- * easy handle.
- */
+}
+
+#endif
+
+/*
+ * curl_easy_cleanup() is the external interface to cleaning/freeing the given
+ * easy handle.
+ */
void curl_easy_cleanup(struct Curl_easy *data)
-{
- SIGPIPE_VARIABLE(pipe_st);
-
- if(!data)
- return;
-
- sigpipe_ignore(data, &pipe_st);
+{
+ SIGPIPE_VARIABLE(pipe_st);
+
+ if(!data)
+ return;
+
+ sigpipe_ignore(data, &pipe_st);
Curl_close(&data);
- sigpipe_restore(&pipe_st);
-}
-
-/*
- * curl_easy_getinfo() is an external interface that allows an app to retrieve
- * information from a performed transfer and similar.
- */
-#undef curl_easy_getinfo
+ sigpipe_restore(&pipe_st);
+}
+
+/*
+ * curl_easy_getinfo() is an external interface that allows an app to retrieve
+ * information from a performed transfer and similar.
+ */
+#undef curl_easy_getinfo
CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...)
-{
- va_list arg;
- void *paramp;
+{
+ va_list arg;
+ void *paramp;
CURLcode result;
-
- va_start(arg, info);
- paramp = va_arg(arg, void *);
-
+
+ va_start(arg, info);
+ paramp = va_arg(arg, void *);
+
result = Curl_getinfo(data, info, paramp);
-
- va_end(arg);
+
+ va_end(arg);
return result;
-}
-
+}
+
static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src)
{
CURLcode result = CURLE_OK;
@@ -802,70 +802,70 @@ static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src)
return result;
}
-/*
- * curl_easy_duphandle() is an external interface to allow duplication of a
- * given input easy handle. The returned handle will be a new working handle
- * with all options set exactly as the input source handle.
- */
+/*
+ * curl_easy_duphandle() is an external interface to allow duplication of a
+ * given input easy handle. The returned handle will be a new working handle
+ * with all options set exactly as the input source handle.
+ */
struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data)
-{
+{
struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy));
- if(NULL == outcurl)
- goto fail;
-
- /*
- * We setup a few buffers we need. We should probably make them
- * get setup on-demand in the code, as that would probably decrease
- * the likeliness of us forgetting to init a buffer here in the future.
- */
+ if(NULL == outcurl)
+ goto fail;
+
+ /*
+ * We setup a few buffers we need. We should probably make them
+ * get setup on-demand in the code, as that would probably decrease
+ * the likeliness of us forgetting to init a buffer here in the future.
+ */
outcurl->set.buffer_size = data->set.buffer_size;
- /* copy all userdefined values */
+ /* copy all userdefined values */
if(dupset(outcurl, data))
- goto fail;
-
+ goto fail;
+
Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER);
- /* the connection cache is setup on demand */
- outcurl->state.conn_cache = NULL;
+ /* the connection cache is setup on demand */
+ outcurl->state.conn_cache = NULL;
outcurl->state.lastconnect_id = -1;
-
- outcurl->progress.flags = data->progress.flags;
- outcurl->progress.callback = data->progress.callback;
-
- if(data->cookies) {
- /* If cookies are enabled in the parent handle, we enable them
- in the clone as well! */
- outcurl->cookies = Curl_cookie_init(data,
- data->cookies->filename,
- outcurl->cookies,
- data->set.cookiesession);
- if(!outcurl->cookies)
- goto fail;
- }
-
- /* duplicate all values in 'change' */
- if(data->change.cookielist) {
- outcurl->change.cookielist =
- Curl_slist_duplicate(data->change.cookielist);
- if(!outcurl->change.cookielist)
- goto fail;
- }
-
- if(data->change.url) {
- outcurl->change.url = strdup(data->change.url);
- if(!outcurl->change.url)
- goto fail;
- outcurl->change.url_alloc = TRUE;
- }
-
- if(data->change.referer) {
- outcurl->change.referer = strdup(data->change.referer);
- if(!outcurl->change.referer)
- goto fail;
- outcurl->change.referer_alloc = TRUE;
- }
-
+
+ outcurl->progress.flags = data->progress.flags;
+ outcurl->progress.callback = data->progress.callback;
+
+ if(data->cookies) {
+ /* If cookies are enabled in the parent handle, we enable them
+ in the clone as well! */
+ outcurl->cookies = Curl_cookie_init(data,
+ data->cookies->filename,
+ outcurl->cookies,
+ data->set.cookiesession);
+ if(!outcurl->cookies)
+ goto fail;
+ }
+
+ /* duplicate all values in 'change' */
+ if(data->change.cookielist) {
+ outcurl->change.cookielist =
+ Curl_slist_duplicate(data->change.cookielist);
+ if(!outcurl->change.cookielist)
+ goto fail;
+ }
+
+ if(data->change.url) {
+ outcurl->change.url = strdup(data->change.url);
+ if(!outcurl->change.url)
+ goto fail;
+ outcurl->change.url_alloc = TRUE;
+ }
+
+ if(data->change.referer) {
+ outcurl->change.referer = strdup(data->change.referer);
+ if(!outcurl->change.referer)
+ goto fail;
+ outcurl->change.referer_alloc = TRUE;
+ }
+
/* Reinitialize an SSL engine for the new handle
* note: the engine name has already been copied by dupset */
if(outcurl->set.str[STRING_SSL_ENGINE]) {
@@ -893,12 +893,12 @@ struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data)
(void)Curl_hsts_loadcb(outcurl, outcurl->hsts);
}
#endif
- /* Clone the resolver handle, if present, for the new handle */
+ /* Clone the resolver handle, if present, for the new handle */
if(Curl_resolver_duphandle(outcurl,
&outcurl->state.resolver,
data->state.resolver))
- goto fail;
-
+ goto fail;
+
#ifdef USE_ARES
{
CURLcode rc;
@@ -921,55 +921,55 @@ struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data)
}
#endif /* USE_ARES */
- Curl_convert_setup(outcurl);
-
+ Curl_convert_setup(outcurl);
+
Curl_initinfo(outcurl);
- outcurl->magic = CURLEASY_MAGIC_NUMBER;
-
- /* we reach this point and thus we are OK */
-
- return outcurl;
-
- fail:
-
- if(outcurl) {
- curl_slist_free_all(outcurl->change.cookielist);
- outcurl->change.cookielist = NULL;
+ outcurl->magic = CURLEASY_MAGIC_NUMBER;
+
+ /* we reach this point and thus we are OK */
+
+ return outcurl;
+
+ fail:
+
+ if(outcurl) {
+ curl_slist_free_all(outcurl->change.cookielist);
+ outcurl->change.cookielist = NULL;
Curl_safefree(outcurl->state.buffer);
Curl_dyn_free(&outcurl->state.headerb);
- Curl_safefree(outcurl->change.url);
- Curl_safefree(outcurl->change.referer);
+ Curl_safefree(outcurl->change.url);
+ Curl_safefree(outcurl->change.referer);
Curl_altsvc_cleanup(&outcurl->asi);
Curl_hsts_cleanup(&outcurl->hsts);
- Curl_freeset(outcurl);
- free(outcurl);
- }
-
- return NULL;
-}
-
-/*
- * curl_easy_reset() is an external interface that allows an app to re-
- * initialize a session handle to the default values.
- */
+ Curl_freeset(outcurl);
+ free(outcurl);
+ }
+
+ return NULL;
+}
+
+/*
+ * curl_easy_reset() is an external interface that allows an app to re-
+ * initialize a session handle to the default values.
+ */
void curl_easy_reset(struct Curl_easy *data)
-{
- Curl_free_request_state(data);
-
- /* zero out UserDefined data: */
- Curl_freeset(data);
- memset(&data->set, 0, sizeof(struct UserDefined));
+{
+ Curl_free_request_state(data);
+
+ /* zero out UserDefined data: */
+ Curl_freeset(data);
+ memset(&data->set, 0, sizeof(struct UserDefined));
(void)Curl_init_userdefined(data);
-
- /* zero out Progress data: */
- memset(&data->progress, 0, sizeof(struct Progress));
-
+
+ /* zero out Progress data: */
+ memset(&data->progress, 0, sizeof(struct Progress));
+
/* zero out PureInfo data: */
Curl_initinfo(data);
- data->progress.flags |= PGRS_HIDE;
- data->state.current_speed = -1; /* init to negative == impossible */
+ data->progress.flags |= PGRS_HIDE;
+ data->state.current_speed = -1; /* init to negative == impossible */
data->state.retrycount = 0; /* reset the retry counter */
/* zero out authentication data: */
@@ -979,40 +979,40 @@ void curl_easy_reset(struct Curl_easy *data)
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
Curl_http_auth_cleanup_digest(data);
#endif
-}
-
-/*
- * curl_easy_pause() allows an application to pause or unpause a specific
- * transfer and direction. This function sets the full new state for the
- * current connection this easy handle operates on.
- *
- * NOTE: if you have the receiving paused and you call this function to remove
- * the pausing, you may get your write callback called at this point.
- *
- * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
+}
+
+/*
+ * curl_easy_pause() allows an application to pause or unpause a specific
+ * transfer and direction. This function sets the full new state for the
+ * current connection this easy handle operates on.
+ *
+ * NOTE: if you have the receiving paused and you call this function to remove
+ * the pausing, you may get your write callback called at this point.
+ *
+ * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
*
* NOTE: This is one of few API functions that are allowed to be called from
* within a callback.
- */
+ */
CURLcode curl_easy_pause(struct Curl_easy *data, int action)
-{
+{
struct SingleRequest *k;
- CURLcode result = CURLE_OK;
+ CURLcode result = CURLE_OK;
int oldstate;
int newstate;
-
+
if(!GOOD_EASY_HANDLE(data) || !data->conn)
/* crazy input, don't continue */
return CURLE_BAD_FUNCTION_ARGUMENT;
-
+
k = &data->req;
oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
/* first switch off both pause bits then set the new pause bits */
newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) |
((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
- ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
-
+ ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
+
if((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) == oldstate) {
/* Not changing any pause state, return */
DEBUGF(infof(data, "pause: no change, early return\n"));
@@ -1027,12 +1027,12 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
Curl_mime_unpause(data->state.in);
}
- /* put it back in the keepon */
- k->keepon = newstate;
-
+ /* put it back in the keepon */
+ k->keepon = newstate;
+
if(!(newstate & KEEP_RECV_PAUSE)) {
Curl_http2_stream_pause(data, FALSE);
-
+
if(data->state.tempcount) {
/* there are buffers for sending that can be delivered as the receive
pausing is lifted! */
@@ -1041,20 +1041,20 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
struct tempbuf writebuf[3]; /* there can only be three */
struct connectdata *conn = data->conn;
struct Curl_easy *saved_data = NULL;
-
+
/* copy the structs to allow for immediate re-pausing */
for(i = 0; i < data->state.tempcount; i++) {
writebuf[i] = data->state.tempwrite[i];
Curl_dyn_init(&data->state.tempwrite[i].b, DYN_PAUSE_BUFFER);
}
data->state.tempcount = 0;
-
+
/* set the connection's current owner */
if(conn->data != data) {
saved_data = conn->data;
conn->data = data;
}
-
+
for(i = 0; i < count; i++) {
/* even if one function returns error, this loops through and frees
all buffers */
@@ -1064,7 +1064,7 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
Curl_dyn_len(&writebuf[i].b));
Curl_dyn_free(&writebuf[i].b);
}
-
+
/* recover previous owner of the connection */
if(saved_data)
conn->data = saved_data;
@@ -1072,10 +1072,10 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
if(result)
return result;
}
- }
-
- /* if there's no error and we're not pausing both directions, we want
- to have this handle checked soon */
+ }
+
+ /* if there's no error and we're not pausing both directions, we want
+ to have this handle checked soon */
if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
(KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) {
Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */
@@ -1087,103 +1087,103 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
if(data->multi)
Curl_update_timer(data->multi);
}
-
+
if(!data->state.done)
/* This transfer may have been moved in or out of the bundle, update the
corresponding socket callback, if used */
Curl_updatesocket(data);
- return result;
-}
-
-
+ return result;
+}
+
+
static CURLcode easy_connection(struct Curl_easy *data,
- curl_socket_t *sfd,
- struct connectdata **connp)
-{
- if(data == NULL)
- return CURLE_BAD_FUNCTION_ARGUMENT;
-
- /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
- if(!data->set.connect_only) {
- failf(data, "CONNECT_ONLY is required!");
- return CURLE_UNSUPPORTED_PROTOCOL;
- }
-
- *sfd = Curl_getconnectinfo(data, connp);
-
- if(*sfd == CURL_SOCKET_BAD) {
- failf(data, "Failed to get recent socket");
- return CURLE_UNSUPPORTED_PROTOCOL;
- }
-
- return CURLE_OK;
-}
-
-/*
- * Receives data from the connected socket. Use after successful
- * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
- * Returns CURLE_OK on success, error code on error.
- */
+ curl_socket_t *sfd,
+ struct connectdata **connp)
+{
+ if(data == NULL)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
+ if(!data->set.connect_only) {
+ failf(data, "CONNECT_ONLY is required!");
+ return CURLE_UNSUPPORTED_PROTOCOL;
+ }
+
+ *sfd = Curl_getconnectinfo(data, connp);
+
+ if(*sfd == CURL_SOCKET_BAD) {
+ failf(data, "Failed to get recent socket");
+ return CURLE_UNSUPPORTED_PROTOCOL;
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Receives data from the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ * Returns CURLE_OK on success, error code on error.
+ */
CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen,
size_t *n)
-{
- curl_socket_t sfd;
+{
+ curl_socket_t sfd;
CURLcode result;
- ssize_t n1;
- struct connectdata *c;
-
+ ssize_t n1;
+ struct connectdata *c;
+
if(Curl_is_in_callback(data))
return CURLE_RECURSIVE_API_CALL;
-
+
result = easy_connection(data, &sfd, &c);
if(result)
return result;
- *n = 0;
+ *n = 0;
result = Curl_read(c, sfd, buffer, buflen, &n1);
-
+
if(result)
return result;
-
- *n = (size_t)n1;
-
- return CURLE_OK;
-}
-
-/*
- * Sends data over the connected socket. Use after successful
- * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
- */
+
+ *n = (size_t)n1;
+
+ return CURLE_OK;
+}
+
+/*
+ * Sends data over the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer,
size_t buflen, size_t *n)
-{
- curl_socket_t sfd;
+{
+ curl_socket_t sfd;
CURLcode result;
- ssize_t n1;
- struct connectdata *c = NULL;
-
+ ssize_t n1;
+ struct connectdata *c = NULL;
+
if(Curl_is_in_callback(data))
return CURLE_RECURSIVE_API_CALL;
-
+
result = easy_connection(data, &sfd, &c);
if(result)
return result;
- *n = 0;
+ *n = 0;
result = Curl_write(c, sfd, buffer, buflen, &n1);
-
- if(n1 == -1)
- return CURLE_SEND_ERROR;
-
- /* detect EAGAIN */
+
+ if(n1 == -1)
+ return CURLE_SEND_ERROR;
+
+ /* detect EAGAIN */
if(!result && !n1)
- return CURLE_AGAIN;
-
- *n = (size_t)n1;
-
+ return CURLE_AGAIN;
+
+ *n = (size_t)n1;
+
return result;
-}
+}
/*
* Wrapper to call functions in Curl_conncache_foreach()
diff --git a/contrib/libs/curl/lib/easyif.h b/contrib/libs/curl/lib/easyif.h
index 89a542e133..3364418285 100644
--- a/contrib/libs/curl/lib/easyif.h
+++ b/contrib/libs/curl/lib/easyif.h
@@ -1,32 +1,32 @@
-#ifndef HEADER_CURL_EASYIF_H
-#define HEADER_CURL_EASYIF_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_EASYIF_H
+#define HEADER_CURL_EASYIF_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * Prototypes for library-wide functions provided by easy.c
- */
-#ifdef CURLDEBUG
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * Prototypes for library-wide functions provided by easy.c
+ */
+#ifdef CURLDEBUG
CURL_EXTERN CURLcode curl_easy_perform_ev(struct Curl_easy *easy);
-#endif
-
-#endif /* HEADER_CURL_EASYIF_H */
+#endif
+
+#endif /* HEADER_CURL_EASYIF_H */
diff --git a/contrib/libs/curl/lib/escape.c b/contrib/libs/curl/lib/escape.c
index 340ff70ff4..683b6fc4a6 100644
--- a/contrib/libs/curl/lib/escape.c
+++ b/contrib/libs/curl/lib/escape.c
@@ -1,88 +1,88 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* Escape and unescape URL encoding in strings. The functions return a new
- * allocated string or NULL if an error occurred. */
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "warnless.h"
-#include "non-ascii.h"
-#include "escape.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* Escape and unescape URL encoding in strings. The functions return a new
+ * allocated string or NULL if an error occurred. */
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "warnless.h"
+#include "non-ascii.h"
+#include "escape.h"
#include "strdup.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-/* Portable character check (remember EBCDIC). Do not use isalnum() because
- its behavior is altered by the current locale.
+#include "memdebug.h"
+
+/* Portable character check (remember EBCDIC). Do not use isalnum() because
+ its behavior is altered by the current locale.
See https://tools.ietf.org/html/rfc3986#section-2.3
-*/
+*/
bool Curl_isunreserved(unsigned char in)
-{
+{
switch(in) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- case 'a': case 'b': case 'c': case 'd': case 'e':
- case 'f': case 'g': case 'h': case 'i': case 'j':
- case 'k': case 'l': case 'm': case 'n': case 'o':
- case 'p': case 'q': case 'r': case 's': case 't':
- case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
- case 'A': case 'B': case 'C': case 'D': case 'E':
- case 'F': case 'G': case 'H': case 'I': case 'J':
- case 'K': case 'L': case 'M': case 'N': case 'O':
- case 'P': case 'Q': case 'R': case 'S': case 'T':
- case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
- case '-': case '.': case '_': case '~':
- return TRUE;
- default:
- break;
- }
- return FALSE;
-}
-
-/* for ABI-compatibility with previous versions */
-char *curl_escape(const char *string, int inlength)
-{
- return curl_easy_escape(NULL, string, inlength);
-}
-
-/* for ABI-compatibility with previous versions */
-char *curl_unescape(const char *string, int length)
-{
- return curl_easy_unescape(NULL, string, length, NULL);
-}
-
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ case 'a': case 'b': case 'c': case 'd': case 'e':
+ case 'f': case 'g': case 'h': case 'i': case 'j':
+ case 'k': case 'l': case 'm': case 'n': case 'o':
+ case 'p': case 'q': case 'r': case 's': case 't':
+ case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
+ case 'A': case 'B': case 'C': case 'D': case 'E':
+ case 'F': case 'G': case 'H': case 'I': case 'J':
+ case 'K': case 'L': case 'M': case 'N': case 'O':
+ case 'P': case 'Q': case 'R': case 'S': case 'T':
+ case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
+ case '-': case '.': case '_': case '~':
+ return TRUE;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+/* for ABI-compatibility with previous versions */
+char *curl_escape(const char *string, int inlength)
+{
+ return curl_easy_escape(NULL, string, inlength);
+}
+
+/* for ABI-compatibility with previous versions */
+char *curl_unescape(const char *string, int length)
+{
+ return curl_easy_unescape(NULL, string, length, NULL);
+}
+
char *curl_easy_escape(struct Curl_easy *data, const char *string,
int inlength)
-{
- size_t length;
+{
+ size_t length;
CURLcode result;
struct dynbuf d;
-
+
if(inlength < 0)
return NULL;
@@ -91,41 +91,41 @@ char *curl_easy_escape(struct Curl_easy *data, const char *string,
length = (inlength?(size_t)inlength:strlen(string));
if(!length)
return strdup("");
-
- while(length--) {
+
+ while(length--) {
unsigned char in = *string; /* we need to treat the characters unsigned */
-
+
if(Curl_isunreserved(in)) {
/* append this */
if(Curl_dyn_addn(&d, &in, 1))
return NULL;
}
- else {
- /* encode it */
+ else {
+ /* encode it */
char encoded[4];
result = Curl_convert_to_network(data, (char *)&in, 1);
if(result) {
- /* Curl_convert_to_network calls failf if unsuccessful */
+ /* Curl_convert_to_network calls failf if unsuccessful */
Curl_dyn_free(&d);
- return NULL;
- }
-
+ return NULL;
+ }
+
msnprintf(encoded, sizeof(encoded), "%%%02X", in);
if(Curl_dyn_add(&d, encoded))
return NULL;
- }
- string++;
- }
+ }
+ string++;
+ }
return Curl_dyn_ptr(&d);
-}
-
-/*
- * Curl_urldecode() URL decodes the given string.
- *
- * Returns a pointer to a malloced string in *ostring with length given in
- * *olen. If length == 0, the length is assumed to be strlen(string).
- *
+}
+
+/*
+ * Curl_urldecode() URL decodes the given string.
+ *
+ * Returns a pointer to a malloced string in *ostring with length given in
+ * *olen. If length == 0, the length is assumed to be strlen(string).
+ *
* 'data' can be set to NULL but then this function can't convert network
* data to host for non-ascii.
*
@@ -137,43 +137,43 @@ char *curl_easy_escape(struct Curl_easy *data, const char *string,
*
* The values for the enum starts at 2, to make the assert detect legacy
* invokes that used TRUE/FALSE (0 and 1).
- */
+ */
CURLcode Curl_urldecode(struct Curl_easy *data,
- const char *string, size_t length,
- char **ostring, size_t *olen,
+ const char *string, size_t length,
+ char **ostring, size_t *olen,
enum urlreject ctrl)
-{
+{
size_t alloc;
char *ns;
size_t strindex = 0;
- unsigned long hex;
+ unsigned long hex;
CURLcode result = CURLE_OK;
-
+
DEBUGASSERT(string);
DEBUGASSERT(ctrl >= REJECT_NADA); /* crash on TRUE/FALSE */
alloc = (length?length:strlen(string)) + 1;
ns = malloc(alloc);
- if(!ns)
- return CURLE_OUT_OF_MEMORY;
-
- while(--alloc > 0) {
+ if(!ns)
+ return CURLE_OUT_OF_MEMORY;
+
+ while(--alloc > 0) {
unsigned char in = *string;
- if(('%' == in) && (alloc > 2) &&
- ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
- /* this is two hexadecimal digits following a '%' */
- char hexstr[3];
- char *ptr;
- hexstr[0] = string[1];
- hexstr[1] = string[2];
- hexstr[2] = 0;
-
- hex = strtoul(hexstr, &ptr, 16);
-
- in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
-
+ if(('%' == in) && (alloc > 2) &&
+ ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
+ /* this is two hexadecimal digits following a '%' */
+ char hexstr[3];
+ char *ptr;
+ hexstr[0] = string[1];
+ hexstr[1] = string[2];
+ hexstr[2] = 0;
+
+ hex = strtoul(hexstr, &ptr, 16);
+
+ in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
+
if(data) {
result = Curl_convert_from_network(data, (char *)&in, 1);
if(result) {
@@ -181,43 +181,43 @@ CURLcode Curl_urldecode(struct Curl_easy *data,
free(ns);
return result;
}
- }
-
+ }
+
string += 2;
alloc -= 2;
- }
+ }
if(((ctrl == REJECT_CTRL) && (in < 0x20)) ||
((ctrl == REJECT_ZERO) && (in == 0))) {
- free(ns);
- return CURLE_URL_MALFORMAT;
- }
-
- ns[strindex++] = in;
- string++;
- }
+ free(ns);
+ return CURLE_URL_MALFORMAT;
+ }
+
+ ns[strindex++] = in;
+ string++;
+ }
ns[strindex] = 0; /* terminate it */
-
- if(olen)
- /* store output size */
- *olen = strindex;
-
+
+ if(olen)
+ /* store output size */
+ *olen = strindex;
+
/* store output string */
*ostring = ns;
-
- return CURLE_OK;
-}
-
-/*
- * Unescapes the given URL escaped string of given length. Returns a
- * pointer to a malloced string with length given in *olen.
- * If length == 0, the length is assumed to be strlen(string).
- * If olen == NULL, no output length is stored.
- */
+
+ return CURLE_OK;
+}
+
+/*
+ * Unescapes the given URL escaped string of given length. Returns a
+ * pointer to a malloced string with length given in *olen.
+ * If length == 0, the length is assumed to be strlen(string).
+ * If olen == NULL, no output length is stored.
+ */
char *curl_easy_unescape(struct Curl_easy *data, const char *string,
int length, int *olen)
-{
- char *str = NULL;
+{
+ char *str = NULL;
if(length >= 0) {
size_t inputlen = length;
size_t outputlen;
@@ -234,13 +234,13 @@ char *curl_easy_unescape(struct Curl_easy *data, const char *string,
Curl_safefree(str);
}
}
- return str;
-}
-
-/* For operating systems/environments that use different malloc/free
- systems for the app and for this library, we provide a free that uses
- the library's memory system */
-void curl_free(void *p)
-{
+ return str;
+}
+
+/* For operating systems/environments that use different malloc/free
+ systems for the app and for this library, we provide a free that uses
+ the library's memory system */
+void curl_free(void *p)
+{
free(p);
-}
+}
diff --git a/contrib/libs/curl/lib/escape.h b/contrib/libs/curl/lib/escape.h
index f1d4a359f8..46cb59039a 100644
--- a/contrib/libs/curl/lib/escape.h
+++ b/contrib/libs/curl/lib/escape.h
@@ -1,29 +1,29 @@
-#ifndef HEADER_CURL_ESCAPE_H
-#define HEADER_CURL_ESCAPE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_ESCAPE_H
+#define HEADER_CURL_ESCAPE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-/* Escape and unescape URL encoding in strings. The functions return a new
- * allocated string or NULL if an error occurred. */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+/* Escape and unescape URL encoding in strings. The functions return a new
+ * allocated string or NULL if an error occurred. */
+
bool Curl_isunreserved(unsigned char in);
enum urlreject {
@@ -33,8 +33,8 @@ enum urlreject {
};
CURLcode Curl_urldecode(struct Curl_easy *data,
- const char *string, size_t length,
- char **ostring, size_t *olen,
+ const char *string, size_t length,
+ char **ostring, size_t *olen,
enum urlreject ctrl);
-
-#endif /* HEADER_CURL_ESCAPE_H */
+
+#endif /* HEADER_CURL_ESCAPE_H */
diff --git a/contrib/libs/curl/lib/file.c b/contrib/libs/curl/lib/file.c
index ad4340ca96..a65eb7798d 100644
--- a/contrib/libs/curl/lib/file.c
+++ b/contrib/libs/curl/lib/file.c
@@ -1,407 +1,407 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_FILE
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-
-#include "strtoofft.h"
-#include "urldata.h"
-#include <curl/curl.h>
-#include "progress.h"
-#include "sendf.h"
-#include "escape.h"
-#include "file.h"
-#include "speedcheck.h"
-#include "getinfo.h"
-#include "transfer.h"
-#include "url.h"
-#include "parsedate.h" /* for the week day and month names */
-#include "warnless.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_FILE
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#include "strtoofft.h"
+#include "urldata.h"
+#include <curl/curl.h>
+#include "progress.h"
+#include "sendf.h"
+#include "escape.h"
+#include "file.h"
+#include "speedcheck.h"
+#include "getinfo.h"
+#include "transfer.h"
+#include "url.h"
+#include "parsedate.h" /* for the week day and month names */
+#include "warnless.h"
#include "curl_range.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "memdebug.h"
+
#if defined(WIN32) || defined(MSDOS) || defined(__EMX__)
-#define DOS_FILESYSTEM 1
-#endif
-
-#ifdef OPEN_NEEDS_ARG3
-# define open_readonly(p,f) open((p),(f),(0))
-#else
-# define open_readonly(p,f) open((p),(f))
-#endif
-
-/*
- * Forward declarations.
- */
-
-static CURLcode file_do(struct connectdata *, bool *done);
-static CURLcode file_done(struct connectdata *conn,
- CURLcode status, bool premature);
-static CURLcode file_connect(struct connectdata *conn, bool *done);
-static CURLcode file_disconnect(struct connectdata *conn,
- bool dead_connection);
-static CURLcode file_setup_connection(struct connectdata *conn);
-
-/*
- * FILE scheme handler.
- */
-
-const struct Curl_handler Curl_handler_file = {
- "FILE", /* scheme */
- file_setup_connection, /* setup_connection */
- file_do, /* do_it */
- file_done, /* done */
- ZERO_NULL, /* do_more */
- file_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- file_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+#define DOS_FILESYSTEM 1
+#endif
+
+#ifdef OPEN_NEEDS_ARG3
+# define open_readonly(p,f) open((p),(f),(0))
+#else
+# define open_readonly(p,f) open((p),(f))
+#endif
+
+/*
+ * Forward declarations.
+ */
+
+static CURLcode file_do(struct connectdata *, bool *done);
+static CURLcode file_done(struct connectdata *conn,
+ CURLcode status, bool premature);
+static CURLcode file_connect(struct connectdata *conn, bool *done);
+static CURLcode file_disconnect(struct connectdata *conn,
+ bool dead_connection);
+static CURLcode file_setup_connection(struct connectdata *conn);
+
+/*
+ * FILE scheme handler.
+ */
+
+const struct Curl_handler Curl_handler_file = {
+ "FILE", /* scheme */
+ file_setup_connection, /* setup_connection */
+ file_do, /* do_it */
+ file_done, /* done */
+ ZERO_NULL, /* do_more */
+ file_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ file_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- 0, /* defport */
- CURLPROTO_FILE, /* protocol */
+ 0, /* defport */
+ CURLPROTO_FILE, /* protocol */
CURLPROTO_FILE, /* family */
- PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */
-};
-
-
-static CURLcode file_setup_connection(struct connectdata *conn)
-{
- /* allocate the FILE specific struct */
+ PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */
+};
+
+
+static CURLcode file_setup_connection(struct connectdata *conn)
+{
+ /* allocate the FILE specific struct */
conn->data->req.p.file = calloc(1, sizeof(struct FILEPROTO));
if(!conn->data->req.p.file)
- return CURLE_OUT_OF_MEMORY;
-
- return CURLE_OK;
-}
-
-/*
- * file_connect() gets called from Curl_protocol_connect() to allow us to
- * do protocol-specific actions at connect-time. We emulate a
- * connect-then-transfer protocol and "connect" to the file here
- */
-static CURLcode file_connect(struct connectdata *conn, bool *done)
-{
+ return CURLE_OUT_OF_MEMORY;
+
+ return CURLE_OK;
+}
+
+/*
+ * file_connect() gets called from Curl_protocol_connect() to allow us to
+ * do protocol-specific actions at connect-time. We emulate a
+ * connect-then-transfer protocol and "connect" to the file here
+ */
+static CURLcode file_connect(struct connectdata *conn, bool *done)
+{
struct Curl_easy *data = conn->data;
- char *real_path;
+ char *real_path;
struct FILEPROTO *file = data->req.p.file;
- int fd;
-#ifdef DOS_FILESYSTEM
+ int fd;
+#ifdef DOS_FILESYSTEM
size_t i;
- char *actual_path;
-#endif
+ char *actual_path;
+#endif
size_t real_path_len;
-
+
CURLcode result = Curl_urldecode(data, data->state.up.path, 0, &real_path,
&real_path_len, REJECT_ZERO);
if(result)
return result;
-
-#ifdef DOS_FILESYSTEM
- /* If the first character is a slash, and there's
- something that looks like a drive at the beginning of
- the path, skip the slash. If we remove the initial
- slash in all cases, paths without drive letters end up
- relative to the current directory which isn't how
- browsers work.
-
- Some browsers accept | instead of : as the drive letter
- separator, so we do too.
-
- On other platforms, we need the slash to indicate an
- absolute pathname. On Windows, absolute paths start
- with a drive letter.
- */
- actual_path = real_path;
- if((actual_path[0] == '/') &&
- actual_path[1] &&
- (actual_path[2] == ':' || actual_path[2] == '|')) {
- actual_path[2] = ':';
- actual_path++;
+
+#ifdef DOS_FILESYSTEM
+ /* If the first character is a slash, and there's
+ something that looks like a drive at the beginning of
+ the path, skip the slash. If we remove the initial
+ slash in all cases, paths without drive letters end up
+ relative to the current directory which isn't how
+ browsers work.
+
+ Some browsers accept | instead of : as the drive letter
+ separator, so we do too.
+
+ On other platforms, we need the slash to indicate an
+ absolute pathname. On Windows, absolute paths start
+ with a drive letter.
+ */
+ actual_path = real_path;
+ if((actual_path[0] == '/') &&
+ actual_path[1] &&
+ (actual_path[2] == ':' || actual_path[2] == '|')) {
+ actual_path[2] = ':';
+ actual_path++;
real_path_len--;
- }
-
- /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */
+ }
+
+ /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */
for(i = 0; i < real_path_len; ++i)
- if(actual_path[i] == '/')
- actual_path[i] = '\\';
+ if(actual_path[i] == '/')
+ actual_path[i] = '\\';
else if(!actual_path[i]) { /* binary zero */
Curl_safefree(real_path);
return CURLE_URL_MALFORMAT;
}
-
- fd = open_readonly(actual_path, O_RDONLY|O_BINARY);
- file->path = actual_path;
-#else
+
+ fd = open_readonly(actual_path, O_RDONLY|O_BINARY);
+ file->path = actual_path;
+#else
if(memchr(real_path, 0, real_path_len)) {
/* binary zeroes indicate foul play */
Curl_safefree(real_path);
return CURLE_URL_MALFORMAT;
}
- fd = open_readonly(real_path, O_RDONLY);
- file->path = real_path;
-#endif
- file->freepath = real_path; /* free this when done */
-
- file->fd = fd;
- if(!data->set.upload && (fd == -1)) {
+ fd = open_readonly(real_path, O_RDONLY);
+ file->path = real_path;
+#endif
+ file->freepath = real_path; /* free this when done */
+
+ file->fd = fd;
+ if(!data->set.upload && (fd == -1)) {
failf(data, "Couldn't open file %s", data->state.up.path);
- file_done(conn, CURLE_FILE_COULDNT_READ_FILE, FALSE);
- return CURLE_FILE_COULDNT_READ_FILE;
- }
- *done = TRUE;
-
- return CURLE_OK;
-}
-
-static CURLcode file_done(struct connectdata *conn,
- CURLcode status, bool premature)
-{
+ file_done(conn, CURLE_FILE_COULDNT_READ_FILE, FALSE);
+ return CURLE_FILE_COULDNT_READ_FILE;
+ }
+ *done = TRUE;
+
+ return CURLE_OK;
+}
+
+static CURLcode file_done(struct connectdata *conn,
+ CURLcode status, bool premature)
+{
struct FILEPROTO *file = conn->data->req.p.file;
- (void)status; /* not used */
- (void)premature; /* not used */
-
- if(file) {
- Curl_safefree(file->freepath);
- file->path = NULL;
- if(file->fd != -1)
- close(file->fd);
- file->fd = -1;
- }
-
- return CURLE_OK;
-}
-
-static CURLcode file_disconnect(struct connectdata *conn,
- bool dead_connection)
-{
- (void)dead_connection; /* not used */
+ (void)status; /* not used */
+ (void)premature; /* not used */
+
+ if(file) {
+ Curl_safefree(file->freepath);
+ file->path = NULL;
+ if(file->fd != -1)
+ close(file->fd);
+ file->fd = -1;
+ }
+
+ return CURLE_OK;
+}
+
+static CURLcode file_disconnect(struct connectdata *conn,
+ bool dead_connection)
+{
+ (void)dead_connection; /* not used */
return file_done(conn, 0, 0);
-}
-
-#ifdef DOS_FILESYSTEM
-#define DIRSEP '\\'
-#else
-#define DIRSEP '/'
-#endif
-
-static CURLcode file_upload(struct connectdata *conn)
-{
+}
+
+#ifdef DOS_FILESYSTEM
+#define DIRSEP '\\'
+#else
+#define DIRSEP '/'
+#endif
+
+static CURLcode file_upload(struct connectdata *conn)
+{
struct FILEPROTO *file = conn->data->req.p.file;
- const char *dir = strchr(file->path, DIRSEP);
- int fd;
- int mode;
+ const char *dir = strchr(file->path, DIRSEP);
+ int fd;
+ int mode;
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- char *buf = data->state.buffer;
- curl_off_t bytecount = 0;
- struct_stat file_stat;
+ char *buf = data->state.buffer;
+ curl_off_t bytecount = 0;
+ struct_stat file_stat;
const char *buf2;
-
- /*
- * Since FILE: doesn't do the full init, we need to provide some extra
- * assignments here.
- */
- conn->data->req.upload_fromhere = buf;
-
- if(!dir)
- return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
-
- if(!dir[1])
- return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
-
-#ifdef O_BINARY
-#define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY
-#else
-#define MODE_DEFAULT O_WRONLY|O_CREAT
-#endif
-
- if(data->state.resume_from)
- mode = MODE_DEFAULT|O_APPEND;
- else
- mode = MODE_DEFAULT|O_TRUNC;
-
- fd = open(file->path, mode, conn->data->set.new_file_perms);
- if(fd < 0) {
- failf(data, "Can't open %s for writing", file->path);
- return CURLE_WRITE_ERROR;
- }
-
+
+ /*
+ * Since FILE: doesn't do the full init, we need to provide some extra
+ * assignments here.
+ */
+ conn->data->req.upload_fromhere = buf;
+
+ if(!dir)
+ return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
+
+ if(!dir[1])
+ return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
+
+#ifdef O_BINARY
+#define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY
+#else
+#define MODE_DEFAULT O_WRONLY|O_CREAT
+#endif
+
+ if(data->state.resume_from)
+ mode = MODE_DEFAULT|O_APPEND;
+ else
+ mode = MODE_DEFAULT|O_TRUNC;
+
+ fd = open(file->path, mode, conn->data->set.new_file_perms);
+ if(fd < 0) {
+ failf(data, "Can't open %s for writing", file->path);
+ return CURLE_WRITE_ERROR;
+ }
+
if(-1 != data->state.infilesize)
- /* known size of data to "upload" */
+ /* known size of data to "upload" */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
-
- /* treat the negative resume offset value as the case of "-" */
- if(data->state.resume_from < 0) {
- if(fstat(fd, &file_stat)) {
- close(fd);
- failf(data, "Can't get the size of %s", file->path);
- return CURLE_WRITE_ERROR;
- }
+
+ /* treat the negative resume offset value as the case of "-" */
+ if(data->state.resume_from < 0) {
+ if(fstat(fd, &file_stat)) {
+ close(fd);
+ failf(data, "Can't get the size of %s", file->path);
+ return CURLE_WRITE_ERROR;
+ }
data->state.resume_from = (curl_off_t)file_stat.st_size;
- }
-
+ }
+
while(!result) {
size_t nread;
size_t nwrite;
size_t readcount;
result = Curl_fillreadbuffer(conn, data->set.buffer_size, &readcount);
if(result)
- break;
-
+ break;
+
if(!readcount)
- break;
-
+ break;
+
nread = readcount;
-
- /*skip bytes before resume point*/
- if(data->state.resume_from) {
+
+ /*skip bytes before resume point*/
+ if(data->state.resume_from) {
if((curl_off_t)nread <= data->state.resume_from) {
- data->state.resume_from -= nread;
- nread = 0;
- buf2 = buf;
- }
- else {
- buf2 = buf + data->state.resume_from;
- nread -= (size_t)data->state.resume_from;
- data->state.resume_from = 0;
- }
- }
- else
- buf2 = buf;
-
- /* write the data to the target */
- nwrite = write(fd, buf2, nread);
- if(nwrite != nread) {
+ data->state.resume_from -= nread;
+ nread = 0;
+ buf2 = buf;
+ }
+ else {
+ buf2 = buf + data->state.resume_from;
+ nread -= (size_t)data->state.resume_from;
+ data->state.resume_from = 0;
+ }
+ }
+ else
+ buf2 = buf;
+
+ /* write the data to the target */
+ nwrite = write(fd, buf2, nread);
+ if(nwrite != nread) {
result = CURLE_SEND_ERROR;
- break;
- }
-
- bytecount += nread;
-
- Curl_pgrsSetUploadCounter(data, bytecount);
-
- if(Curl_pgrsUpdate(conn))
+ break;
+ }
+
+ bytecount += nread;
+
+ Curl_pgrsSetUploadCounter(data, bytecount);
+
+ if(Curl_pgrsUpdate(conn))
result = CURLE_ABORTED_BY_CALLBACK;
- else
+ else
result = Curl_speedcheck(data, Curl_now());
- }
+ }
if(!result && Curl_pgrsUpdate(conn))
result = CURLE_ABORTED_BY_CALLBACK;
-
- close(fd);
-
+
+ close(fd);
+
return result;
-}
-
-/*
- * file_do() is the protocol-specific function for the do-phase, separated
- * from the connect-phase above. Other protocols merely setup the transfer in
- * the do-phase, to have it done in the main transfer loop but since some
- * platforms we support don't allow select()ing etc on file handles (as
- * opposed to sockets) we instead perform the whole do-operation in this
- * function.
- */
-static CURLcode file_do(struct connectdata *conn, bool *done)
-{
- /* This implementation ignores the host name in conformance with
- RFC 1738. Only local files (reachable via the standard file system)
- are supported. This means that files on remotely mounted directories
- (via NFS, Samba, NT sharing) can be accessed through a file:// URL
- */
+}
+
+/*
+ * file_do() is the protocol-specific function for the do-phase, separated
+ * from the connect-phase above. Other protocols merely setup the transfer in
+ * the do-phase, to have it done in the main transfer loop but since some
+ * platforms we support don't allow select()ing etc on file handles (as
+ * opposed to sockets) we instead perform the whole do-operation in this
+ * function.
+ */
+static CURLcode file_do(struct connectdata *conn, bool *done)
+{
+ /* This implementation ignores the host name in conformance with
+ RFC 1738. Only local files (reachable via the standard file system)
+ are supported. This means that files on remotely mounted directories
+ (via NFS, Samba, NT sharing) can be accessed through a file:// URL
+ */
CURLcode result = CURLE_OK;
- struct_stat statbuf; /* struct_stat instead of struct stat just to allow the
- Windows version to have a different struct without
- having to redefine the simple word 'stat' */
+ struct_stat statbuf; /* struct_stat instead of struct stat just to allow the
+ Windows version to have a different struct without
+ having to redefine the simple word 'stat' */
curl_off_t expected_size = 0;
bool size_known;
bool fstated = FALSE;
struct Curl_easy *data = conn->data;
- char *buf = data->state.buffer;
- curl_off_t bytecount = 0;
- int fd;
- struct FILEPROTO *file;
-
- *done = TRUE; /* unconditionally */
-
- Curl_pgrsStartNow(data);
-
- if(data->set.upload)
- return file_upload(conn);
-
+ char *buf = data->state.buffer;
+ curl_off_t bytecount = 0;
+ int fd;
+ struct FILEPROTO *file;
+
+ *done = TRUE; /* unconditionally */
+
+ Curl_pgrsStartNow(data);
+
+ if(data->set.upload)
+ return file_upload(conn);
+
file = conn->data->req.p.file;
-
- /* get the fd from the connection phase */
- fd = file->fd;
-
- /* VMS: This only works reliable for STREAMLF files */
- if(-1 != fstat(fd, &statbuf)) {
- /* we could stat it, then read out the size */
- expected_size = statbuf.st_size;
- /* and store the modification time */
+
+ /* get the fd from the connection phase */
+ fd = file->fd;
+
+ /* VMS: This only works reliable for STREAMLF files */
+ if(-1 != fstat(fd, &statbuf)) {
+ /* we could stat it, then read out the size */
+ expected_size = statbuf.st_size;
+ /* and store the modification time */
data->info.filetime = statbuf.st_mtime;
- fstated = TRUE;
- }
-
- if(fstated && !data->state.range && data->set.timecondition) {
+ fstated = TRUE;
+ }
+
+ if(fstated && !data->state.range && data->set.timecondition) {
if(!Curl_meets_timecondition(data, data->info.filetime)) {
- *done = TRUE;
- return CURLE_OK;
- }
- }
-
+ *done = TRUE;
+ return CURLE_OK;
+ }
+ }
+
if(fstated) {
time_t filetime;
struct tm buffer;
@@ -411,19 +411,19 @@ static CURLcode file_do(struct connectdata *conn, bool *done)
"Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n",
expected_size);
result = Curl_client_write(conn, CLIENTWRITE_HEADER, header, 0);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
result = Curl_client_write(conn, CLIENTWRITE_HEADER,
- (char *)"Accept-ranges: bytes\r\n", 0);
- if(result)
- return result;
-
+ (char *)"Accept-ranges: bytes\r\n", 0);
+ if(result)
+ return result;
+
filetime = (time_t)statbuf.st_mtime;
result = Curl_gmtime(filetime, &buffer);
if(result)
return result;
-
+
/* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
msnprintf(header, sizeof(header),
"Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n%s",
@@ -442,59 +442,59 @@ static CURLcode file_do(struct connectdata *conn, bool *done)
Curl_pgrsSetDownloadSize(data, expected_size);
if(data->set.opt_no_body)
return result;
- }
-
- /* Check whether file range has been specified */
+ }
+
+ /* Check whether file range has been specified */
result = Curl_range(conn);
if(result)
return result;
-
- /* Adjust the start offset in case we want to get the N last bytes
+
+ /* Adjust the start offset in case we want to get the N last bytes
* of the stream if the filesize could be determined */
- if(data->state.resume_from < 0) {
- if(!fstated) {
- failf(data, "Can't get the size of file.");
- return CURLE_READ_ERROR;
- }
+ if(data->state.resume_from < 0) {
+ if(!fstated) {
+ failf(data, "Can't get the size of file.");
+ return CURLE_READ_ERROR;
+ }
data->state.resume_from += (curl_off_t)statbuf.st_size;
- }
-
- if(data->state.resume_from <= expected_size)
- expected_size -= data->state.resume_from;
- else {
- failf(data, "failed to resume file:// transfer");
- return CURLE_BAD_DOWNLOAD_RESUME;
- }
-
- /* A high water mark has been specified so we obey... */
- if(data->req.maxdownload > 0)
- expected_size = data->req.maxdownload;
-
+ }
+
+ if(data->state.resume_from <= expected_size)
+ expected_size -= data->state.resume_from;
+ else {
+ failf(data, "failed to resume file:// transfer");
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+
+ /* A high water mark has been specified so we obey... */
+ if(data->req.maxdownload > 0)
+ expected_size = data->req.maxdownload;
+
if(!fstated || (expected_size == 0))
size_known = FALSE;
else
size_known = TRUE;
-
- /* The following is a shortcut implementation of file reading
- this is both more efficient than the former call to download() and
- it avoids problems with select() and recv() on file descriptors
- in Winsock */
- if(fstated)
- Curl_pgrsSetDownloadSize(data, expected_size);
-
- if(data->state.resume_from) {
- if(data->state.resume_from !=
- lseek(fd, data->state.resume_from, SEEK_SET))
- return CURLE_BAD_DOWNLOAD_RESUME;
- }
-
- Curl_pgrsTime(data, TIMER_STARTTRANSFER);
-
+
+ /* The following is a shortcut implementation of file reading
+ this is both more efficient than the former call to download() and
+ it avoids problems with select() and recv() on file descriptors
+ in Winsock */
+ if(fstated)
+ Curl_pgrsSetDownloadSize(data, expected_size);
+
+ if(data->state.resume_from) {
+ if(data->state.resume_from !=
+ lseek(fd, data->state.resume_from, SEEK_SET))
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+
+ Curl_pgrsTime(data, TIMER_STARTTRANSFER);
+
while(!result) {
ssize_t nread;
- /* Don't fill a whole buffer if we want less than all data */
+ /* Don't fill a whole buffer if we want less than all data */
size_t bytestoread;
-
+
if(size_known) {
bytestoread = (expected_size < data->set.buffer_size) ?
curlx_sotouz(expected_size) : (size_t)data->set.buffer_size;
@@ -502,33 +502,33 @@ static CURLcode file_do(struct connectdata *conn, bool *done)
else
bytestoread = data->set.buffer_size-1;
- nread = read(fd, buf, bytestoread);
-
- if(nread > 0)
- buf[nread] = 0;
-
+ nread = read(fd, buf, bytestoread);
+
+ if(nread > 0)
+ buf[nread] = 0;
+
if(nread <= 0 || (size_known && (expected_size == 0)))
- break;
-
- bytecount += nread;
+ break;
+
+ bytecount += nread;
if(size_known)
expected_size -= nread;
-
+
result = Curl_client_write(conn, CLIENTWRITE_BODY, buf, nread);
if(result)
return result;
-
- Curl_pgrsSetDownloadCounter(data, bytecount);
-
- if(Curl_pgrsUpdate(conn))
+
+ Curl_pgrsSetDownloadCounter(data, bytecount);
+
+ if(Curl_pgrsUpdate(conn))
result = CURLE_ABORTED_BY_CALLBACK;
- else
+ else
result = Curl_speedcheck(data, Curl_now());
- }
- if(Curl_pgrsUpdate(conn))
+ }
+ if(Curl_pgrsUpdate(conn))
result = CURLE_ABORTED_BY_CALLBACK;
-
+
return result;
-}
-
-#endif
+}
+
+#endif
diff --git a/contrib/libs/curl/lib/file.h b/contrib/libs/curl/lib/file.h
index 9770d37a42..338f92e46a 100644
--- a/contrib/libs/curl/lib/file.h
+++ b/contrib/libs/curl/lib/file.h
@@ -1,40 +1,40 @@
-#ifndef HEADER_CURL_FILE_H
-#define HEADER_CURL_FILE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_FILE_H
+#define HEADER_CURL_FILE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-
-/****************************************************************************
- * FILE unique setup
- ***************************************************************************/
-struct FILEPROTO {
- char *path; /* the path we operate on */
- char *freepath; /* pointer to the allocated block we must free, this might
- differ from the 'path' pointer */
- int fd; /* open file descriptor to read from! */
-};
-
-#ifndef CURL_DISABLE_FILE
-extern const struct Curl_handler Curl_handler_file;
-#endif
-
-#endif /* HEADER_CURL_FILE_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+
+/****************************************************************************
+ * FILE unique setup
+ ***************************************************************************/
+struct FILEPROTO {
+ char *path; /* the path we operate on */
+ char *freepath; /* pointer to the allocated block we must free, this might
+ differ from the 'path' pointer */
+ int fd; /* open file descriptor to read from! */
+};
+
+#ifndef CURL_DISABLE_FILE
+extern const struct Curl_handler Curl_handler_file;
+#endif
+
+#endif /* HEADER_CURL_FILE_H */
diff --git a/contrib/libs/curl/lib/fileinfo.c b/contrib/libs/curl/lib/fileinfo.c
index a156dbfd49..b7e9f0f5e8 100644
--- a/contrib/libs/curl/lib/fileinfo.c
+++ b/contrib/libs/curl/lib/fileinfo.c
@@ -1,44 +1,44 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2010 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
#ifndef CURL_DISABLE_FTP
-#include "strdup.h"
-#include "fileinfo.h"
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
+#include "strdup.h"
+#include "fileinfo.h"
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
struct fileinfo *Curl_fileinfo_alloc(void)
-{
+{
return calloc(1, sizeof(struct fileinfo));
-}
-
+}
+
void Curl_fileinfo_cleanup(struct fileinfo *finfo)
-{
- if(!finfo)
- return;
-
+{
+ if(!finfo)
+ return;
+
Curl_safefree(finfo->info.b_data);
- free(finfo);
-}
+ free(finfo);
+}
#endif
diff --git a/contrib/libs/curl/lib/fileinfo.h b/contrib/libs/curl/lib/fileinfo.h
index 8980eda712..5ae23ad4a3 100644
--- a/contrib/libs/curl/lib/fileinfo.h
+++ b/contrib/libs/curl/lib/fileinfo.h
@@ -1,36 +1,36 @@
-#ifndef HEADER_CURL_FILEINFO_H
-#define HEADER_CURL_FILEINFO_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_FILEINFO_H
+#define HEADER_CURL_FILEINFO_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2010 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <curl/curl.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <curl/curl.h>
#include "llist.h"
-
+
struct fileinfo {
struct curl_fileinfo info;
struct Curl_llist_element list;
};
-
+
struct fileinfo *Curl_fileinfo_alloc(void);
void Curl_fileinfo_cleanup(struct fileinfo *finfo);
-
-#endif /* HEADER_CURL_FILEINFO_H */
+
+#endif /* HEADER_CURL_FILEINFO_H */
diff --git a/contrib/libs/curl/lib/formdata.c b/contrib/libs/curl/lib/formdata.c
index c59984fd71..769f06a705 100644
--- a/contrib/libs/curl/lib/formdata.c
+++ b/contrib/libs/curl/lib/formdata.c
@@ -1,36 +1,36 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
#include "formdata.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME)
-
-#if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
-#include <libgen.h>
-#endif
-
+
+#if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
+#include <libgen.h>
+#endif
+
#include "urldata.h" /* for struct Curl_easy */
#include "mime.h"
#include "non-ascii.h"
@@ -42,10 +42,10 @@
#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+
#define HTTPPOST_PTRNAME CURL_HTTPPOST_PTRNAME
#define HTTPPOST_FILENAME CURL_HTTPPOST_FILENAME
#define HTTPPOST_PTRCONTENTS CURL_HTTPPOST_PTRCONTENTS
@@ -53,519 +53,519 @@
#define HTTPPOST_PTRBUFFER CURL_HTTPPOST_PTRBUFFER
#define HTTPPOST_CALLBACK CURL_HTTPPOST_CALLBACK
#define HTTPPOST_BUFFER CURL_HTTPPOST_BUFFER
-
-/***************************************************************************
- *
- * AddHttpPost()
- *
- * Adds a HttpPost structure to the list, if parent_post is given becomes
- * a subpost of parent_post instead of a direct list element.
- *
- * Returns newly allocated HttpPost on success and NULL if malloc failed.
- *
- ***************************************************************************/
-static struct curl_httppost *
-AddHttpPost(char *name, size_t namelength,
+
+/***************************************************************************
+ *
+ * AddHttpPost()
+ *
+ * Adds a HttpPost structure to the list, if parent_post is given becomes
+ * a subpost of parent_post instead of a direct list element.
+ *
+ * Returns newly allocated HttpPost on success and NULL if malloc failed.
+ *
+ ***************************************************************************/
+static struct curl_httppost *
+AddHttpPost(char *name, size_t namelength,
char *value, curl_off_t contentslength,
- char *buffer, size_t bufferlength,
- char *contenttype,
- long flags,
+ char *buffer, size_t bufferlength,
+ char *contenttype,
+ long flags,
struct curl_slist *contentHeader,
- char *showfilename, char *userp,
- struct curl_httppost *parent_post,
- struct curl_httppost **httppost,
- struct curl_httppost **last_post)
-{
- struct curl_httppost *post;
- post = calloc(1, sizeof(struct curl_httppost));
- if(post) {
- post->name = name;
- post->namelength = (long)(name?(namelength?namelength:strlen(name)):0);
- post->contents = value;
+ char *showfilename, char *userp,
+ struct curl_httppost *parent_post,
+ struct curl_httppost **httppost,
+ struct curl_httppost **last_post)
+{
+ struct curl_httppost *post;
+ post = calloc(1, sizeof(struct curl_httppost));
+ if(post) {
+ post->name = name;
+ post->namelength = (long)(name?(namelength?namelength:strlen(name)):0);
+ post->contents = value;
post->contentlen = contentslength;
- post->buffer = buffer;
- post->bufferlength = (long)bufferlength;
- post->contenttype = contenttype;
- post->contentheader = contentHeader;
- post->showfilename = showfilename;
+ post->buffer = buffer;
+ post->bufferlength = (long)bufferlength;
+ post->contenttype = contenttype;
+ post->contentheader = contentHeader;
+ post->showfilename = showfilename;
post->userp = userp;
post->flags = flags | CURL_HTTPPOST_LARGE;
- }
- else
- return NULL;
-
- if(parent_post) {
- /* now, point our 'more' to the original 'more' */
- post->more = parent_post->more;
-
- /* then move the original 'more' to point to ourselves */
- parent_post->more = post;
- }
- else {
- /* make the previous point to this */
- if(*last_post)
- (*last_post)->next = post;
- else
- (*httppost) = post;
-
- (*last_post) = post;
- }
- return post;
-}
-
-/***************************************************************************
- *
- * AddFormInfo()
- *
- * Adds a FormInfo structure to the list presented by parent_form_info.
- *
- * Returns newly allocated FormInfo on success and NULL if malloc failed/
- * parent_form_info is NULL.
- *
- ***************************************************************************/
+ }
+ else
+ return NULL;
+
+ if(parent_post) {
+ /* now, point our 'more' to the original 'more' */
+ post->more = parent_post->more;
+
+ /* then move the original 'more' to point to ourselves */
+ parent_post->more = post;
+ }
+ else {
+ /* make the previous point to this */
+ if(*last_post)
+ (*last_post)->next = post;
+ else
+ (*httppost) = post;
+
+ (*last_post) = post;
+ }
+ return post;
+}
+
+/***************************************************************************
+ *
+ * AddFormInfo()
+ *
+ * Adds a FormInfo structure to the list presented by parent_form_info.
+ *
+ * Returns newly allocated FormInfo on success and NULL if malloc failed/
+ * parent_form_info is NULL.
+ *
+ ***************************************************************************/
static struct FormInfo *AddFormInfo(char *value,
char *contenttype,
struct FormInfo *parent_form_info)
-{
+{
struct FormInfo *form_info;
- form_info = calloc(1, sizeof(struct FormInfo));
- if(form_info) {
- if(value)
- form_info->value = value;
- if(contenttype)
- form_info->contenttype = contenttype;
- form_info->flags = HTTPPOST_FILENAME;
- }
- else
- return NULL;
-
- if(parent_form_info) {
- /* now, point our 'more' to the original 'more' */
- form_info->more = parent_form_info->more;
-
- /* then move the original 'more' to point to ourselves */
- parent_form_info->more = form_info;
- }
-
- return form_info;
-}
-
-/***************************************************************************
- *
- * FormAdd()
- *
- * Stores a formpost parameter and builds the appropriate linked list.
- *
- * Has two principal functionalities: using files and byte arrays as
- * post parts. Byte arrays are either copied or just the pointer is stored
- * (as the user requests) while for files only the filename and not the
- * content is stored.
- *
- * While you may have only one byte array for each name, multiple filenames
- * are allowed (and because of this feature CURLFORM_END is needed after
- * using CURLFORM_FILE).
- *
- * Examples:
- *
- * Simple name/value pair with copied contents:
- * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
- * CURLFORM_COPYCONTENTS, "value", CURLFORM_END);
- *
- * name/value pair where only the content pointer is remembered:
- * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
- * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END);
- * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used)
- *
- * storing a filename (CONTENTTYPE is optional!):
- * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
- * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text",
- * CURLFORM_END);
- *
- * storing multiple filenames:
- * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
- * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END);
- *
- * Returns:
- * CURL_FORMADD_OK on success
- * CURL_FORMADD_MEMORY if the FormInfo allocation fails
- * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
- * CURL_FORMADD_NULL if a null pointer was given for a char
- * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
- * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
- * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
- * CURL_FORMADD_MEMORY if a HttpPost struct cannot be allocated
- * CURL_FORMADD_MEMORY if some allocation for string copying failed.
- * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
- *
- ***************************************************************************/
-
-static
-CURLFORMcode FormAdd(struct curl_httppost **httppost,
- struct curl_httppost **last_post,
- va_list params)
-{
+ form_info = calloc(1, sizeof(struct FormInfo));
+ if(form_info) {
+ if(value)
+ form_info->value = value;
+ if(contenttype)
+ form_info->contenttype = contenttype;
+ form_info->flags = HTTPPOST_FILENAME;
+ }
+ else
+ return NULL;
+
+ if(parent_form_info) {
+ /* now, point our 'more' to the original 'more' */
+ form_info->more = parent_form_info->more;
+
+ /* then move the original 'more' to point to ourselves */
+ parent_form_info->more = form_info;
+ }
+
+ return form_info;
+}
+
+/***************************************************************************
+ *
+ * FormAdd()
+ *
+ * Stores a formpost parameter and builds the appropriate linked list.
+ *
+ * Has two principal functionalities: using files and byte arrays as
+ * post parts. Byte arrays are either copied or just the pointer is stored
+ * (as the user requests) while for files only the filename and not the
+ * content is stored.
+ *
+ * While you may have only one byte array for each name, multiple filenames
+ * are allowed (and because of this feature CURLFORM_END is needed after
+ * using CURLFORM_FILE).
+ *
+ * Examples:
+ *
+ * Simple name/value pair with copied contents:
+ * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
+ * CURLFORM_COPYCONTENTS, "value", CURLFORM_END);
+ *
+ * name/value pair where only the content pointer is remembered:
+ * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
+ * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END);
+ * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used)
+ *
+ * storing a filename (CONTENTTYPE is optional!):
+ * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
+ * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text",
+ * CURLFORM_END);
+ *
+ * storing multiple filenames:
+ * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
+ * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END);
+ *
+ * Returns:
+ * CURL_FORMADD_OK on success
+ * CURL_FORMADD_MEMORY if the FormInfo allocation fails
+ * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
+ * CURL_FORMADD_NULL if a null pointer was given for a char
+ * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
+ * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
+ * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
+ * CURL_FORMADD_MEMORY if a HttpPost struct cannot be allocated
+ * CURL_FORMADD_MEMORY if some allocation for string copying failed.
+ * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
+ *
+ ***************************************************************************/
+
+static
+CURLFORMcode FormAdd(struct curl_httppost **httppost,
+ struct curl_httppost **last_post,
+ va_list params)
+{
struct FormInfo *first_form, *current_form, *form = NULL;
- CURLFORMcode return_value = CURL_FORMADD_OK;
- const char *prevtype = NULL;
- struct curl_httppost *post = NULL;
- CURLformoption option;
- struct curl_forms *forms = NULL;
+ CURLFORMcode return_value = CURL_FORMADD_OK;
+ const char *prevtype = NULL;
+ struct curl_httppost *post = NULL;
+ CURLformoption option;
+ struct curl_forms *forms = NULL;
char *array_value = NULL; /* value read from an array */
-
- /* This is a state variable, that if TRUE means that we're parsing an
- array that we got passed to us. If FALSE we're parsing the input
- va_list arguments. */
- bool array_state = FALSE;
-
- /*
- * We need to allocate the first struct to fill in.
- */
- first_form = calloc(1, sizeof(struct FormInfo));
- if(!first_form)
- return CURL_FORMADD_MEMORY;
-
- current_form = first_form;
-
- /*
- * Loop through all the options set. Break if we have an error to report.
- */
- while(return_value == CURL_FORMADD_OK) {
-
- /* first see if we have more parts of the array param */
- if(array_state && forms) {
- /* get the upcoming option from the given array */
- option = forms->option;
- array_value = (char *)forms->value;
-
- forms++; /* advance this to next entry */
- if(CURLFORM_END == option) {
- /* end of array state */
- array_state = FALSE;
- continue;
- }
- }
- else {
- /* This is not array-state, get next option */
- option = va_arg(params, CURLformoption);
- if(CURLFORM_END == option)
- break;
- }
-
+
+ /* This is a state variable, that if TRUE means that we're parsing an
+ array that we got passed to us. If FALSE we're parsing the input
+ va_list arguments. */
+ bool array_state = FALSE;
+
+ /*
+ * We need to allocate the first struct to fill in.
+ */
+ first_form = calloc(1, sizeof(struct FormInfo));
+ if(!first_form)
+ return CURL_FORMADD_MEMORY;
+
+ current_form = first_form;
+
+ /*
+ * Loop through all the options set. Break if we have an error to report.
+ */
+ while(return_value == CURL_FORMADD_OK) {
+
+ /* first see if we have more parts of the array param */
+ if(array_state && forms) {
+ /* get the upcoming option from the given array */
+ option = forms->option;
+ array_value = (char *)forms->value;
+
+ forms++; /* advance this to next entry */
+ if(CURLFORM_END == option) {
+ /* end of array state */
+ array_state = FALSE;
+ continue;
+ }
+ }
+ else {
+ /* This is not array-state, get next option */
+ option = va_arg(params, CURLformoption);
+ if(CURLFORM_END == option)
+ break;
+ }
+
switch(option) {
- case CURLFORM_ARRAY:
- if(array_state)
- /* we don't support an array from within an array */
- return_value = CURL_FORMADD_ILLEGAL_ARRAY;
- else {
- forms = va_arg(params, struct curl_forms *);
- if(forms)
- array_state = TRUE;
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
-
- /*
- * Set the Name property.
- */
- case CURLFORM_PTRNAME:
-#ifdef CURL_DOES_CONVERSIONS
- /* Treat CURLFORM_PTR like CURLFORM_COPYNAME so that libcurl will copy
- * the data in all cases so that we'll have safe memory for the eventual
- * conversion.
- */
-#else
- current_form->flags |= HTTPPOST_PTRNAME; /* fall through */
-#endif
+ case CURLFORM_ARRAY:
+ if(array_state)
+ /* we don't support an array from within an array */
+ return_value = CURL_FORMADD_ILLEGAL_ARRAY;
+ else {
+ forms = va_arg(params, struct curl_forms *);
+ if(forms)
+ array_state = TRUE;
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+
+ /*
+ * Set the Name property.
+ */
+ case CURLFORM_PTRNAME:
+#ifdef CURL_DOES_CONVERSIONS
+ /* Treat CURLFORM_PTR like CURLFORM_COPYNAME so that libcurl will copy
+ * the data in all cases so that we'll have safe memory for the eventual
+ * conversion.
+ */
+#else
+ current_form->flags |= HTTPPOST_PTRNAME; /* fall through */
+#endif
/* FALLTHROUGH */
- case CURLFORM_COPYNAME:
- if(current_form->name)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else {
- char *name = array_state?
- array_value:va_arg(params, char *);
- if(name)
- current_form->name = name; /* store for the moment */
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
- case CURLFORM_NAMELENGTH:
- if(current_form->namelength)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else
- current_form->namelength =
- array_state?(size_t)array_value:(size_t)va_arg(params, long);
- break;
-
- /*
- * Set the contents property.
- */
- case CURLFORM_PTRCONTENTS:
+ case CURLFORM_COPYNAME:
+ if(current_form->name)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else {
+ char *name = array_state?
+ array_value:va_arg(params, char *);
+ if(name)
+ current_form->name = name; /* store for the moment */
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+ case CURLFORM_NAMELENGTH:
+ if(current_form->namelength)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else
+ current_form->namelength =
+ array_state?(size_t)array_value:(size_t)va_arg(params, long);
+ break;
+
+ /*
+ * Set the contents property.
+ */
+ case CURLFORM_PTRCONTENTS:
current_form->flags |= HTTPPOST_PTRCONTENTS;
/* FALLTHROUGH */
- case CURLFORM_COPYCONTENTS:
- if(current_form->value)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else {
- char *value =
- array_state?array_value:va_arg(params, char *);
- if(value)
- current_form->value = value; /* store for the moment */
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
- case CURLFORM_CONTENTSLENGTH:
+ case CURLFORM_COPYCONTENTS:
+ if(current_form->value)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else {
+ char *value =
+ array_state?array_value:va_arg(params, char *);
+ if(value)
+ current_form->value = value; /* store for the moment */
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+ case CURLFORM_CONTENTSLENGTH:
current_form->contentslength =
array_state?(size_t)array_value:(size_t)va_arg(params, long);
- break;
-
+ break;
+
case CURLFORM_CONTENTLEN:
current_form->flags |= CURL_HTTPPOST_LARGE;
current_form->contentslength =
array_state?(curl_off_t)(size_t)array_value:va_arg(params, curl_off_t);
break;
- /* Get contents from a given file name */
- case CURLFORM_FILECONTENT:
- if(current_form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_READFILE))
- return_value = CURL_FORMADD_OPTION_TWICE;
- else {
- const char *filename = array_state?
- array_value:va_arg(params, char *);
- if(filename) {
- current_form->value = strdup(filename);
- if(!current_form->value)
- return_value = CURL_FORMADD_MEMORY;
- else {
- current_form->flags |= HTTPPOST_READFILE;
- current_form->value_alloc = TRUE;
- }
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
-
- /* We upload a file */
- case CURLFORM_FILE:
- {
- const char *filename = array_state?array_value:
- va_arg(params, char *);
-
- if(current_form->value) {
- if(current_form->flags & HTTPPOST_FILENAME) {
- if(filename) {
- char *fname = strdup(filename);
- if(!fname)
- return_value = CURL_FORMADD_MEMORY;
- else {
- form = AddFormInfo(fname, NULL, current_form);
- if(!form) {
+ /* Get contents from a given file name */
+ case CURLFORM_FILECONTENT:
+ if(current_form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_READFILE))
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else {
+ const char *filename = array_state?
+ array_value:va_arg(params, char *);
+ if(filename) {
+ current_form->value = strdup(filename);
+ if(!current_form->value)
+ return_value = CURL_FORMADD_MEMORY;
+ else {
+ current_form->flags |= HTTPPOST_READFILE;
+ current_form->value_alloc = TRUE;
+ }
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+
+ /* We upload a file */
+ case CURLFORM_FILE:
+ {
+ const char *filename = array_state?array_value:
+ va_arg(params, char *);
+
+ if(current_form->value) {
+ if(current_form->flags & HTTPPOST_FILENAME) {
+ if(filename) {
+ char *fname = strdup(filename);
+ if(!fname)
+ return_value = CURL_FORMADD_MEMORY;
+ else {
+ form = AddFormInfo(fname, NULL, current_form);
+ if(!form) {
free(fname);
- return_value = CURL_FORMADD_MEMORY;
- }
- else {
- form->value_alloc = TRUE;
- current_form = form;
- form = NULL;
- }
- }
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- else
- return_value = CURL_FORMADD_OPTION_TWICE;
- }
- else {
- if(filename) {
- current_form->value = strdup(filename);
- if(!current_form->value)
- return_value = CURL_FORMADD_MEMORY;
- else {
- current_form->flags |= HTTPPOST_FILENAME;
- current_form->value_alloc = TRUE;
- }
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
- }
-
- case CURLFORM_BUFFERPTR:
- current_form->flags |= HTTPPOST_PTRBUFFER|HTTPPOST_BUFFER;
- if(current_form->buffer)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else {
- char *buffer =
- array_state?array_value:va_arg(params, char *);
- if(buffer) {
- current_form->buffer = buffer; /* store for the moment */
- current_form->value = buffer; /* make it non-NULL to be accepted
- as fine */
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
-
- case CURLFORM_BUFFERLENGTH:
- if(current_form->bufferlength)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else
- current_form->bufferlength =
- array_state?(size_t)array_value:(size_t)va_arg(params, long);
- break;
-
- case CURLFORM_STREAM:
- current_form->flags |= HTTPPOST_CALLBACK;
- if(current_form->userp)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else {
- char *userp =
- array_state?array_value:va_arg(params, char *);
- if(userp) {
- current_form->userp = userp;
- current_form->value = userp; /* this isn't strictly true but we
- derive a value from this later on
- and we need this non-NULL to be
- accepted as a fine form part */
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
-
- case CURLFORM_CONTENTTYPE:
- {
- const char *contenttype =
- array_state?array_value:va_arg(params, char *);
- if(current_form->contenttype) {
- if(current_form->flags & HTTPPOST_FILENAME) {
- if(contenttype) {
- char *type = strdup(contenttype);
- if(!type)
- return_value = CURL_FORMADD_MEMORY;
- else {
- form = AddFormInfo(NULL, type, current_form);
- if(!form) {
+ return_value = CURL_FORMADD_MEMORY;
+ }
+ else {
+ form->value_alloc = TRUE;
+ current_form = form;
+ form = NULL;
+ }
+ }
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ else
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ }
+ else {
+ if(filename) {
+ current_form->value = strdup(filename);
+ if(!current_form->value)
+ return_value = CURL_FORMADD_MEMORY;
+ else {
+ current_form->flags |= HTTPPOST_FILENAME;
+ current_form->value_alloc = TRUE;
+ }
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+ }
+
+ case CURLFORM_BUFFERPTR:
+ current_form->flags |= HTTPPOST_PTRBUFFER|HTTPPOST_BUFFER;
+ if(current_form->buffer)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else {
+ char *buffer =
+ array_state?array_value:va_arg(params, char *);
+ if(buffer) {
+ current_form->buffer = buffer; /* store for the moment */
+ current_form->value = buffer; /* make it non-NULL to be accepted
+ as fine */
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+
+ case CURLFORM_BUFFERLENGTH:
+ if(current_form->bufferlength)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else
+ current_form->bufferlength =
+ array_state?(size_t)array_value:(size_t)va_arg(params, long);
+ break;
+
+ case CURLFORM_STREAM:
+ current_form->flags |= HTTPPOST_CALLBACK;
+ if(current_form->userp)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else {
+ char *userp =
+ array_state?array_value:va_arg(params, char *);
+ if(userp) {
+ current_form->userp = userp;
+ current_form->value = userp; /* this isn't strictly true but we
+ derive a value from this later on
+ and we need this non-NULL to be
+ accepted as a fine form part */
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+
+ case CURLFORM_CONTENTTYPE:
+ {
+ const char *contenttype =
+ array_state?array_value:va_arg(params, char *);
+ if(current_form->contenttype) {
+ if(current_form->flags & HTTPPOST_FILENAME) {
+ if(contenttype) {
+ char *type = strdup(contenttype);
+ if(!type)
+ return_value = CURL_FORMADD_MEMORY;
+ else {
+ form = AddFormInfo(NULL, type, current_form);
+ if(!form) {
free(type);
- return_value = CURL_FORMADD_MEMORY;
- }
- else {
- form->contenttype_alloc = TRUE;
- current_form = form;
- form = NULL;
- }
- }
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- else
- return_value = CURL_FORMADD_OPTION_TWICE;
- }
- else {
- if(contenttype) {
- current_form->contenttype = strdup(contenttype);
- if(!current_form->contenttype)
- return_value = CURL_FORMADD_MEMORY;
- else
- current_form->contenttype_alloc = TRUE;
- }
- else
- return_value = CURL_FORMADD_NULL;
- }
- break;
- }
- case CURLFORM_CONTENTHEADER:
- {
- /* this "cast increases required alignment of target type" but
- we consider it OK anyway */
+ return_value = CURL_FORMADD_MEMORY;
+ }
+ else {
+ form->contenttype_alloc = TRUE;
+ current_form = form;
+ form = NULL;
+ }
+ }
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ else
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ }
+ else {
+ if(contenttype) {
+ current_form->contenttype = strdup(contenttype);
+ if(!current_form->contenttype)
+ return_value = CURL_FORMADD_MEMORY;
+ else
+ current_form->contenttype_alloc = TRUE;
+ }
+ else
+ return_value = CURL_FORMADD_NULL;
+ }
+ break;
+ }
+ case CURLFORM_CONTENTHEADER:
+ {
+ /* this "cast increases required alignment of target type" but
+ we consider it OK anyway */
struct curl_slist *list = array_state?
(struct curl_slist *)(void *)array_value:
va_arg(params, struct curl_slist *);
-
- if(current_form->contentheader)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else
- current_form->contentheader = list;
-
- break;
- }
- case CURLFORM_FILENAME:
- case CURLFORM_BUFFER:
- {
- const char *filename = array_state?array_value:
- va_arg(params, char *);
- if(current_form->showfilename)
- return_value = CURL_FORMADD_OPTION_TWICE;
- else {
- current_form->showfilename = strdup(filename);
- if(!current_form->showfilename)
- return_value = CURL_FORMADD_MEMORY;
- else
- current_form->showfilename_alloc = TRUE;
- }
- break;
- }
- default:
- return_value = CURL_FORMADD_UNKNOWN_OPTION;
- break;
- }
- }
-
- if(CURL_FORMADD_OK != return_value) {
- /* On error, free allocated fields for all nodes of the FormInfo linked
- list without deallocating nodes. List nodes are deallocated later on */
+
+ if(current_form->contentheader)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else
+ current_form->contentheader = list;
+
+ break;
+ }
+ case CURLFORM_FILENAME:
+ case CURLFORM_BUFFER:
+ {
+ const char *filename = array_state?array_value:
+ va_arg(params, char *);
+ if(current_form->showfilename)
+ return_value = CURL_FORMADD_OPTION_TWICE;
+ else {
+ current_form->showfilename = strdup(filename);
+ if(!current_form->showfilename)
+ return_value = CURL_FORMADD_MEMORY;
+ else
+ current_form->showfilename_alloc = TRUE;
+ }
+ break;
+ }
+ default:
+ return_value = CURL_FORMADD_UNKNOWN_OPTION;
+ break;
+ }
+ }
+
+ if(CURL_FORMADD_OK != return_value) {
+ /* On error, free allocated fields for all nodes of the FormInfo linked
+ list without deallocating nodes. List nodes are deallocated later on */
struct FormInfo *ptr;
- for(ptr = first_form; ptr != NULL; ptr = ptr->more) {
- if(ptr->name_alloc) {
- Curl_safefree(ptr->name);
- ptr->name_alloc = FALSE;
- }
- if(ptr->value_alloc) {
- Curl_safefree(ptr->value);
- ptr->value_alloc = FALSE;
- }
- if(ptr->contenttype_alloc) {
- Curl_safefree(ptr->contenttype);
- ptr->contenttype_alloc = FALSE;
- }
- if(ptr->showfilename_alloc) {
- Curl_safefree(ptr->showfilename);
- ptr->showfilename_alloc = FALSE;
- }
- }
- }
-
- if(CURL_FORMADD_OK == return_value) {
- /* go through the list, check for completeness and if everything is
- * alright add the HttpPost item otherwise set return_value accordingly */
-
- post = NULL;
- for(form = first_form;
- form != NULL;
- form = form->more) {
- if(((!form->name || !form->value) && !post) ||
- ( (form->contentslength) &&
- (form->flags & HTTPPOST_FILENAME) ) ||
- ( (form->flags & HTTPPOST_FILENAME) &&
- (form->flags & HTTPPOST_PTRCONTENTS) ) ||
-
- ( (!form->buffer) &&
- (form->flags & HTTPPOST_BUFFER) &&
- (form->flags & HTTPPOST_PTRBUFFER) ) ||
-
- ( (form->flags & HTTPPOST_READFILE) &&
- (form->flags & HTTPPOST_PTRCONTENTS) )
- ) {
- return_value = CURL_FORMADD_INCOMPLETE;
- break;
- }
+ for(ptr = first_form; ptr != NULL; ptr = ptr->more) {
+ if(ptr->name_alloc) {
+ Curl_safefree(ptr->name);
+ ptr->name_alloc = FALSE;
+ }
+ if(ptr->value_alloc) {
+ Curl_safefree(ptr->value);
+ ptr->value_alloc = FALSE;
+ }
+ if(ptr->contenttype_alloc) {
+ Curl_safefree(ptr->contenttype);
+ ptr->contenttype_alloc = FALSE;
+ }
+ if(ptr->showfilename_alloc) {
+ Curl_safefree(ptr->showfilename);
+ ptr->showfilename_alloc = FALSE;
+ }
+ }
+ }
+
+ if(CURL_FORMADD_OK == return_value) {
+ /* go through the list, check for completeness and if everything is
+ * alright add the HttpPost item otherwise set return_value accordingly */
+
+ post = NULL;
+ for(form = first_form;
+ form != NULL;
+ form = form->more) {
+ if(((!form->name || !form->value) && !post) ||
+ ( (form->contentslength) &&
+ (form->flags & HTTPPOST_FILENAME) ) ||
+ ( (form->flags & HTTPPOST_FILENAME) &&
+ (form->flags & HTTPPOST_PTRCONTENTS) ) ||
+
+ ( (!form->buffer) &&
+ (form->flags & HTTPPOST_BUFFER) &&
+ (form->flags & HTTPPOST_PTRBUFFER) ) ||
+
+ ( (form->flags & HTTPPOST_READFILE) &&
+ (form->flags & HTTPPOST_PTRCONTENTS) )
+ ) {
+ return_value = CURL_FORMADD_INCOMPLETE;
+ break;
+ }
if(((form->flags & HTTPPOST_FILENAME) ||
(form->flags & HTTPPOST_BUFFER)) &&
!form->contenttype) {
@@ -577,13 +577,13 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
type = prevtype;
if(!type)
type = FILE_CONTENTTYPE_DEFAULT;
-
+
/* our contenttype is missing */
form->contenttype = strdup(type);
if(!form->contenttype) {
return_value = CURL_FORMADD_MEMORY;
break;
- }
+ }
form->contenttype_alloc = TRUE;
}
if(form->name && form->namelength) {
@@ -592,8 +592,8 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
for(i = 0; i < form->namelength; i++)
if(!form->name[i]) {
return_value = CURL_FORMADD_NULL;
- break;
- }
+ break;
+ }
if(return_value != CURL_FORMADD_OK)
break;
}
@@ -606,11 +606,11 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
form->name = Curl_memdup(form->name, form->namelength?
form->namelength:
strlen(form->name) + 1);
- }
+ }
if(!form->name) {
return_value = CURL_FORMADD_MEMORY;
break;
- }
+ }
form->name_alloc = TRUE;
}
if(!(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE |
@@ -620,13 +620,13 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
size_t clen = (size_t) form->contentslength;
if(!clen)
clen = strlen(form->value) + 1;
-
+
form->value = Curl_memdup(form->value, clen);
if(!form->value) {
- return_value = CURL_FORMADD_MEMORY;
- break;
- }
+ return_value = CURL_FORMADD_MEMORY;
+ break;
+ }
form->value_alloc = TRUE;
}
post = AddHttpPost(form->name, form->namelength,
@@ -637,146 +637,146 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
form->userp,
post, httppost,
last_post);
-
+
if(!post) {
return_value = CURL_FORMADD_MEMORY;
break;
- }
+ }
if(form->contenttype)
prevtype = form->contenttype;
- }
- if(CURL_FORMADD_OK != return_value) {
- /* On error, free allocated fields for nodes of the FormInfo linked
- list which are not already owned by the httppost linked list
- without deallocating nodes. List nodes are deallocated later on */
+ }
+ if(CURL_FORMADD_OK != return_value) {
+ /* On error, free allocated fields for nodes of the FormInfo linked
+ list which are not already owned by the httppost linked list
+ without deallocating nodes. List nodes are deallocated later on */
struct FormInfo *ptr;
- for(ptr = form; ptr != NULL; ptr = ptr->more) {
- if(ptr->name_alloc) {
- Curl_safefree(ptr->name);
- ptr->name_alloc = FALSE;
- }
- if(ptr->value_alloc) {
- Curl_safefree(ptr->value);
- ptr->value_alloc = FALSE;
- }
- if(ptr->contenttype_alloc) {
- Curl_safefree(ptr->contenttype);
- ptr->contenttype_alloc = FALSE;
- }
- if(ptr->showfilename_alloc) {
- Curl_safefree(ptr->showfilename);
- ptr->showfilename_alloc = FALSE;
- }
- }
- }
- }
-
- /* Always deallocate FormInfo linked list nodes without touching node
- fields given that these have either been deallocated or are owned
- now by the httppost linked list */
- while(first_form) {
+ for(ptr = form; ptr != NULL; ptr = ptr->more) {
+ if(ptr->name_alloc) {
+ Curl_safefree(ptr->name);
+ ptr->name_alloc = FALSE;
+ }
+ if(ptr->value_alloc) {
+ Curl_safefree(ptr->value);
+ ptr->value_alloc = FALSE;
+ }
+ if(ptr->contenttype_alloc) {
+ Curl_safefree(ptr->contenttype);
+ ptr->contenttype_alloc = FALSE;
+ }
+ if(ptr->showfilename_alloc) {
+ Curl_safefree(ptr->showfilename);
+ ptr->showfilename_alloc = FALSE;
+ }
+ }
+ }
+ }
+
+ /* Always deallocate FormInfo linked list nodes without touching node
+ fields given that these have either been deallocated or are owned
+ now by the httppost linked list */
+ while(first_form) {
struct FormInfo *ptr = first_form->more;
free(first_form);
- first_form = ptr;
- }
-
- return return_value;
-}
-
-/*
- * curl_formadd() is a public API to add a section to the multipart formpost.
- *
- * @unittest: 1308
- */
-
-CURLFORMcode curl_formadd(struct curl_httppost **httppost,
- struct curl_httppost **last_post,
- ...)
-{
- va_list arg;
- CURLFORMcode result;
- va_start(arg, last_post);
- result = FormAdd(httppost, last_post, arg);
- va_end(arg);
- return result;
-}
-
-/*
- * curl_formget()
- * Serialize a curl_httppost struct.
- * Returns 0 on success.
- *
- * @unittest: 1308
- */
-int curl_formget(struct curl_httppost *form, void *arg,
- curl_formget_callback append)
-{
+ first_form = ptr;
+ }
+
+ return return_value;
+}
+
+/*
+ * curl_formadd() is a public API to add a section to the multipart formpost.
+ *
+ * @unittest: 1308
+ */
+
+CURLFORMcode curl_formadd(struct curl_httppost **httppost,
+ struct curl_httppost **last_post,
+ ...)
+{
+ va_list arg;
+ CURLFORMcode result;
+ va_start(arg, last_post);
+ result = FormAdd(httppost, last_post, arg);
+ va_end(arg);
+ return result;
+}
+
+/*
+ * curl_formget()
+ * Serialize a curl_httppost struct.
+ * Returns 0 on success.
+ *
+ * @unittest: 1308
+ */
+int curl_formget(struct curl_httppost *form, void *arg,
+ curl_formget_callback append)
+{
CURLcode result;
curl_mimepart toppart;
-
+
Curl_mime_initpart(&toppart, NULL); /* default form is empty */
result = Curl_getformdata(NULL, &toppart, form, NULL);
if(!result)
result = Curl_mime_prepare_headers(&toppart, "multipart/form-data",
NULL, MIMESTRATEGY_FORM);
-
+
while(!result) {
char buffer[8192];
size_t nread = Curl_mime_read(buffer, 1, sizeof(buffer), &toppart);
-
+
if(!nread)
break;
-
+
if(nread > sizeof(buffer) || append(arg, buffer, nread) != nread) {
result = CURLE_READ_ERROR;
if(nread == CURL_READFUNC_ABORT)
result = CURLE_ABORTED_BY_CALLBACK;
- }
- }
+ }
+ }
Curl_mime_cleanpart(&toppart);
return (int) result;
-}
-
-/*
- * curl_formfree() is an external function to free up a whole form post
- * chain
- */
-void curl_formfree(struct curl_httppost *form)
-{
- struct curl_httppost *next;
-
- if(!form)
- /* no form to free, just get out of this */
- return;
-
- do {
+}
+
+/*
+ * curl_formfree() is an external function to free up a whole form post
+ * chain
+ */
+void curl_formfree(struct curl_httppost *form)
+{
+ struct curl_httppost *next;
+
+ if(!form)
+ /* no form to free, just get out of this */
+ return;
+
+ do {
next = form->next; /* the following form line */
-
- /* recurse to sub-contents */
+
+ /* recurse to sub-contents */
curl_formfree(form->more);
-
+
if(!(form->flags & HTTPPOST_PTRNAME))
- free(form->name); /* free the name */
- if(!(form->flags &
+ free(form->name); /* free the name */
+ if(!(form->flags &
(HTTPPOST_PTRCONTENTS|HTTPPOST_BUFFER|HTTPPOST_CALLBACK))
)
- free(form->contents); /* free the contents */
+ free(form->contents); /* free the contents */
free(form->contenttype); /* free the content type */
free(form->showfilename); /* free the faked file name */
- free(form); /* free the struct */
+ free(form); /* free the struct */
form = next;
} while(form); /* continue */
-}
-
-
+}
+
+
/* Set mime part name, taking care of non null-terminated name string. */
static CURLcode setname(curl_mimepart *part, const char *name, size_t len)
-{
+{
char *zname;
CURLcode res;
-
+
if(!name || !len)
return curl_mime_name(part, name);
zname = malloc(len + 1);
@@ -787,87 +787,87 @@ static CURLcode setname(curl_mimepart *part, const char *name, size_t len)
res = curl_mime_name(part, zname);
free(zname);
return res;
-}
-
-/*
+}
+
+/*
* Curl_getformdata() converts a linked list of "meta data" into a mime
* structure. The input list is in 'post', while the output is stored in
* mime part at '*finalform'.
- *
- * This function will not do a failf() for the potential memory failures but
- * should for all other errors it spots. Just note that this function MAY get
- * a NULL pointer in the 'data' argument.
- */
-
+ *
+ * This function will not do a failf() for the potential memory failures but
+ * should for all other errors it spots. Just note that this function MAY get
+ * a NULL pointer in the 'data' argument.
+ */
+
CURLcode Curl_getformdata(struct Curl_easy *data,
curl_mimepart *finalform,
- struct curl_httppost *post,
+ struct curl_httppost *post,
curl_read_callback fread_func)
-{
+{
CURLcode result = CURLE_OK;
curl_mime *form = NULL;
curl_mimepart *part;
- struct curl_httppost *file;
-
+ struct curl_httppost *file;
+
Curl_mime_cleanpart(finalform); /* default form is empty */
-
- if(!post)
- return result; /* no input => no output! */
-
+
+ if(!post)
+ return result; /* no input => no output! */
+
form = curl_mime_init(data);
if(!form)
result = CURLE_OUT_OF_MEMORY;
-
+
if(!result)
result = curl_mime_subparts(finalform, form);
-
+
/* Process each top part. */
for(; !result && post; post = post->next) {
/* If we have more than a file here, create a mime subpart and fill it. */
curl_mime *multipart = form;
- if(post->more) {
+ if(post->more) {
part = curl_mime_addpart(form);
if(!part)
- result = CURLE_OUT_OF_MEMORY;
+ result = CURLE_OUT_OF_MEMORY;
if(!result)
result = setname(part, post->name, post->namelength);
if(!result) {
multipart = curl_mime_init(data);
if(!multipart)
result = CURLE_OUT_OF_MEMORY;
- }
+ }
if(!result)
result = curl_mime_subparts(part, multipart);
- }
-
+ }
+
/* Generate all the part contents. */
for(file = post; !result && file; file = file->more) {
/* Create the part. */
part = curl_mime_addpart(multipart);
if(!part)
result = CURLE_OUT_OF_MEMORY;
-
+
/* Set the headers. */
if(!result)
result = curl_mime_headers(part, file->contentheader, 0);
-
+
/* Set the content type. */
if(!result && file->contenttype)
result = curl_mime_type(part, file->contenttype);
-
+
/* Set field name. */
if(!result && !post->more)
result = setname(part, post->name, post->namelength);
-
+
/* Process contents. */
if(!result) {
curl_off_t clen = post->contentslength;
-
+
if(post->flags & CURL_HTTPPOST_LARGE)
clen = post->contentlen;
if(!clen)
clen = -1;
-
+
if(post->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE)) {
if(!strcmp(file->contents, "-")) {
/* There are a few cases where the code below won't work; in
@@ -879,12 +879,12 @@ CURLcode Curl_getformdata(struct Curl_easy *data,
CURLX_FUNCTION_CAST(curl_seek_callback,
fseek),
NULL, (void *) stdin);
- }
+ }
else
result = curl_mime_filedata(part, file->contents);
if(!result && (post->flags & HTTPPOST_READFILE))
result = curl_mime_filename(part, NULL);
- }
+ }
else if(post->flags & HTTPPOST_BUFFER)
result = curl_mime_data(part, post->buffer,
post->bufferlength? post->bufferlength: -1);
@@ -893,54 +893,54 @@ CURLcode Curl_getformdata(struct Curl_easy *data,
with the contentslength */
result = curl_mime_data_cb(part, clen,
fread_func, NULL, NULL, post->userp);
- else {
+ else {
result = curl_mime_data(part, post->contents, (ssize_t) clen);
#ifdef CURL_DOES_CONVERSIONS
/* Convert textual contents now. */
if(!result && data && part->datasize)
result = Curl_convert_to_network(data, part->data, part->datasize);
#endif
- }
- }
-
+ }
+ }
+
/* Set fake file name. */
if(!result && post->showfilename)
if(post->more || (post->flags & (HTTPPOST_FILENAME | HTTPPOST_BUFFER |
HTTPPOST_CALLBACK)))
result = curl_mime_filename(part, post->showfilename);
- }
- }
-
+ }
+ }
+
if(result)
Curl_mime_cleanpart(finalform);
-
- return result;
-}
-
+
+ return result;
+}
+
#else
/* if disabled */
-CURLFORMcode curl_formadd(struct curl_httppost **httppost,
- struct curl_httppost **last_post,
- ...)
-{
- (void)httppost;
- (void)last_post;
- return CURL_FORMADD_DISABLED;
-}
-
-int curl_formget(struct curl_httppost *form, void *arg,
- curl_formget_callback append)
-{
- (void) form;
- (void) arg;
- (void) append;
- return CURL_FORMADD_DISABLED;
-}
-
-void curl_formfree(struct curl_httppost *form)
-{
- (void)form;
- /* does nothing HTTP is disabled */
-}
-
+CURLFORMcode curl_formadd(struct curl_httppost **httppost,
+ struct curl_httppost **last_post,
+ ...)
+{
+ (void)httppost;
+ (void)last_post;
+ return CURL_FORMADD_DISABLED;
+}
+
+int curl_formget(struct curl_httppost *form, void *arg,
+ curl_formget_callback append)
+{
+ (void) form;
+ (void) arg;
+ (void) append;
+ return CURL_FORMADD_DISABLED;
+}
+
+void curl_formfree(struct curl_httppost *form)
+{
+ (void)form;
+ /* does nothing HTTP is disabled */
+}
+
#endif /* if disabled */
diff --git a/contrib/libs/curl/lib/formdata.h b/contrib/libs/curl/lib/formdata.h
index bdf59e9528..5a021ceb92 100644
--- a/contrib/libs/curl/lib/formdata.h
+++ b/contrib/libs/curl/lib/formdata.h
@@ -1,60 +1,60 @@
-#ifndef HEADER_CURL_FORMDATA_H
-#define HEADER_CURL_FORMDATA_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_FORMDATA_H
+#define HEADER_CURL_FORMDATA_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include "curl_setup.h"
#ifndef CURL_DISABLE_MIME
-/* used by FormAdd for temporary storage */
+/* used by FormAdd for temporary storage */
struct FormInfo {
- char *name;
- bool name_alloc;
- size_t namelength;
- char *value;
- bool value_alloc;
+ char *name;
+ bool name_alloc;
+ size_t namelength;
+ char *value;
+ bool value_alloc;
curl_off_t contentslength;
- char *contenttype;
- bool contenttype_alloc;
- long flags;
- char *buffer; /* pointer to existing buffer used for file upload */
- size_t bufferlength;
- char *showfilename; /* The file name to show. If not set, the actual
- file name will be used */
- bool showfilename_alloc;
- char *userp; /* pointer for the read callback */
+ char *contenttype;
+ bool contenttype_alloc;
+ long flags;
+ char *buffer; /* pointer to existing buffer used for file upload */
+ size_t bufferlength;
+ char *showfilename; /* The file name to show. If not set, the actual
+ file name will be used */
+ bool showfilename_alloc;
+ char *userp; /* pointer for the read callback */
struct curl_slist *contentheader;
- struct FormInfo *more;
+ struct FormInfo *more;
};
-
+
CURLcode Curl_getformdata(struct Curl_easy *data,
curl_mimepart *,
- struct curl_httppost *post,
+ struct curl_httppost *post,
curl_read_callback fread_func);
#else
/* disabled */
#define Curl_getformdata(a,b,c,d) CURLE_NOT_BUILT_IN
#endif
-
-#endif /* HEADER_CURL_FORMDATA_H */
+
+#endif /* HEADER_CURL_FORMDATA_H */
diff --git a/contrib/libs/curl/lib/ftp.c b/contrib/libs/curl/lib/ftp.c
index c2d11b96e5..bc35574217 100644
--- a/contrib/libs/curl/lib/ftp.c
+++ b/contrib/libs/curl/lib/ftp.c
@@ -1,211 +1,211 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_FTP
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_UTSNAME_H
-#include <sys/utsname.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-#include <curl/curl.h>
-#include "urldata.h"
-#include "sendf.h"
-#include "if2ip.h"
-#include "hostip.h"
-#include "progress.h"
-#include "transfer.h"
-#include "escape.h"
-#include "http.h" /* for HTTP proxy tunnel stuff */
-#include "ftp.h"
-#include "fileinfo.h"
-#include "ftplistparser.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_FTP
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_UTSNAME_H
+#include <sys/utsname.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "sendf.h"
+#include "if2ip.h"
+#include "hostip.h"
+#include "progress.h"
+#include "transfer.h"
+#include "escape.h"
+#include "http.h" /* for HTTP proxy tunnel stuff */
+#include "ftp.h"
+#include "fileinfo.h"
+#include "ftplistparser.h"
#include "curl_range.h"
#include "curl_krb5.h"
-#include "strtoofft.h"
+#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
-#include "connect.h"
-#include "strerror.h"
-#include "inet_ntop.h"
-#include "inet_pton.h"
-#include "select.h"
-#include "parsedate.h" /* for the week day and month names */
-#include "sockaddr.h" /* required for Curl_sockaddr_storage */
-#include "multiif.h"
-#include "url.h"
+#include "connect.h"
+#include "strerror.h"
+#include "inet_ntop.h"
+#include "inet_pton.h"
+#include "select.h"
+#include "parsedate.h" /* for the week day and month names */
+#include "sockaddr.h" /* required for Curl_sockaddr_storage */
+#include "multiif.h"
+#include "url.h"
#include "strcase.h"
-#include "speedcheck.h"
-#include "warnless.h"
-#include "http_proxy.h"
-#include "non-ascii.h"
+#include "speedcheck.h"
+#include "warnless.h"
+#include "http_proxy.h"
+#include "non-ascii.h"
#include "socks.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-#ifndef NI_MAXHOST
-#define NI_MAXHOST 1025
-#endif
-#ifndef INET_ADDRSTRLEN
-#define INET_ADDRSTRLEN 16
-#endif
-
-#ifdef CURL_DISABLE_VERBOSE_STRINGS
-#define ftp_pasv_verbose(a,b,c,d) Curl_nop_stmt
-#endif
-
-/* Local API functions */
-#ifndef DEBUGBUILD
-static void _state(struct connectdata *conn,
- ftpstate newstate);
-#define state(x,y) _state(x,y)
-#else
-static void _state(struct connectdata *conn,
- ftpstate newstate,
- int lineno);
-#define state(x,y) _state(x,y,__LINE__)
-#endif
-
-static CURLcode ftp_sendquote(struct connectdata *conn,
- struct curl_slist *quote);
-static CURLcode ftp_quit(struct connectdata *conn);
-static CURLcode ftp_parse_url_path(struct connectdata *conn);
-static CURLcode ftp_regular_transfer(struct connectdata *conn, bool *done);
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-static void ftp_pasv_verbose(struct connectdata *conn,
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#ifndef NI_MAXHOST
+#define NI_MAXHOST 1025
+#endif
+#ifndef INET_ADDRSTRLEN
+#define INET_ADDRSTRLEN 16
+#endif
+
+#ifdef CURL_DISABLE_VERBOSE_STRINGS
+#define ftp_pasv_verbose(a,b,c,d) Curl_nop_stmt
+#endif
+
+/* Local API functions */
+#ifndef DEBUGBUILD
+static void _state(struct connectdata *conn,
+ ftpstate newstate);
+#define state(x,y) _state(x,y)
+#else
+static void _state(struct connectdata *conn,
+ ftpstate newstate,
+ int lineno);
+#define state(x,y) _state(x,y,__LINE__)
+#endif
+
+static CURLcode ftp_sendquote(struct connectdata *conn,
+ struct curl_slist *quote);
+static CURLcode ftp_quit(struct connectdata *conn);
+static CURLcode ftp_parse_url_path(struct connectdata *conn);
+static CURLcode ftp_regular_transfer(struct connectdata *conn, bool *done);
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+static void ftp_pasv_verbose(struct connectdata *conn,
struct Curl_addrinfo *ai,
- char *newhost, /* ascii version */
- int port);
-#endif
-static CURLcode ftp_state_prepare_transfer(struct connectdata *conn);
-static CURLcode ftp_state_mdtm(struct connectdata *conn);
-static CURLcode ftp_state_quote(struct connectdata *conn,
- bool init, ftpstate instate);
-static CURLcode ftp_nb_type(struct connectdata *conn,
- bool ascii, ftpstate newstate);
-static int ftp_need_type(struct connectdata *conn,
- bool ascii);
-static CURLcode ftp_do(struct connectdata *conn, bool *done);
-static CURLcode ftp_done(struct connectdata *conn,
- CURLcode, bool premature);
-static CURLcode ftp_connect(struct connectdata *conn, bool *done);
-static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection);
-static CURLcode ftp_do_more(struct connectdata *conn, int *completed);
-static CURLcode ftp_multi_statemach(struct connectdata *conn, bool *done);
+ char *newhost, /* ascii version */
+ int port);
+#endif
+static CURLcode ftp_state_prepare_transfer(struct connectdata *conn);
+static CURLcode ftp_state_mdtm(struct connectdata *conn);
+static CURLcode ftp_state_quote(struct connectdata *conn,
+ bool init, ftpstate instate);
+static CURLcode ftp_nb_type(struct connectdata *conn,
+ bool ascii, ftpstate newstate);
+static int ftp_need_type(struct connectdata *conn,
+ bool ascii);
+static CURLcode ftp_do(struct connectdata *conn, bool *done);
+static CURLcode ftp_done(struct connectdata *conn,
+ CURLcode, bool premature);
+static CURLcode ftp_connect(struct connectdata *conn, bool *done);
+static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection);
+static CURLcode ftp_do_more(struct connectdata *conn, int *completed);
+static CURLcode ftp_multi_statemach(struct connectdata *conn, bool *done);
static int ftp_getsock(struct connectdata *conn, curl_socket_t *socks);
static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks);
-static CURLcode ftp_doing(struct connectdata *conn,
- bool *dophase_done);
+static CURLcode ftp_doing(struct connectdata *conn,
+ bool *dophase_done);
static CURLcode ftp_setup_connection(struct connectdata *conn);
-static CURLcode init_wc_data(struct connectdata *conn);
-static CURLcode wc_statemach(struct connectdata *conn);
-static void wc_data_dtor(void *ptr);
-static CURLcode ftp_state_retr(struct connectdata *conn, curl_off_t filesize);
-static CURLcode ftp_readresp(curl_socket_t sockfd,
- struct pingpong *pp,
- int *ftpcode,
- size_t *size);
-static CURLcode ftp_dophase_done(struct connectdata *conn,
- bool connected);
-
-/*
- * FTP protocol handler.
- */
-
-const struct Curl_handler Curl_handler_ftp = {
- "FTP", /* scheme */
- ftp_setup_connection, /* setup_connection */
- ftp_do, /* do_it */
- ftp_done, /* done */
- ftp_do_more, /* do_more */
- ftp_connect, /* connect_it */
- ftp_multi_statemach, /* connecting */
- ftp_doing, /* doing */
- ftp_getsock, /* proto_getsock */
- ftp_getsock, /* doing_getsock */
- ftp_domore_getsock, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ftp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+static CURLcode init_wc_data(struct connectdata *conn);
+static CURLcode wc_statemach(struct connectdata *conn);
+static void wc_data_dtor(void *ptr);
+static CURLcode ftp_state_retr(struct connectdata *conn, curl_off_t filesize);
+static CURLcode ftp_readresp(curl_socket_t sockfd,
+ struct pingpong *pp,
+ int *ftpcode,
+ size_t *size);
+static CURLcode ftp_dophase_done(struct connectdata *conn,
+ bool connected);
+
+/*
+ * FTP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_ftp = {
+ "FTP", /* scheme */
+ ftp_setup_connection, /* setup_connection */
+ ftp_do, /* do_it */
+ ftp_done, /* done */
+ ftp_do_more, /* do_more */
+ ftp_connect, /* connect_it */
+ ftp_multi_statemach, /* connecting */
+ ftp_doing, /* doing */
+ ftp_getsock, /* proto_getsock */
+ ftp_getsock, /* doing_getsock */
+ ftp_domore_getsock, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ftp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_FTP, /* defport */
- CURLPROTO_FTP, /* protocol */
+ PORT_FTP, /* defport */
+ CURLPROTO_FTP, /* protocol */
CURLPROTO_FTP, /* family */
PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD |
PROTOPT_NOURLQUERY | PROTOPT_PROXY_AS_HTTP |
PROTOPT_WILDCARD /* flags */
-};
-
-
-#ifdef USE_SSL
-/*
- * FTPS protocol handler.
- */
-
-const struct Curl_handler Curl_handler_ftps = {
- "FTPS", /* scheme */
- ftp_setup_connection, /* setup_connection */
- ftp_do, /* do_it */
- ftp_done, /* done */
- ftp_do_more, /* do_more */
- ftp_connect, /* connect_it */
- ftp_multi_statemach, /* connecting */
- ftp_doing, /* doing */
- ftp_getsock, /* proto_getsock */
- ftp_getsock, /* doing_getsock */
- ftp_domore_getsock, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ftp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+};
+
+
+#ifdef USE_SSL
+/*
+ * FTPS protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_ftps = {
+ "FTPS", /* scheme */
+ ftp_setup_connection, /* setup_connection */
+ ftp_do, /* do_it */
+ ftp_done, /* done */
+ ftp_do_more, /* do_more */
+ ftp_connect, /* connect_it */
+ ftp_multi_statemach, /* connecting */
+ ftp_doing, /* doing */
+ ftp_getsock, /* proto_getsock */
+ ftp_getsock, /* doing_getsock */
+ ftp_domore_getsock, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ftp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_FTPS, /* defport */
+ PORT_FTPS, /* defport */
CURLPROTO_FTPS, /* protocol */
CURLPROTO_FTP, /* family */
- PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION |
+ PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION |
PROTOPT_NEEDSPWD | PROTOPT_NOURLQUERY | PROTOPT_WILDCARD /* flags */
-};
-#endif
-
+};
+#endif
+
static void close_secondarysocket(struct connectdata *conn)
{
if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
@@ -217,556 +217,556 @@ static void close_secondarysocket(struct connectdata *conn)
conn->bits.proxy_ssl_connected[SECONDARYSOCKET] = FALSE;
#endif
}
-
-/*
- * NOTE: back in the old days, we added code in the FTP code that made NOBODY
- * requests on files respond with headers passed to the client/stdout that
- * looked like HTTP ones.
- *
- * This approach is not very elegant, it causes confusion and is error-prone.
- * It is subject for removal at the next (or at least a future) soname bump.
- * Until then you can test the effects of the removal by undefining the
- * following define named CURL_FTP_HTTPSTYLE_HEAD.
- */
-#define CURL_FTP_HTTPSTYLE_HEAD 1
-
-static void freedirs(struct ftp_conn *ftpc)
-{
- if(ftpc->dirs) {
+
+/*
+ * NOTE: back in the old days, we added code in the FTP code that made NOBODY
+ * requests on files respond with headers passed to the client/stdout that
+ * looked like HTTP ones.
+ *
+ * This approach is not very elegant, it causes confusion and is error-prone.
+ * It is subject for removal at the next (or at least a future) soname bump.
+ * Until then you can test the effects of the removal by undefining the
+ * following define named CURL_FTP_HTTPSTYLE_HEAD.
+ */
+#define CURL_FTP_HTTPSTYLE_HEAD 1
+
+static void freedirs(struct ftp_conn *ftpc)
+{
+ if(ftpc->dirs) {
int i;
for(i = 0; i < ftpc->dirdepth; i++) {
free(ftpc->dirs[i]);
ftpc->dirs[i] = NULL;
- }
- free(ftpc->dirs);
- ftpc->dirs = NULL;
- ftpc->dirdepth = 0;
- }
+ }
+ free(ftpc->dirs);
+ ftpc->dirs = NULL;
+ ftpc->dirdepth = 0;
+ }
Curl_safefree(ftpc->file);
/* no longer of any use */
Curl_safefree(ftpc->newhost);
-}
-
-/***********************************************************************
- *
- * AcceptServerConnect()
- *
- * After connection request is received from the server this function is
- * called to accept the connection and close the listening socket
- *
- */
-static CURLcode AcceptServerConnect(struct connectdata *conn)
-{
+}
+
+/***********************************************************************
+ *
+ * AcceptServerConnect()
+ *
+ * After connection request is received from the server this function is
+ * called to accept the connection and close the listening socket
+ *
+ */
+static CURLcode AcceptServerConnect(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- curl_socket_t sock = conn->sock[SECONDARYSOCKET];
- curl_socket_t s = CURL_SOCKET_BAD;
-#ifdef ENABLE_IPV6
- struct Curl_sockaddr_storage add;
-#else
- struct sockaddr_in add;
-#endif
- curl_socklen_t size = (curl_socklen_t) sizeof(add);
-
- if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) {
- size = sizeof(add);
-
+ curl_socket_t sock = conn->sock[SECONDARYSOCKET];
+ curl_socket_t s = CURL_SOCKET_BAD;
+#ifdef ENABLE_IPV6
+ struct Curl_sockaddr_storage add;
+#else
+ struct sockaddr_in add;
+#endif
+ curl_socklen_t size = (curl_socklen_t) sizeof(add);
+
+ if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) {
+ size = sizeof(add);
+
s = accept(sock, (struct sockaddr *) &add, &size);
- }
- Curl_closesocket(conn, sock); /* close the first socket */
-
- if(CURL_SOCKET_BAD == s) {
- failf(data, "Error accept()ing server connect");
- return CURLE_FTP_PORT_FAILED;
- }
- infof(data, "Connection accepted from server\n");
+ }
+ Curl_closesocket(conn, sock); /* close the first socket */
+
+ if(CURL_SOCKET_BAD == s) {
+ failf(data, "Error accept()ing server connect");
+ return CURLE_FTP_PORT_FAILED;
+ }
+ infof(data, "Connection accepted from server\n");
/* when this happens within the DO state it is important that we mark us as
not needing DO_MORE anymore */
conn->bits.do_more = FALSE;
-
- conn->sock[SECONDARYSOCKET] = s;
+
+ conn->sock[SECONDARYSOCKET] = s;
(void)curlx_nonblock(s, TRUE); /* enable non-blocking */
conn->bits.sock_accepted = TRUE;
-
- if(data->set.fsockopt) {
- int error = 0;
-
- /* activate callback for setting socket options */
+
+ if(data->set.fsockopt) {
+ int error = 0;
+
+ /* activate callback for setting socket options */
Curl_set_in_callback(data, true);
- error = data->set.fsockopt(data->set.sockopt_client,
- s,
- CURLSOCKTYPE_ACCEPT);
+ error = data->set.fsockopt(data->set.sockopt_client,
+ s,
+ CURLSOCKTYPE_ACCEPT);
Curl_set_in_callback(data, false);
-
- if(error) {
+
+ if(error) {
close_secondarysocket(conn);
- return CURLE_ABORTED_BY_CALLBACK;
- }
- }
-
- return CURLE_OK;
-
-}
-
-/*
- * ftp_timeleft_accept() returns the amount of milliseconds left allowed for
- * waiting server to connect. If the value is negative, the timeout time has
- * already elapsed.
- *
- * The start time is stored in progress.t_acceptdata - as set with
- * Curl_pgrsTime(..., TIMER_STARTACCEPT);
- *
- */
+ return CURLE_ABORTED_BY_CALLBACK;
+ }
+ }
+
+ return CURLE_OK;
+
+}
+
+/*
+ * ftp_timeleft_accept() returns the amount of milliseconds left allowed for
+ * waiting server to connect. If the value is negative, the timeout time has
+ * already elapsed.
+ *
+ * The start time is stored in progress.t_acceptdata - as set with
+ * Curl_pgrsTime(..., TIMER_STARTACCEPT);
+ *
+ */
static timediff_t ftp_timeleft_accept(struct Curl_easy *data)
-{
+{
timediff_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT;
timediff_t other;
struct curltime now;
-
- if(data->set.accepttimeout > 0)
- timeout_ms = data->set.accepttimeout;
-
+
+ if(data->set.accepttimeout > 0)
+ timeout_ms = data->set.accepttimeout;
+
now = Curl_now();
-
- /* check if the generic timeout possibly is set shorter */
+
+ /* check if the generic timeout possibly is set shorter */
other = Curl_timeleft(data, &now, FALSE);
- if(other && (other < timeout_ms))
- /* note that this also works fine for when other happens to be negative
- due to it already having elapsed */
- timeout_ms = other;
- else {
- /* subtract elapsed time */
+ if(other && (other < timeout_ms))
+ /* note that this also works fine for when other happens to be negative
+ due to it already having elapsed */
+ timeout_ms = other;
+ else {
+ /* subtract elapsed time */
timeout_ms -= Curl_timediff(now, data->progress.t_acceptdata);
- if(!timeout_ms)
- /* avoid returning 0 as that means no timeout! */
- return -1;
- }
-
- return timeout_ms;
-}
-
-
-/***********************************************************************
- *
- * ReceivedServerConnect()
- *
- * After allowing server to connect to us from data port, this function
- * checks both data connection for connection establishment and ctrl
- * connection for a negative response regarding a failure in connecting
- *
- */
-static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received)
-{
+ if(!timeout_ms)
+ /* avoid returning 0 as that means no timeout! */
+ return -1;
+ }
+
+ return timeout_ms;
+}
+
+
+/***********************************************************************
+ *
+ * ReceivedServerConnect()
+ *
+ * After allowing server to connect to us from data port, this function
+ * checks both data connection for connection establishment and ctrl
+ * connection for a negative response regarding a failure in connecting
+ *
+ */
+static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received)
+{
struct Curl_easy *data = conn->data;
- curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET];
- curl_socket_t data_sock = conn->sock[SECONDARYSOCKET];
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
- int result;
+ curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET];
+ curl_socket_t data_sock = conn->sock[SECONDARYSOCKET];
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+ int result;
timediff_t timeout_ms;
- ssize_t nread;
- int ftpcode;
-
- *received = FALSE;
-
- timeout_ms = ftp_timeleft_accept(data);
- infof(data, "Checking for server connect\n");
- if(timeout_ms < 0) {
- /* if a timeout was already reached, bail out */
- failf(data, "Accept timeout occurred while waiting server connect");
- return CURLE_FTP_ACCEPT_TIMEOUT;
- }
-
- /* First check whether there is a cached response from server */
- if(pp->cache_size && pp->cache && pp->cache[0] > '3') {
- /* Data connection could not be established, let's return */
- infof(data, "There is negative response in cache while serv connect\n");
+ ssize_t nread;
+ int ftpcode;
+
+ *received = FALSE;
+
+ timeout_ms = ftp_timeleft_accept(data);
+ infof(data, "Checking for server connect\n");
+ if(timeout_ms < 0) {
+ /* if a timeout was already reached, bail out */
+ failf(data, "Accept timeout occurred while waiting server connect");
+ return CURLE_FTP_ACCEPT_TIMEOUT;
+ }
+
+ /* First check whether there is a cached response from server */
+ if(pp->cache_size && pp->cache && pp->cache[0] > '3') {
+ /* Data connection could not be established, let's return */
+ infof(data, "There is negative response in cache while serv connect\n");
(void)Curl_GetFTPResponse(&nread, conn, &ftpcode);
- return CURLE_FTP_ACCEPT_FAILED;
- }
-
- result = Curl_socket_check(ctrl_sock, data_sock, CURL_SOCKET_BAD, 0);
-
- /* see if the connection request is already here */
+ return CURLE_FTP_ACCEPT_FAILED;
+ }
+
+ result = Curl_socket_check(ctrl_sock, data_sock, CURL_SOCKET_BAD, 0);
+
+ /* see if the connection request is already here */
switch(result) {
- case -1: /* error */
- /* let's die here */
- failf(data, "Error while waiting for server connect");
- return CURLE_FTP_ACCEPT_FAILED;
- case 0: /* Server connect is not received yet */
- break; /* loop */
- default:
-
- if(result & CURL_CSELECT_IN2) {
- infof(data, "Ready to accept data connection from server\n");
- *received = TRUE;
- }
- else if(result & CURL_CSELECT_IN) {
- infof(data, "Ctrl conn has data while waiting for data conn\n");
+ case -1: /* error */
+ /* let's die here */
+ failf(data, "Error while waiting for server connect");
+ return CURLE_FTP_ACCEPT_FAILED;
+ case 0: /* Server connect is not received yet */
+ break; /* loop */
+ default:
+
+ if(result & CURL_CSELECT_IN2) {
+ infof(data, "Ready to accept data connection from server\n");
+ *received = TRUE;
+ }
+ else if(result & CURL_CSELECT_IN) {
+ infof(data, "Ctrl conn has data while waiting for data conn\n");
(void)Curl_GetFTPResponse(&nread, conn, &ftpcode);
-
- if(ftpcode/100 > 3)
- return CURLE_FTP_ACCEPT_FAILED;
-
+
+ if(ftpcode/100 > 3)
+ return CURLE_FTP_ACCEPT_FAILED;
+
return CURLE_WEIRD_SERVER_REPLY;
- }
-
- break;
- } /* switch() */
-
- return CURLE_OK;
-}
-
-
-/***********************************************************************
- *
- * InitiateTransfer()
- *
- * After connection from server is accepted this function is called to
- * setup transfer parameters and initiate the data transfer.
- *
- */
-static CURLcode InitiateTransfer(struct connectdata *conn)
-{
+ }
+
+ break;
+ } /* switch() */
+
+ return CURLE_OK;
+}
+
+
+/***********************************************************************
+ *
+ * InitiateTransfer()
+ *
+ * After connection from server is accepted this function is called to
+ * setup transfer parameters and initiate the data transfer.
+ *
+ */
+static CURLcode InitiateTransfer(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- CURLcode result = CURLE_OK;
-
+ CURLcode result = CURLE_OK;
+
if(conn->bits.ftp_use_data_ssl) {
- /* since we only have a plaintext TCP connection here, we must now
- * do the TLS stuff */
- infof(data, "Doing the SSL/TLS handshake on the data stream\n");
- result = Curl_ssl_connect(conn, SECONDARYSOCKET);
- if(result)
- return result;
- }
-
- if(conn->proto.ftpc.state_saved == FTP_STOR) {
- /* When we know we're uploading a specified file, we can get the file
- size prior to the actual upload. */
+ /* since we only have a plaintext TCP connection here, we must now
+ * do the TLS stuff */
+ infof(data, "Doing the SSL/TLS handshake on the data stream\n");
+ result = Curl_ssl_connect(conn, SECONDARYSOCKET);
+ if(result)
+ return result;
+ }
+
+ if(conn->proto.ftpc.state_saved == FTP_STOR) {
+ /* When we know we're uploading a specified file, we can get the file
+ size prior to the actual upload. */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
-
- /* set the SO_SNDBUF for the secondary socket for those who need it */
- Curl_sndbufset(conn->sock[SECONDARYSOCKET]);
-
+
+ /* set the SO_SNDBUF for the secondary socket for those who need it */
+ Curl_sndbufset(conn->sock[SECONDARYSOCKET]);
+
Curl_setup_transfer(data, -1, -1, FALSE, SECONDARYSOCKET);
- }
- else {
- /* FTP download: */
+ }
+ else {
+ /* FTP download: */
Curl_setup_transfer(data, SECONDARYSOCKET,
conn->proto.ftpc.retr_size_saved, FALSE, -1);
- }
-
- conn->proto.ftpc.pp.pending_resp = TRUE; /* expect server response */
- state(conn, FTP_STOP);
-
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * AllowServerConnect()
- *
- * When we've issue the PORT command, we have told the server to connect to
- * us. This function checks whether data connection is established if so it is
- * accepted.
- *
- */
-static CURLcode AllowServerConnect(struct connectdata *conn, bool *connected)
-{
+ }
+
+ conn->proto.ftpc.pp.pending_resp = TRUE; /* expect server response */
+ state(conn, FTP_STOP);
+
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * AllowServerConnect()
+ *
+ * When we've issue the PORT command, we have told the server to connect to
+ * us. This function checks whether data connection is established if so it is
+ * accepted.
+ *
+ */
+static CURLcode AllowServerConnect(struct connectdata *conn, bool *connected)
+{
struct Curl_easy *data = conn->data;
timediff_t timeout_ms;
CURLcode result = CURLE_OK;
-
- *connected = FALSE;
- infof(data, "Preparing for accepting server on data port\n");
-
- /* Save the time we start accepting server connect */
- Curl_pgrsTime(data, TIMER_STARTACCEPT);
-
- timeout_ms = ftp_timeleft_accept(data);
- if(timeout_ms < 0) {
- /* if a timeout was already reached, bail out */
- failf(data, "Accept timeout occurred while waiting server connect");
- return CURLE_FTP_ACCEPT_TIMEOUT;
- }
-
- /* see if the connection request is already here */
+
+ *connected = FALSE;
+ infof(data, "Preparing for accepting server on data port\n");
+
+ /* Save the time we start accepting server connect */
+ Curl_pgrsTime(data, TIMER_STARTACCEPT);
+
+ timeout_ms = ftp_timeleft_accept(data);
+ if(timeout_ms < 0) {
+ /* if a timeout was already reached, bail out */
+ failf(data, "Accept timeout occurred while waiting server connect");
+ return CURLE_FTP_ACCEPT_TIMEOUT;
+ }
+
+ /* see if the connection request is already here */
result = ReceivedServerConnect(conn, connected);
if(result)
return result;
-
- if(*connected) {
+
+ if(*connected) {
result = AcceptServerConnect(conn);
if(result)
return result;
-
+
result = InitiateTransfer(conn);
if(result)
return result;
- }
- else {
- /* Add timeout to multi handle and break out of the loop */
+ }
+ else {
+ /* Add timeout to multi handle and break out of the loop */
if(*connected == FALSE) {
Curl_expire(data, data->set.accepttimeout > 0 ?
data->set.accepttimeout: DEFAULT_ACCEPT_TIMEOUT, 0);
- }
- }
-
+ }
+ }
+
return result;
-}
-
-/* macro to check for a three-digit ftp status code at the start of the
- given string */
-#define STATUSCODE(line) (ISDIGIT(line[0]) && ISDIGIT(line[1]) && \
- ISDIGIT(line[2]))
-
-/* macro to check for the last line in an FTP server response */
-#define LASTLINE(line) (STATUSCODE(line) && (' ' == line[3]))
-
-static bool ftp_endofresp(struct connectdata *conn, char *line, size_t len,
- int *code)
-{
- (void)conn;
-
- if((len > 3) && LASTLINE(line)) {
- *code = curlx_sltosi(strtol(line, NULL, 10));
- return TRUE;
- }
-
- return FALSE;
-}
-
-static CURLcode ftp_readresp(curl_socket_t sockfd,
- struct pingpong *pp,
- int *ftpcode, /* return the ftp-code if done */
- size_t *size) /* size of the response */
-{
- struct connectdata *conn = pp->conn;
+}
+
+/* macro to check for a three-digit ftp status code at the start of the
+ given string */
+#define STATUSCODE(line) (ISDIGIT(line[0]) && ISDIGIT(line[1]) && \
+ ISDIGIT(line[2]))
+
+/* macro to check for the last line in an FTP server response */
+#define LASTLINE(line) (STATUSCODE(line) && (' ' == line[3]))
+
+static bool ftp_endofresp(struct connectdata *conn, char *line, size_t len,
+ int *code)
+{
+ (void)conn;
+
+ if((len > 3) && LASTLINE(line)) {
+ *code = curlx_sltosi(strtol(line, NULL, 10));
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+static CURLcode ftp_readresp(curl_socket_t sockfd,
+ struct pingpong *pp,
+ int *ftpcode, /* return the ftp-code if done */
+ size_t *size) /* size of the response */
+{
+ struct connectdata *conn = pp->conn;
struct Curl_easy *data = conn->data;
-#ifdef HAVE_GSSAPI
- char * const buf = data->state.buffer;
-#endif
- int code;
+#ifdef HAVE_GSSAPI
+ char * const buf = data->state.buffer;
+#endif
+ int code;
CURLcode result = Curl_pp_readresp(sockfd, pp, &code, size);
-
-#if defined(HAVE_GSSAPI)
- /* handle the security-oriented responses 6xx ***/
- switch(code) {
- case 631:
- code = Curl_sec_read_msg(conn, buf, PROT_SAFE);
- break;
- case 632:
- code = Curl_sec_read_msg(conn, buf, PROT_PRIVATE);
- break;
- case 633:
- code = Curl_sec_read_msg(conn, buf, PROT_CONFIDENTIAL);
- break;
- default:
- /* normal ftp stuff we pass through! */
- break;
- }
-#endif
-
- /* store the latest code for later retrieval */
+
+#if defined(HAVE_GSSAPI)
+ /* handle the security-oriented responses 6xx ***/
+ switch(code) {
+ case 631:
+ code = Curl_sec_read_msg(conn, buf, PROT_SAFE);
+ break;
+ case 632:
+ code = Curl_sec_read_msg(conn, buf, PROT_PRIVATE);
+ break;
+ case 633:
+ code = Curl_sec_read_msg(conn, buf, PROT_CONFIDENTIAL);
+ break;
+ default:
+ /* normal ftp stuff we pass through! */
+ break;
+ }
+#endif
+
+ /* store the latest code for later retrieval */
data->info.httpcode = code;
-
- if(ftpcode)
- *ftpcode = code;
-
- if(421 == code) {
- /* 421 means "Service not available, closing control connection." and FTP
- * servers use it to signal that idle session timeout has been exceeded.
- * If we ignored the response, it could end up hanging in some cases.
- *
- * This response code can come at any point so having it treated
- * generically is a good idea.
- */
- infof(data, "We got a 421 - timeout!\n");
- state(conn, FTP_STOP);
- return CURLE_OPERATION_TIMEDOUT;
- }
-
- return result;
-}
-
-/* --- parse FTP server responses --- */
-
-/*
- * Curl_GetFTPResponse() is a BLOCKING function to read the full response
- * from a server after a command.
- *
- */
-
-CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
- struct connectdata *conn,
- int *ftpcode) /* return the ftp-code */
-{
- /*
- * We cannot read just one byte per read() and then go back to select() as
- * the OpenSSL read() doesn't grok that properly.
- *
- * Alas, read as much as possible, split up into lines, use the ending
- * line in a response or continue reading. */
-
- curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
+
+ if(ftpcode)
+ *ftpcode = code;
+
+ if(421 == code) {
+ /* 421 means "Service not available, closing control connection." and FTP
+ * servers use it to signal that idle session timeout has been exceeded.
+ * If we ignored the response, it could end up hanging in some cases.
+ *
+ * This response code can come at any point so having it treated
+ * generically is a good idea.
+ */
+ infof(data, "We got a 421 - timeout!\n");
+ state(conn, FTP_STOP);
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ return result;
+}
+
+/* --- parse FTP server responses --- */
+
+/*
+ * Curl_GetFTPResponse() is a BLOCKING function to read the full response
+ * from a server after a command.
+ *
+ */
+
+CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
+ struct connectdata *conn,
+ int *ftpcode) /* return the ftp-code */
+{
+ /*
+ * We cannot read just one byte per read() and then go back to select() as
+ * the OpenSSL read() doesn't grok that properly.
+ *
+ * Alas, read as much as possible, split up into lines, use the ending
+ * line in a response or continue reading. */
+
+ curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
struct Curl_easy *data = conn->data;
- CURLcode result = CURLE_OK;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
- size_t nread;
+ CURLcode result = CURLE_OK;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+ size_t nread;
int cache_skip = 0;
int value_to_be_ignored = 0;
-
- if(ftpcode)
- *ftpcode = 0; /* 0 for errors */
- else
- /* make the pointer point to something for the rest of this function */
- ftpcode = &value_to_be_ignored;
-
+
+ if(ftpcode)
+ *ftpcode = 0; /* 0 for errors */
+ else
+ /* make the pointer point to something for the rest of this function */
+ ftpcode = &value_to_be_ignored;
+
*nreadp = 0;
-
- while(!*ftpcode && !result) {
- /* check and reset timeout value every lap */
+
+ while(!*ftpcode && !result) {
+ /* check and reset timeout value every lap */
timediff_t timeout = Curl_pp_state_timeout(pp, FALSE);
timediff_t interval_ms;
-
+
if(timeout <= 0) {
- failf(data, "FTP response timeout");
- return CURLE_OPERATION_TIMEDOUT; /* already too little time */
- }
-
- interval_ms = 1000; /* use 1 second timeout intervals */
- if(timeout < interval_ms)
- interval_ms = timeout;
-
- /*
- * Since this function is blocking, we need to wait here for input on the
- * connection and only then we call the response reading function. We do
- * timeout at least every second to make the timeout check run.
- *
- * A caution here is that the ftp_readresp() function has a cache that may
- * contain pieces of a response from the previous invoke and we need to
- * make sure we don't just wait for input while there is unhandled data in
- * that cache. But also, if the cache is there, we call ftp_readresp() and
- * the cache wasn't good enough to continue we must not just busy-loop
- * around this function.
- *
- */
-
- if(pp->cache && (cache_skip < 2)) {
- /*
- * There's a cache left since before. We then skipping the wait for
- * socket action, unless this is the same cache like the previous round
- * as then the cache was deemed not enough to act on and we then need to
- * wait for more data anyway.
- */
- }
+ failf(data, "FTP response timeout");
+ return CURLE_OPERATION_TIMEDOUT; /* already too little time */
+ }
+
+ interval_ms = 1000; /* use 1 second timeout intervals */
+ if(timeout < interval_ms)
+ interval_ms = timeout;
+
+ /*
+ * Since this function is blocking, we need to wait here for input on the
+ * connection and only then we call the response reading function. We do
+ * timeout at least every second to make the timeout check run.
+ *
+ * A caution here is that the ftp_readresp() function has a cache that may
+ * contain pieces of a response from the previous invoke and we need to
+ * make sure we don't just wait for input while there is unhandled data in
+ * that cache. But also, if the cache is there, we call ftp_readresp() and
+ * the cache wasn't good enough to continue we must not just busy-loop
+ * around this function.
+ *
+ */
+
+ if(pp->cache && (cache_skip < 2)) {
+ /*
+ * There's a cache left since before. We then skipping the wait for
+ * socket action, unless this is the same cache like the previous round
+ * as then the cache was deemed not enough to act on and we then need to
+ * wait for more data anyway.
+ */
+ }
else if(!Curl_conn_data_pending(conn, FIRSTSOCKET)) {
switch(SOCKET_READABLE(sockfd, interval_ms)) {
- case -1: /* select() error, stop reading */
- failf(data, "FTP response aborted due to select/poll error: %d",
- SOCKERRNO);
- return CURLE_RECV_ERROR;
-
- case 0: /* timeout */
- if(Curl_pgrsUpdate(conn))
- return CURLE_ABORTED_BY_CALLBACK;
- continue; /* just continue in our loop for the timeout duration */
-
- default: /* for clarity */
- break;
- }
- }
- result = ftp_readresp(sockfd, pp, ftpcode, &nread);
- if(result)
- break;
-
- if(!nread && pp->cache)
- /* bump cache skip counter as on repeated skips we must wait for more
- data */
- cache_skip++;
- else
- /* when we got data or there is no cache left, we reset the cache skip
- counter */
+ case -1: /* select() error, stop reading */
+ failf(data, "FTP response aborted due to select/poll error: %d",
+ SOCKERRNO);
+ return CURLE_RECV_ERROR;
+
+ case 0: /* timeout */
+ if(Curl_pgrsUpdate(conn))
+ return CURLE_ABORTED_BY_CALLBACK;
+ continue; /* just continue in our loop for the timeout duration */
+
+ default: /* for clarity */
+ break;
+ }
+ }
+ result = ftp_readresp(sockfd, pp, ftpcode, &nread);
+ if(result)
+ break;
+
+ if(!nread && pp->cache)
+ /* bump cache skip counter as on repeated skips we must wait for more
+ data */
+ cache_skip++;
+ else
+ /* when we got data or there is no cache left, we reset the cache skip
+ counter */
cache_skip = 0;
-
- *nreadp += nread;
-
- } /* while there's buffer left and loop is requested */
-
- pp->pending_resp = FALSE;
-
- return result;
-}
-
-#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
- /* for debug purposes */
-static const char * const ftp_state_names[]={
- "STOP",
- "WAIT220",
- "AUTH",
- "USER",
- "PASS",
- "ACCT",
- "PBSZ",
- "PROT",
- "CCC",
- "PWD",
- "SYST",
- "NAMEFMT",
- "QUOTE",
- "RETR_PREQUOTE",
- "STOR_PREQUOTE",
- "POSTQUOTE",
- "CWD",
- "MKD",
- "MDTM",
- "TYPE",
- "LIST_TYPE",
- "RETR_TYPE",
- "STOR_TYPE",
- "SIZE",
- "RETR_SIZE",
- "STOR_SIZE",
- "REST",
- "RETR_REST",
- "PORT",
- "PRET",
- "PASV",
- "LIST",
- "RETR",
- "STOR",
- "QUIT"
-};
-#endif
-
-/* This is the ONLY way to change FTP state! */
-static void _state(struct connectdata *conn,
- ftpstate newstate
-#ifdef DEBUGBUILD
- , int lineno
-#endif
- )
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ *nreadp += nread;
+
+ } /* while there's buffer left and loop is requested */
+
+ pp->pending_resp = FALSE;
+
+ return result;
+}
+
+#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
+ /* for debug purposes */
+static const char * const ftp_state_names[]={
+ "STOP",
+ "WAIT220",
+ "AUTH",
+ "USER",
+ "PASS",
+ "ACCT",
+ "PBSZ",
+ "PROT",
+ "CCC",
+ "PWD",
+ "SYST",
+ "NAMEFMT",
+ "QUOTE",
+ "RETR_PREQUOTE",
+ "STOR_PREQUOTE",
+ "POSTQUOTE",
+ "CWD",
+ "MKD",
+ "MDTM",
+ "TYPE",
+ "LIST_TYPE",
+ "RETR_TYPE",
+ "STOR_TYPE",
+ "SIZE",
+ "RETR_SIZE",
+ "STOR_SIZE",
+ "REST",
+ "RETR_REST",
+ "PORT",
+ "PRET",
+ "PASV",
+ "LIST",
+ "RETR",
+ "STOR",
+ "QUIT"
+};
+#endif
+
+/* This is the ONLY way to change FTP state! */
+static void _state(struct connectdata *conn,
+ ftpstate newstate
+#ifdef DEBUGBUILD
+ , int lineno
+#endif
+ )
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
#if defined(DEBUGBUILD)
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) lineno;
#else
- if(ftpc->state != newstate)
- infof(conn->data, "FTP %p (line %d) state change from %s to %s\n",
- (void *)ftpc, lineno, ftp_state_names[ftpc->state],
- ftp_state_names[newstate]);
-#endif
+ if(ftpc->state != newstate)
+ infof(conn->data, "FTP %p (line %d) state change from %s to %s\n",
+ (void *)ftpc, lineno, ftp_state_names[ftpc->state],
+ ftp_state_names[newstate]);
+#endif
#endif
- ftpc->state = newstate;
-}
-
-static CURLcode ftp_state_user(struct connectdata *conn)
-{
+ ftpc->state = newstate;
+}
+
+static CURLcode ftp_state_user(struct connectdata *conn)
+{
CURLcode result = Curl_pp_sendf(&conn->proto.ftpc.pp, "USER %s",
conn->user?conn->user:"");
if(!result) {
@@ -774,45 +774,45 @@ static CURLcode ftp_state_user(struct connectdata *conn)
conn->data->state.ftp_trying_alternative = FALSE;
}
return result;
-}
-
-static CURLcode ftp_state_pwd(struct connectdata *conn)
-{
+}
+
+static CURLcode ftp_state_pwd(struct connectdata *conn)
+{
CURLcode result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", "PWD");
if(!result)
state(conn, FTP_PWD);
-
+
return result;
-}
-
-/* For the FTP "protocol connect" and "doing" phases only */
-static int ftp_getsock(struct connectdata *conn,
+}
+
+/* For the FTP "protocol connect" and "doing" phases only */
+static int ftp_getsock(struct connectdata *conn,
curl_socket_t *socks)
-{
+{
return Curl_pp_getsock(&conn->proto.ftpc.pp, socks);
-}
-
-/* For the FTP "DO_MORE" phase only */
+}
+
+/* For the FTP "DO_MORE" phase only */
static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks)
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- /* When in DO_MORE state, we could be either waiting for us to connect to a
- * remote site, or we could wait for that site to connect to us. Or just
- * handle ordinary commands.
- */
-
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ /* When in DO_MORE state, we could be either waiting for us to connect to a
+ * remote site, or we could wait for that site to connect to us. Or just
+ * handle ordinary commands.
+ */
+
if(SOCKS_STATE(conn->cnnct.state))
return Curl_SOCKS_getsock(conn, socks, SECONDARYSOCKET);
- if(FTP_STOP == ftpc->state) {
+ if(FTP_STOP == ftpc->state) {
int bits = GETSOCK_READSOCK(0);
bool any = FALSE;
- /* if stopped and still in this state, then we're also waiting for a
- connect on the secondary connection */
- socks[0] = conn->sock[FIRSTSOCKET];
-
+ /* if stopped and still in this state, then we're also waiting for a
+ connect on the secondary connection */
+ socks[0] = conn->sock[FIRSTSOCKET];
+
if(!conn->data->set.ftp_use_port) {
int s;
int i;
@@ -832,147 +832,147 @@ static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks)
}
return bits;
- }
+ }
return Curl_pp_getsock(&conn->proto.ftpc.pp, socks);
-}
-
-/* This is called after the FTP_QUOTE state is passed.
-
- ftp_state_cwd() sends the range of CWD commands to the server to change to
- the correct directory. It may also need to send MKD commands to create
- missing ones, if that option is enabled.
-*/
-static CURLcode ftp_state_cwd(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- if(ftpc->cwddone)
- /* already done and fine */
- result = ftp_state_mdtm(conn);
- else {
+}
+
+/* This is called after the FTP_QUOTE state is passed.
+
+ ftp_state_cwd() sends the range of CWD commands to the server to change to
+ the correct directory. It may also need to send MKD commands to create
+ missing ones, if that option is enabled.
+*/
+static CURLcode ftp_state_cwd(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ if(ftpc->cwddone)
+ /* already done and fine */
+ result = ftp_state_mdtm(conn);
+ else {
/* FTPFILE_NOCWD with full path: expect ftpc->cwddone! */
DEBUGASSERT((conn->data->set.ftp_filemethod != FTPFILE_NOCWD) ||
!(ftpc->dirdepth && ftpc->dirs[0][0] == '/'));
- ftpc->count2 = 0; /* count2 counts failed CWDs */
-
- /* count3 is set to allow a MKD to fail once. In the case when first CWD
- fails and then MKD fails (due to another session raced it to create the
- dir) this then allows for a second try to CWD to it */
+ ftpc->count2 = 0; /* count2 counts failed CWDs */
+
+ /* count3 is set to allow a MKD to fail once. In the case when first CWD
+ fails and then MKD fails (due to another session raced it to create the
+ dir) this then allows for a second try to CWD to it */
ftpc->count3 = (conn->data->set.ftp_create_missing_dirs == 2)?1:0;
-
+
if(conn->bits.reuse && ftpc->entrypath &&
/* no need to go to entrypath when we have an absolute path */
!(ftpc->dirdepth && ftpc->dirs[0][0] == '/')) {
- /* This is a re-used connection. Since we change directory to where the
- transfer is taking place, we must first get back to the original dir
- where we ended up after login: */
+ /* This is a re-used connection. Since we change directory to where the
+ transfer is taking place, we must first get back to the original dir
+ where we ended up after login: */
ftpc->cwdcount = 0; /* we count this as the first path, then we add one
for all upcoming ones in the ftp->dirs[] array */
result = Curl_pp_sendf(&ftpc->pp, "CWD %s", ftpc->entrypath);
if(!result)
state(conn, FTP_CWD);
- }
- else {
- if(ftpc->dirdepth) {
+ }
+ else {
+ if(ftpc->dirdepth) {
ftpc->cwdcount = 1;
- /* issue the first CWD, the rest is sent when the CWD responses are
- received... */
+ /* issue the first CWD, the rest is sent when the CWD responses are
+ received... */
result = Curl_pp_sendf(&ftpc->pp, "CWD %s",
ftpc->dirs[ftpc->cwdcount -1]);
if(!result)
state(conn, FTP_CWD);
- }
- else {
- /* No CWD necessary */
- result = ftp_state_mdtm(conn);
- }
- }
- }
- return result;
-}
-
-typedef enum {
- EPRT,
- PORT,
- DONE
-} ftpport;
-
-static CURLcode ftp_state_use_port(struct connectdata *conn,
- ftpport fcmd) /* start with this */
-{
- CURLcode result = CURLE_OK;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
+ }
+ else {
+ /* No CWD necessary */
+ result = ftp_state_mdtm(conn);
+ }
+ }
+ }
+ return result;
+}
+
+typedef enum {
+ EPRT,
+ PORT,
+ DONE
+} ftpport;
+
+static CURLcode ftp_state_use_port(struct connectdata *conn,
+ ftpport fcmd) /* start with this */
+{
+ CURLcode result = CURLE_OK;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
struct Curl_easy *data = conn->data;
curl_socket_t portsock = CURL_SOCKET_BAD;
char myhost[MAX_IPADR_LEN + 1] = "";
-
- struct Curl_sockaddr_storage ss;
+
+ struct Curl_sockaddr_storage ss;
struct Curl_addrinfo *res, *ai;
- curl_socklen_t sslen;
- char hbuf[NI_MAXHOST];
+ curl_socklen_t sslen;
+ char hbuf[NI_MAXHOST];
struct sockaddr *sa = (struct sockaddr *)&ss;
- struct sockaddr_in * const sa4 = (void *)sa;
-#ifdef ENABLE_IPV6
- struct sockaddr_in6 * const sa6 = (void *)sa;
-#endif
- static const char mode[][5] = { "EPRT", "PORT" };
+ struct sockaddr_in * const sa4 = (void *)sa;
+#ifdef ENABLE_IPV6
+ struct sockaddr_in6 * const sa6 = (void *)sa;
+#endif
+ static const char mode[][5] = { "EPRT", "PORT" };
enum resolve_t rc;
- int error;
- char *host = NULL;
- char *string_ftpport = data->set.str[STRING_FTPPORT];
+ int error;
+ char *host = NULL;
+ char *string_ftpport = data->set.str[STRING_FTPPORT];
struct Curl_dns_entry *h = NULL;
- unsigned short port_min = 0;
- unsigned short port_max = 0;
- unsigned short port;
- bool possibly_non_local = TRUE;
+ unsigned short port_min = 0;
+ unsigned short port_max = 0;
+ unsigned short port;
+ bool possibly_non_local = TRUE;
char buffer[STRERROR_LEN];
- char *addr = NULL;
-
- /* Step 1, figure out what is requested,
- * accepted format :
- * (ipv4|ipv6|domain|interface)?(:port(-range)?)?
- */
-
- if(data->set.str[STRING_FTPPORT] &&
- (strlen(data->set.str[STRING_FTPPORT]) > 1)) {
-
-#ifdef ENABLE_IPV6
- size_t addrlen = INET6_ADDRSTRLEN > strlen(string_ftpport) ?
- INET6_ADDRSTRLEN : strlen(string_ftpport);
-#else
- size_t addrlen = INET_ADDRSTRLEN > strlen(string_ftpport) ?
- INET_ADDRSTRLEN : strlen(string_ftpport);
-#endif
- char *ip_start = string_ftpport;
- char *ip_end = NULL;
- char *port_start = NULL;
- char *port_sep = NULL;
-
+ char *addr = NULL;
+
+ /* Step 1, figure out what is requested,
+ * accepted format :
+ * (ipv4|ipv6|domain|interface)?(:port(-range)?)?
+ */
+
+ if(data->set.str[STRING_FTPPORT] &&
+ (strlen(data->set.str[STRING_FTPPORT]) > 1)) {
+
+#ifdef ENABLE_IPV6
+ size_t addrlen = INET6_ADDRSTRLEN > strlen(string_ftpport) ?
+ INET6_ADDRSTRLEN : strlen(string_ftpport);
+#else
+ size_t addrlen = INET_ADDRSTRLEN > strlen(string_ftpport) ?
+ INET_ADDRSTRLEN : strlen(string_ftpport);
+#endif
+ char *ip_start = string_ftpport;
+ char *ip_end = NULL;
+ char *port_start = NULL;
+ char *port_sep = NULL;
+
addr = calloc(addrlen + 1, 1);
- if(!addr)
- return CURLE_OUT_OF_MEMORY;
-
-#ifdef ENABLE_IPV6
- if(*string_ftpport == '[') {
- /* [ipv6]:port(-range) */
- ip_start = string_ftpport + 1;
+ if(!addr)
+ return CURLE_OUT_OF_MEMORY;
+
+#ifdef ENABLE_IPV6
+ if(*string_ftpport == '[') {
+ /* [ipv6]:port(-range) */
+ ip_start = string_ftpport + 1;
ip_end = strchr(string_ftpport, ']');
if(ip_end)
- strncpy(addr, ip_start, ip_end - ip_start);
- }
- else
-#endif
- if(*string_ftpport == ':') {
- /* :port */
- ip_end = string_ftpport;
+ strncpy(addr, ip_start, ip_end - ip_start);
+ }
+ else
+#endif
+ if(*string_ftpport == ':') {
+ /* :port */
+ ip_end = string_ftpport;
}
else {
ip_end = strchr(string_ftpport, ':');
if(ip_end) {
/* either ipv6 or (ipv4|domain|interface):port(-range) */
-#ifdef ENABLE_IPV6
+#ifdef ENABLE_IPV6
if(Curl_inet_pton(AF_INET6, string_ftpport, sa6) == 1) {
/* ipv6 */
port_min = port_max = 0;
@@ -987,374 +987,374 @@ static CURLcode ftp_state_use_port(struct connectdata *conn,
else
/* ipv4|interface */
strcpy(addr, string_ftpport);
- }
-
- /* parse the port */
- if(ip_end != NULL) {
+ }
+
+ /* parse the port */
+ if(ip_end != NULL) {
port_start = strchr(ip_end, ':');
if(port_start) {
port_min = curlx_ultous(strtoul(port_start + 1, NULL, 10));
port_sep = strchr(port_start, '-');
if(port_sep) {
- port_max = curlx_ultous(strtoul(port_sep + 1, NULL, 10));
- }
- else
- port_max = port_min;
- }
- }
-
- /* correct errors like:
- * :1234-1230
+ port_max = curlx_ultous(strtoul(port_sep + 1, NULL, 10));
+ }
+ else
+ port_max = port_min;
+ }
+ }
+
+ /* correct errors like:
+ * :1234-1230
* :-4711, in this case port_min is (unsigned)-1,
- * therefore port_min > port_max for all cases
- * but port_max = (unsigned)-1
- */
+ * therefore port_min > port_max for all cases
+ * but port_max = (unsigned)-1
+ */
if(port_min > port_max)
- port_min = port_max = 0;
-
-
- if(*addr != '\0') {
- /* attempt to get the address of the given interface name */
+ port_min = port_max = 0;
+
+
+ if(*addr != '\0') {
+ /* attempt to get the address of the given interface name */
switch(Curl_if2ip(conn->ip_addr->ai_family,
Curl_ipv6_scope(conn->ip_addr->ai_addr),
conn->scope_id, addr, hbuf, sizeof(hbuf))) {
- case IF2IP_NOT_FOUND:
- /* not an interface, use the given string as host name instead */
- host = addr;
- break;
- case IF2IP_AF_NOT_SUPPORTED:
- return CURLE_FTP_PORT_FAILED;
- case IF2IP_FOUND:
- host = hbuf; /* use the hbuf for host name */
- }
- }
- else
- /* there was only a port(-range) given, default the host */
- host = NULL;
- } /* data->set.ftpport */
-
- if(!host) {
+ case IF2IP_NOT_FOUND:
+ /* not an interface, use the given string as host name instead */
+ host = addr;
+ break;
+ case IF2IP_AF_NOT_SUPPORTED:
+ return CURLE_FTP_PORT_FAILED;
+ case IF2IP_FOUND:
+ host = hbuf; /* use the hbuf for host name */
+ }
+ }
+ else
+ /* there was only a port(-range) given, default the host */
+ host = NULL;
+ } /* data->set.ftpport */
+
+ if(!host) {
const char *r;
- /* not an interface and not a host name, get default by extracting
- the IP from the control connection */
- sslen = sizeof(ss);
- if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) {
- failf(data, "getsockname() failed: %s",
+ /* not an interface and not a host name, get default by extracting
+ the IP from the control connection */
+ sslen = sizeof(ss);
+ if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) {
+ failf(data, "getsockname() failed: %s",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
free(addr);
- return CURLE_FTP_PORT_FAILED;
- }
- switch(sa->sa_family) {
-#ifdef ENABLE_IPV6
- case AF_INET6:
+ return CURLE_FTP_PORT_FAILED;
+ }
+ switch(sa->sa_family) {
+#ifdef ENABLE_IPV6
+ case AF_INET6:
r = Curl_inet_ntop(sa->sa_family, &sa6->sin6_addr, hbuf, sizeof(hbuf));
- break;
-#endif
- default:
+ break;
+#endif
+ default:
r = Curl_inet_ntop(sa->sa_family, &sa4->sin_addr, hbuf, sizeof(hbuf));
- break;
- }
+ break;
+ }
if(!r)
return CURLE_FTP_PORT_FAILED;
- host = hbuf; /* use this host name */
- possibly_non_local = FALSE; /* we know it is local now */
- }
-
- /* resolv ip/host to ip */
+ host = hbuf; /* use this host name */
+ possibly_non_local = FALSE; /* we know it is local now */
+ }
+
+ /* resolv ip/host to ip */
rc = Curl_resolv(conn, host, 0, FALSE, &h);
- if(rc == CURLRESOLV_PENDING)
- (void)Curl_resolver_wait_resolv(conn, &h);
- if(h) {
- res = h->addr;
- /* when we return from this function, we can forget about this entry
- to we can unlock it now already */
- Curl_resolv_unlock(data, h);
- } /* (h) */
- else
- res = NULL; /* failure! */
-
- if(res == NULL) {
- failf(data, "failed to resolve the address provided to PORT: %s", host);
+ if(rc == CURLRESOLV_PENDING)
+ (void)Curl_resolver_wait_resolv(conn, &h);
+ if(h) {
+ res = h->addr;
+ /* when we return from this function, we can forget about this entry
+ to we can unlock it now already */
+ Curl_resolv_unlock(data, h);
+ } /* (h) */
+ else
+ res = NULL; /* failure! */
+
+ if(res == NULL) {
+ failf(data, "failed to resolve the address provided to PORT: %s", host);
free(addr);
- return CURLE_FTP_PORT_FAILED;
- }
-
+ return CURLE_FTP_PORT_FAILED;
+ }
+
free(addr);
- host = NULL;
-
- /* step 2, create a socket for the requested address */
-
- portsock = CURL_SOCKET_BAD;
- error = 0;
- for(ai = res; ai; ai = ai->ai_next) {
- result = Curl_socket(conn, ai, NULL, &portsock);
- if(result) {
- error = SOCKERRNO;
- continue;
- }
- break;
- }
- if(!ai) {
+ host = NULL;
+
+ /* step 2, create a socket for the requested address */
+
+ portsock = CURL_SOCKET_BAD;
+ error = 0;
+ for(ai = res; ai; ai = ai->ai_next) {
+ result = Curl_socket(conn, ai, NULL, &portsock);
+ if(result) {
+ error = SOCKERRNO;
+ continue;
+ }
+ break;
+ }
+ if(!ai) {
failf(data, "socket failure: %s",
Curl_strerror(error, buffer, sizeof(buffer)));
- return CURLE_FTP_PORT_FAILED;
- }
-
- /* step 3, bind to a suitable local address */
-
- memcpy(sa, ai->ai_addr, ai->ai_addrlen);
- sslen = ai->ai_addrlen;
-
- for(port = port_min; port <= port_max;) {
- if(sa->sa_family == AF_INET)
- sa4->sin_port = htons(port);
-#ifdef ENABLE_IPV6
- else
- sa6->sin6_port = htons(port);
-#endif
- /* Try binding the given address. */
- if(bind(portsock, sa, sslen) ) {
- /* It failed. */
- error = SOCKERRNO;
- if(possibly_non_local && (error == EADDRNOTAVAIL)) {
- /* The requested bind address is not local. Use the address used for
- * the control connection instead and restart the port loop
- */
- infof(data, "bind(port=%hu) on non-local address failed: %s\n", port,
+ return CURLE_FTP_PORT_FAILED;
+ }
+
+ /* step 3, bind to a suitable local address */
+
+ memcpy(sa, ai->ai_addr, ai->ai_addrlen);
+ sslen = ai->ai_addrlen;
+
+ for(port = port_min; port <= port_max;) {
+ if(sa->sa_family == AF_INET)
+ sa4->sin_port = htons(port);
+#ifdef ENABLE_IPV6
+ else
+ sa6->sin6_port = htons(port);
+#endif
+ /* Try binding the given address. */
+ if(bind(portsock, sa, sslen) ) {
+ /* It failed. */
+ error = SOCKERRNO;
+ if(possibly_non_local && (error == EADDRNOTAVAIL)) {
+ /* The requested bind address is not local. Use the address used for
+ * the control connection instead and restart the port loop
+ */
+ infof(data, "bind(port=%hu) on non-local address failed: %s\n", port,
Curl_strerror(error, buffer, sizeof(buffer)));
-
- sslen = sizeof(ss);
- if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) {
- failf(data, "getsockname() failed: %s",
+
+ sslen = sizeof(ss);
+ if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) {
+ failf(data, "getsockname() failed: %s",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- Curl_closesocket(conn, portsock);
- return CURLE_FTP_PORT_FAILED;
- }
- port = port_min;
- possibly_non_local = FALSE; /* don't try this again */
- continue;
- }
+ Curl_closesocket(conn, portsock);
+ return CURLE_FTP_PORT_FAILED;
+ }
+ port = port_min;
+ possibly_non_local = FALSE; /* don't try this again */
+ continue;
+ }
if(error != EADDRINUSE && error != EACCES) {
- failf(data, "bind(port=%hu) failed: %s", port,
+ failf(data, "bind(port=%hu) failed: %s", port,
Curl_strerror(error, buffer, sizeof(buffer)));
- Curl_closesocket(conn, portsock);
- return CURLE_FTP_PORT_FAILED;
- }
- }
- else
- break;
-
- port++;
- }
-
- /* maybe all ports were in use already*/
- if(port > port_max) {
- failf(data, "bind() failed, we ran out of ports!");
- Curl_closesocket(conn, portsock);
- return CURLE_FTP_PORT_FAILED;
- }
-
- /* get the name again after the bind() so that we can extract the
- port number it uses now */
- sslen = sizeof(ss);
- if(getsockname(portsock, (struct sockaddr *)sa, &sslen)) {
- failf(data, "getsockname() failed: %s",
+ Curl_closesocket(conn, portsock);
+ return CURLE_FTP_PORT_FAILED;
+ }
+ }
+ else
+ break;
+
+ port++;
+ }
+
+ /* maybe all ports were in use already*/
+ if(port > port_max) {
+ failf(data, "bind() failed, we ran out of ports!");
+ Curl_closesocket(conn, portsock);
+ return CURLE_FTP_PORT_FAILED;
+ }
+
+ /* get the name again after the bind() so that we can extract the
+ port number it uses now */
+ sslen = sizeof(ss);
+ if(getsockname(portsock, (struct sockaddr *)sa, &sslen)) {
+ failf(data, "getsockname() failed: %s",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- Curl_closesocket(conn, portsock);
- return CURLE_FTP_PORT_FAILED;
- }
-
- /* step 4, listen on the socket */
-
- if(listen(portsock, 1)) {
+ Curl_closesocket(conn, portsock);
+ return CURLE_FTP_PORT_FAILED;
+ }
+
+ /* step 4, listen on the socket */
+
+ if(listen(portsock, 1)) {
failf(data, "socket failure: %s",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- Curl_closesocket(conn, portsock);
- return CURLE_FTP_PORT_FAILED;
- }
-
- /* step 5, send the proper FTP command */
-
- /* get a plain printable version of the numerical address to work with
- below */
- Curl_printable_address(ai, myhost, sizeof(myhost));
-
-#ifdef ENABLE_IPV6
- if(!conn->bits.ftp_use_eprt && conn->bits.ipv6)
- /* EPRT is disabled but we are connected to a IPv6 host, so we ignore the
- request and enable EPRT again! */
- conn->bits.ftp_use_eprt = TRUE;
-#endif
-
- for(; fcmd != DONE; fcmd++) {
-
- if(!conn->bits.ftp_use_eprt && (EPRT == fcmd))
- /* if disabled, goto next */
- continue;
-
- if((PORT == fcmd) && sa->sa_family != AF_INET)
+ Curl_closesocket(conn, portsock);
+ return CURLE_FTP_PORT_FAILED;
+ }
+
+ /* step 5, send the proper FTP command */
+
+ /* get a plain printable version of the numerical address to work with
+ below */
+ Curl_printable_address(ai, myhost, sizeof(myhost));
+
+#ifdef ENABLE_IPV6
+ if(!conn->bits.ftp_use_eprt && conn->bits.ipv6)
+ /* EPRT is disabled but we are connected to a IPv6 host, so we ignore the
+ request and enable EPRT again! */
+ conn->bits.ftp_use_eprt = TRUE;
+#endif
+
+ for(; fcmd != DONE; fcmd++) {
+
+ if(!conn->bits.ftp_use_eprt && (EPRT == fcmd))
+ /* if disabled, goto next */
+ continue;
+
+ if((PORT == fcmd) && sa->sa_family != AF_INET)
/* PORT is IPv4 only */
- continue;
-
+ continue;
+
switch(sa->sa_family) {
- case AF_INET:
- port = ntohs(sa4->sin_port);
- break;
-#ifdef ENABLE_IPV6
- case AF_INET6:
- port = ntohs(sa6->sin6_port);
- break;
-#endif
- default:
- continue; /* might as well skip this */
- }
-
- if(EPRT == fcmd) {
- /*
- * Two fine examples from RFC2428;
- *
- * EPRT |1|132.235.1.2|6275|
- *
- * EPRT |2|1080::8:800:200C:417A|5282|
- */
-
- result = Curl_pp_sendf(&ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd],
- sa->sa_family == AF_INET?1:2,
- myhost, port);
- if(result) {
- failf(data, "Failure sending EPRT command: %s",
- curl_easy_strerror(result));
- Curl_closesocket(conn, portsock);
- /* don't retry using PORT */
- ftpc->count1 = PORT;
- /* bail out */
- state(conn, FTP_STOP);
- return result;
- }
- break;
- }
+ case AF_INET:
+ port = ntohs(sa4->sin_port);
+ break;
+#ifdef ENABLE_IPV6
+ case AF_INET6:
+ port = ntohs(sa6->sin6_port);
+ break;
+#endif
+ default:
+ continue; /* might as well skip this */
+ }
+
+ if(EPRT == fcmd) {
+ /*
+ * Two fine examples from RFC2428;
+ *
+ * EPRT |1|132.235.1.2|6275|
+ *
+ * EPRT |2|1080::8:800:200C:417A|5282|
+ */
+
+ result = Curl_pp_sendf(&ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd],
+ sa->sa_family == AF_INET?1:2,
+ myhost, port);
+ if(result) {
+ failf(data, "Failure sending EPRT command: %s",
+ curl_easy_strerror(result));
+ Curl_closesocket(conn, portsock);
+ /* don't retry using PORT */
+ ftpc->count1 = PORT;
+ /* bail out */
+ state(conn, FTP_STOP);
+ return result;
+ }
+ break;
+ }
if(PORT == fcmd) {
/* large enough for [IP address],[num],[num] */
char target[sizeof(myhost) + 20];
- char *source = myhost;
+ char *source = myhost;
char *dest = target;
-
- /* translate x.x.x.x to x,x,x,x */
- while(source && *source) {
- if(*source == '.')
+
+ /* translate x.x.x.x to x,x,x,x */
+ while(source && *source) {
+ if(*source == '.')
*dest = ',';
- else
- *dest = *source;
- dest++;
- source++;
- }
- *dest = 0;
+ else
+ *dest = *source;
+ dest++;
+ source++;
+ }
+ *dest = 0;
msnprintf(dest, 20, ",%d,%d", (int)(port>>8), (int)(port&0xff));
-
+
result = Curl_pp_sendf(&ftpc->pp, "%s %s", mode[fcmd], target);
- if(result) {
- failf(data, "Failure sending PORT command: %s",
- curl_easy_strerror(result));
- Curl_closesocket(conn, portsock);
- /* bail out */
- state(conn, FTP_STOP);
- return result;
- }
- break;
- }
- }
-
- /* store which command was sent */
- ftpc->count1 = fcmd;
-
+ if(result) {
+ failf(data, "Failure sending PORT command: %s",
+ curl_easy_strerror(result));
+ Curl_closesocket(conn, portsock);
+ /* bail out */
+ state(conn, FTP_STOP);
+ return result;
+ }
+ break;
+ }
+ }
+
+ /* store which command was sent */
+ ftpc->count1 = fcmd;
+
close_secondarysocket(conn);
- /* we set the secondary socket variable to this for now, it is only so that
- the cleanup function will close it in case we fail before the true
- secondary stuff is made */
- conn->sock[SECONDARYSOCKET] = portsock;
-
- /* this tcpconnect assignment below is a hackish work-around to make the
- multi interface with active FTP work - as it will not wait for a
- (passive) connect in Curl_is_connected().
-
- The *proper* fix is to make sure that the active connection from the
- server is done in a non-blocking way. Currently, it is still BLOCKING.
- */
- conn->bits.tcpconnect[SECONDARYSOCKET] = TRUE;
-
- state(conn, FTP_PORT);
- return result;
-}
-
-static CURLcode ftp_state_use_pasv(struct connectdata *conn)
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- CURLcode result = CURLE_OK;
- /*
+ /* we set the secondary socket variable to this for now, it is only so that
+ the cleanup function will close it in case we fail before the true
+ secondary stuff is made */
+ conn->sock[SECONDARYSOCKET] = portsock;
+
+ /* this tcpconnect assignment below is a hackish work-around to make the
+ multi interface with active FTP work - as it will not wait for a
+ (passive) connect in Curl_is_connected().
+
+ The *proper* fix is to make sure that the active connection from the
+ server is done in a non-blocking way. Currently, it is still BLOCKING.
+ */
+ conn->bits.tcpconnect[SECONDARYSOCKET] = TRUE;
+
+ state(conn, FTP_PORT);
+ return result;
+}
+
+static CURLcode ftp_state_use_pasv(struct connectdata *conn)
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ CURLcode result = CURLE_OK;
+ /*
Here's the executive summary on what to do:
-
- PASV is RFC959, expect:
- 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
-
- LPSV is RFC1639, expect:
- 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2)
-
- EPSV is RFC2428, expect:
- 229 Entering Extended Passive Mode (|||port|)
-
- */
-
- static const char mode[][5] = { "EPSV", "PASV" };
- int modeoff;
-
-#ifdef PF_INET6
- if(!conn->bits.ftp_use_epsv && conn->bits.ipv6)
- /* EPSV is disabled but we are connected to a IPv6 host, so we ignore the
- request and enable EPSV again! */
- conn->bits.ftp_use_epsv = TRUE;
-#endif
-
- modeoff = conn->bits.ftp_use_epsv?0:1;
-
+
+ PASV is RFC959, expect:
+ 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
+
+ LPSV is RFC1639, expect:
+ 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2)
+
+ EPSV is RFC2428, expect:
+ 229 Entering Extended Passive Mode (|||port|)
+
+ */
+
+ static const char mode[][5] = { "EPSV", "PASV" };
+ int modeoff;
+
+#ifdef PF_INET6
+ if(!conn->bits.ftp_use_epsv && conn->bits.ipv6)
+ /* EPSV is disabled but we are connected to a IPv6 host, so we ignore the
+ request and enable EPSV again! */
+ conn->bits.ftp_use_epsv = TRUE;
+#endif
+
+ modeoff = conn->bits.ftp_use_epsv?0:1;
+
result = Curl_pp_sendf(&ftpc->pp, "%s", mode[modeoff]);
if(!result) {
ftpc->count1 = modeoff;
state(conn, FTP_PASV);
infof(conn->data, "Connect data stream passively\n");
}
- return result;
-}
-
-/*
- * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc.
- *
- * REST is the last command in the chain of commands when a "head"-like
- * request is made. Thus, if an actual transfer is to be made this is where we
- * take off for real.
- */
-static CURLcode ftp_state_prepare_transfer(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ return result;
+}
+
+/*
+ * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc.
+ *
+ * REST is the last command in the chain of commands when a "head"-like
+ * request is made. Thus, if an actual transfer is to be made this is where we
+ * take off for real.
+ */
+static CURLcode ftp_state_prepare_transfer(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct FTP *ftp = conn->data->req.p.ftp;
struct Curl_easy *data = conn->data;
-
- if(ftp->transfer != FTPTRANSFER_BODY) {
- /* doesn't transfer any data */
-
- /* still possibly do PRE QUOTE jobs */
- state(conn, FTP_RETR_PREQUOTE);
- result = ftp_state_quote(conn, TRUE, FTP_RETR_PREQUOTE);
- }
- else if(data->set.ftp_use_port) {
- /* We have chosen to use the PORT (or similar) command */
- result = ftp_state_use_port(conn, EPRT);
- }
- else {
- /* We have chosen (this is default) to use the PASV (or similar) command */
- if(data->set.ftp_use_pret) {
- /* The user has requested that we send a PRET command
- to prepare the server for the upcoming PASV */
+
+ if(ftp->transfer != FTPTRANSFER_BODY) {
+ /* doesn't transfer any data */
+
+ /* still possibly do PRE QUOTE jobs */
+ state(conn, FTP_RETR_PREQUOTE);
+ result = ftp_state_quote(conn, TRUE, FTP_RETR_PREQUOTE);
+ }
+ else if(data->set.ftp_use_port) {
+ /* We have chosen to use the PORT (or similar) command */
+ result = ftp_state_use_port(conn, EPRT);
+ }
+ else {
+ /* We have chosen (this is default) to use the PASV (or similar) command */
+ if(data->set.ftp_use_pret) {
+ /* The user has requested that we send a PRET command
+ to prepare the server for the upcoming PASV */
struct ftp_conn *ftpc = &conn->proto.ftpc;
if(!conn->proto.ftpc.file)
result = Curl_pp_sendf(&ftpc->pp, "PRET %s",
@@ -1369,76 +1369,76 @@ static CURLcode ftp_state_prepare_transfer(struct connectdata *conn)
conn->proto.ftpc.file);
if(!result)
state(conn, FTP_PRET);
- }
+ }
else
- result = ftp_state_use_pasv(conn);
- }
- return result;
-}
-
-static CURLcode ftp_state_rest(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ result = ftp_state_use_pasv(conn);
+ }
+ return result;
+}
+
+static CURLcode ftp_state_rest(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct FTP *ftp = conn->data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- if((ftp->transfer != FTPTRANSFER_BODY) && ftpc->file) {
- /* if a "head"-like request is being made (on a file) */
-
- /* Determine if server can respond to REST command and therefore
- whether it supports range */
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ if((ftp->transfer != FTPTRANSFER_BODY) && ftpc->file) {
+ /* if a "head"-like request is being made (on a file) */
+
+ /* Determine if server can respond to REST command and therefore
+ whether it supports range */
result = Curl_pp_sendf(&ftpc->pp, "REST %d", 0);
if(!result)
state(conn, FTP_REST);
- }
- else
- result = ftp_state_prepare_transfer(conn);
-
- return result;
-}
-
-static CURLcode ftp_state_size(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ }
+ else
+ result = ftp_state_prepare_transfer(conn);
+
+ return result;
+}
+
+static CURLcode ftp_state_size(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct FTP *ftp = conn->data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- if((ftp->transfer == FTPTRANSFER_INFO) && ftpc->file) {
- /* if a "head"-like request is being made (on a file) */
-
- /* we know ftpc->file is a valid pointer to a file name */
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ if((ftp->transfer == FTPTRANSFER_INFO) && ftpc->file) {
+ /* if a "head"-like request is being made (on a file) */
+
+ /* we know ftpc->file is a valid pointer to a file name */
result = Curl_pp_sendf(&ftpc->pp, "SIZE %s", ftpc->file);
if(!result)
state(conn, FTP_SIZE);
- }
- else
- result = ftp_state_rest(conn);
-
- return result;
-}
-
-static CURLcode ftp_state_list(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ }
+ else
+ result = ftp_state_rest(conn);
+
+ return result;
+}
+
+static CURLcode ftp_state_list(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.p.ftp;
-
- /* If this output is to be machine-parsed, the NLST command might be better
- to use, since the LIST command output is not specified or standard in any
- way. It has turned out that the NLST list output is not the same on all
- servers either... */
-
- /*
+
+ /* If this output is to be machine-parsed, the NLST command might be better
+ to use, since the LIST command output is not specified or standard in any
+ way. It has turned out that the NLST list output is not the same on all
+ servers either... */
+
+ /*
if FTPFILE_NOCWD was specified, we should add the path
- as argument for the LIST / NLST / or custom command.
- Whether the server will support this, is uncertain.
-
- The other ftp_filemethods will CWD into dir/dir/ first and
- then just do LIST (in that case: nothing to do here)
- */
+ as argument for the LIST / NLST / or custom command.
+ Whether the server will support this, is uncertain.
+
+ The other ftp_filemethods will CWD into dir/dir/ first and
+ then just do LIST (in that case: nothing to do here)
+ */
char *lstArg = NULL;
char *cmd;
-
+
if((data->set.ftp_filemethod == FTPFILE_NOCWD) && ftp->path) {
/* url-decode before evaluation: e.g. paths starting/ending with %2f */
const char *slashPos = NULL;
@@ -1446,7 +1446,7 @@ static CURLcode ftp_state_list(struct connectdata *conn)
result = Curl_urldecode(data, ftp->path, 0, &rawPath, NULL, REJECT_CTRL);
if(result)
return result;
-
+
slashPos = strrchr(rawPath, '/');
if(slashPos) {
/* chop off the file part if format is dir/file otherwise remove
@@ -1457,11 +1457,11 @@ static CURLcode ftp_state_list(struct connectdata *conn)
lstArg = rawPath;
lstArg[n] = '\0';
- }
+ }
else
free(rawPath);
- }
-
+ }
+
cmd = aprintf("%s%s%s",
data->set.str[STRING_CUSTOMREQUEST]?
data->set.str[STRING_CUSTOMREQUEST]:
@@ -1469,148 +1469,148 @@ static CURLcode ftp_state_list(struct connectdata *conn)
lstArg? " ": "",
lstArg? lstArg: "");
free(lstArg);
-
+
if(!cmd)
- return CURLE_OUT_OF_MEMORY;
-
- result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", cmd);
- free(cmd);
-
+ return CURLE_OUT_OF_MEMORY;
+
+ result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", cmd);
+ free(cmd);
+
if(!result)
state(conn, FTP_LIST);
-
- return result;
-}
-
-static CURLcode ftp_state_retr_prequote(struct connectdata *conn)
-{
- /* We've sent the TYPE, now we must send the list of prequote strings */
+
+ return result;
+}
+
+static CURLcode ftp_state_retr_prequote(struct connectdata *conn)
+{
+ /* We've sent the TYPE, now we must send the list of prequote strings */
return ftp_state_quote(conn, TRUE, FTP_RETR_PREQUOTE);
-}
-
-static CURLcode ftp_state_stor_prequote(struct connectdata *conn)
-{
- /* We've sent the TYPE, now we must send the list of prequote strings */
+}
+
+static CURLcode ftp_state_stor_prequote(struct connectdata *conn)
+{
+ /* We've sent the TYPE, now we must send the list of prequote strings */
return ftp_state_quote(conn, TRUE, FTP_STOR_PREQUOTE);
-}
-
-static CURLcode ftp_state_type(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+}
+
+static CURLcode ftp_state_type(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct FTP *ftp = conn->data->req.p.ftp;
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- /* If we have selected NOBODY and HEADER, it means that we only want file
- information. Which in FTP can't be much more than the file size and
- date. */
- if(data->set.opt_no_body && ftpc->file &&
- ftp_need_type(conn, data->set.prefer_ascii)) {
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ /* If we have selected NOBODY and HEADER, it means that we only want file
+ information. Which in FTP can't be much more than the file size and
+ date. */
+ if(data->set.opt_no_body && ftpc->file &&
+ ftp_need_type(conn, data->set.prefer_ascii)) {
/* The SIZE command is _not_ RFC 959 specified, and therefore many servers
- may not support it! It is however the only way we have to get a file's
- size! */
-
- ftp->transfer = FTPTRANSFER_INFO;
- /* this means no actual transfer will be made */
-
- /* Some servers return different sizes for different modes, and thus we
- must set the proper type before we check the size */
- result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_TYPE);
- if(result)
- return result;
- }
- else
- result = ftp_state_size(conn);
-
- return result;
-}
-
-/* This is called after the CWD commands have been done in the beginning of
- the DO phase */
-static CURLcode ftp_state_mdtm(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ may not support it! It is however the only way we have to get a file's
+ size! */
+
+ ftp->transfer = FTPTRANSFER_INFO;
+ /* this means no actual transfer will be made */
+
+ /* Some servers return different sizes for different modes, and thus we
+ must set the proper type before we check the size */
+ result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_TYPE);
+ if(result)
+ return result;
+ }
+ else
+ result = ftp_state_size(conn);
+
+ return result;
+}
+
+/* This is called after the CWD commands have been done in the beginning of
+ the DO phase */
+static CURLcode ftp_state_mdtm(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- /* Requested time of file or time-depended transfer? */
- if((data->set.get_filetime || data->set.timecondition) && ftpc->file) {
-
- /* we have requested to get the modified-time of the file, this is a white
- spot as the MDTM is not mentioned in RFC959 */
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ /* Requested time of file or time-depended transfer? */
+ if((data->set.get_filetime || data->set.timecondition) && ftpc->file) {
+
+ /* we have requested to get the modified-time of the file, this is a white
+ spot as the MDTM is not mentioned in RFC959 */
result = Curl_pp_sendf(&ftpc->pp, "MDTM %s", ftpc->file);
-
+
if(!result)
state(conn, FTP_MDTM);
- }
- else
- result = ftp_state_type(conn);
-
- return result;
-}
-
-
-/* This is called after the TYPE and possible quote commands have been sent */
-static CURLcode ftp_state_ul_setup(struct connectdata *conn,
- bool sizechecked)
-{
- CURLcode result = CURLE_OK;
+ }
+ else
+ result = ftp_state_type(conn);
+
+ return result;
+}
+
+
+/* This is called after the TYPE and possible quote commands have been sent */
+static CURLcode ftp_state_ul_setup(struct connectdata *conn,
+ bool sizechecked)
+{
+ CURLcode result = CURLE_OK;
struct FTP *ftp = conn->data->req.p.ftp;
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- if((data->state.resume_from && !sizechecked) ||
- ((data->state.resume_from > 0) && sizechecked)) {
- /* we're about to continue the uploading of a file */
- /* 1. get already existing file's size. We use the SIZE command for this
- which may not exist in the server! The SIZE command is not in
- RFC959. */
-
- /* 2. This used to set REST. But since we can do append, we
- don't another ftp command. We just skip the source file
- offset and then we APPEND the rest on the file instead */
-
- /* 3. pass file-size number of bytes in the source file */
- /* 4. lower the infilesize counter */
- /* => transfer as usual */
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ if((data->state.resume_from && !sizechecked) ||
+ ((data->state.resume_from > 0) && sizechecked)) {
+ /* we're about to continue the uploading of a file */
+ /* 1. get already existing file's size. We use the SIZE command for this
+ which may not exist in the server! The SIZE command is not in
+ RFC959. */
+
+ /* 2. This used to set REST. But since we can do append, we
+ don't another ftp command. We just skip the source file
+ offset and then we APPEND the rest on the file instead */
+
+ /* 3. pass file-size number of bytes in the source file */
+ /* 4. lower the infilesize counter */
+ /* => transfer as usual */
int seekerr = CURL_SEEKFUNC_OK;
-
+
if(data->state.resume_from < 0) {
- /* Got no given size to start from, figure it out */
+ /* Got no given size to start from, figure it out */
result = Curl_pp_sendf(&ftpc->pp, "SIZE %s", ftpc->file);
if(!result)
state(conn, FTP_STOR_SIZE);
- return result;
- }
-
- /* enable append */
- data->set.ftp_append = TRUE;
-
- /* Let's read off the proper amount of bytes from the input. */
- if(conn->seek_func) {
+ return result;
+ }
+
+ /* enable append */
+ data->set.ftp_append = TRUE;
+
+ /* Let's read off the proper amount of bytes from the input. */
+ if(conn->seek_func) {
Curl_set_in_callback(data, true);
- seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
- SEEK_SET);
+ seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
+ SEEK_SET);
Curl_set_in_callback(data, false);
- }
-
- if(seekerr != CURL_SEEKFUNC_OK) {
+ }
+
+ if(seekerr != CURL_SEEKFUNC_OK) {
curl_off_t passed = 0;
- if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
- failf(data, "Could not seek stream");
- return CURLE_FTP_COULDNT_USE_REST;
- }
- /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
+ if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
+ failf(data, "Could not seek stream");
+ return CURLE_FTP_COULDNT_USE_REST;
+ }
+ /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
do {
size_t readthisamountnow =
(data->state.resume_from - passed > data->set.buffer_size) ?
(size_t)data->set.buffer_size :
curlx_sotouz(data->state.resume_from - passed);
-
+
size_t actuallyread =
data->state.fread_func(data->state.buffer, 1, readthisamountnow,
data->state.in);
-
+
passed += actuallyread;
if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
/* this checks for greater-than only to make sure that the
@@ -1619,113 +1619,113 @@ static CURLcode ftp_state_ul_setup(struct connectdata *conn,
return CURLE_FTP_COULDNT_USE_REST;
}
} while(passed < data->state.resume_from);
- }
- /* now, decrease the size of the read */
+ }
+ /* now, decrease the size of the read */
if(data->state.infilesize>0) {
data->state.infilesize -= data->state.resume_from;
-
+
if(data->state.infilesize <= 0) {
- infof(data, "File already completely uploaded\n");
-
- /* no data to transfer */
+ infof(data, "File already completely uploaded\n");
+
+ /* no data to transfer */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
-
- /* Set ->transfer so that we won't get any error in
- * ftp_done() because we didn't transfer anything! */
- ftp->transfer = FTPTRANSFER_NONE;
-
- state(conn, FTP_STOP);
- return CURLE_OK;
- }
- }
- /* we've passed, proceed as normal */
- } /* resume_from */
-
+
+ /* Set ->transfer so that we won't get any error in
+ * ftp_done() because we didn't transfer anything! */
+ ftp->transfer = FTPTRANSFER_NONE;
+
+ state(conn, FTP_STOP);
+ return CURLE_OK;
+ }
+ }
+ /* we've passed, proceed as normal */
+ } /* resume_from */
+
result = Curl_pp_sendf(&ftpc->pp, data->set.ftp_append?"APPE %s":"STOR %s",
ftpc->file);
if(!result)
state(conn, FTP_STOR);
-
- return result;
-}
-
-static CURLcode ftp_state_quote(struct connectdata *conn,
- bool init,
- ftpstate instate)
-{
- CURLcode result = CURLE_OK;
+
+ return result;
+}
+
+static CURLcode ftp_state_quote(struct connectdata *conn,
+ bool init,
+ ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
bool quote = FALSE;
- struct curl_slist *item;
-
- switch(instate) {
- case FTP_QUOTE:
- default:
- item = data->set.quote;
- break;
- case FTP_RETR_PREQUOTE:
- case FTP_STOR_PREQUOTE:
- item = data->set.prequote;
- break;
- case FTP_POSTQUOTE:
- item = data->set.postquote;
- break;
- }
-
- /*
- * This state uses:
- * 'count1' to iterate over the commands to send
+ struct curl_slist *item;
+
+ switch(instate) {
+ case FTP_QUOTE:
+ default:
+ item = data->set.quote;
+ break;
+ case FTP_RETR_PREQUOTE:
+ case FTP_STOR_PREQUOTE:
+ item = data->set.prequote;
+ break;
+ case FTP_POSTQUOTE:
+ item = data->set.postquote;
+ break;
+ }
+
+ /*
+ * This state uses:
+ * 'count1' to iterate over the commands to send
* 'count2' to store whether to allow commands to fail
- */
-
- if(init)
- ftpc->count1 = 0;
- else
- ftpc->count1++;
-
- if(item) {
- int i = 0;
-
- /* Skip count1 items in the linked list */
- while((i< ftpc->count1) && item) {
- item = item->next;
- i++;
- }
- if(item) {
- char *cmd = item->data;
- if(cmd[0] == '*') {
- cmd++;
- ftpc->count2 = 1; /* the sent command is allowed to fail */
- }
- else
- ftpc->count2 = 0; /* failure means cancel operation */
-
+ */
+
+ if(init)
+ ftpc->count1 = 0;
+ else
+ ftpc->count1++;
+
+ if(item) {
+ int i = 0;
+
+ /* Skip count1 items in the linked list */
+ while((i< ftpc->count1) && item) {
+ item = item->next;
+ i++;
+ }
+ if(item) {
+ char *cmd = item->data;
+ if(cmd[0] == '*') {
+ cmd++;
+ ftpc->count2 = 1; /* the sent command is allowed to fail */
+ }
+ else
+ ftpc->count2 = 0; /* failure means cancel operation */
+
result = Curl_pp_sendf(&ftpc->pp, "%s", cmd);
if(result)
return result;
- state(conn, instate);
- quote = TRUE;
- }
- }
-
- if(!quote) {
- /* No more quote to send, continue to ... */
- switch(instate) {
- case FTP_QUOTE:
- default:
- result = ftp_state_cwd(conn);
- break;
- case FTP_RETR_PREQUOTE:
- if(ftp->transfer != FTPTRANSFER_BODY)
- state(conn, FTP_STOP);
- else {
- if(ftpc->known_filesize != -1) {
- Curl_pgrsSetDownloadSize(data, ftpc->known_filesize);
- result = ftp_state_retr(conn, ftpc->known_filesize);
- }
- else {
+ state(conn, instate);
+ quote = TRUE;
+ }
+ }
+
+ if(!quote) {
+ /* No more quote to send, continue to ... */
+ switch(instate) {
+ case FTP_QUOTE:
+ default:
+ result = ftp_state_cwd(conn);
+ break;
+ case FTP_RETR_PREQUOTE:
+ if(ftp->transfer != FTPTRANSFER_BODY)
+ state(conn, FTP_STOP);
+ else {
+ if(ftpc->known_filesize != -1) {
+ Curl_pgrsSetDownloadSize(data, ftpc->known_filesize);
+ result = ftp_state_retr(conn, ftpc->known_filesize);
+ }
+ else {
if(data->set.ignorecl) {
/* This code is to support download of growing files. It prevents
the state machine from requesting the file size from the
@@ -1742,25 +1742,25 @@ static CURLcode ftp_state_quote(struct connectdata *conn,
if(!result)
state(conn, FTP_RETR_SIZE);
}
- }
- }
- break;
- case FTP_STOR_PREQUOTE:
- result = ftp_state_ul_setup(conn, FALSE);
- break;
- case FTP_POSTQUOTE:
- break;
- }
- }
-
- return result;
-}
-
-/* called from ftp_state_pasv_resp to switch to PASV in case of EPSV
- problems */
-static CURLcode ftp_epsv_disable(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ }
+ }
+ break;
+ case FTP_STOR_PREQUOTE:
+ result = ftp_state_ul_setup(conn, FALSE);
+ break;
+ case FTP_POSTQUOTE:
+ break;
+ }
+ }
+
+ return result;
+}
+
+/* called from ftp_state_pasv_resp to switch to PASV in case of EPSV
+ problems */
+static CURLcode ftp_epsv_disable(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
if(conn->bits.ipv6
#ifndef CURL_DISABLE_PROXY
@@ -1772,20 +1772,20 @@ static CURLcode ftp_epsv_disable(struct connectdata *conn)
return CURLE_WEIRD_SERVER_REPLY;
}
- infof(conn->data, "Failed EPSV attempt. Disabling EPSV\n");
- /* disable it for next transfer */
- conn->bits.ftp_use_epsv = FALSE;
- conn->data->state.errorbuf = FALSE; /* allow error message to get
- rewritten */
+ infof(conn->data, "Failed EPSV attempt. Disabling EPSV\n");
+ /* disable it for next transfer */
+ conn->bits.ftp_use_epsv = FALSE;
+ conn->data->state.errorbuf = FALSE; /* allow error message to get
+ rewritten */
result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", "PASV");
if(!result) {
conn->proto.ftpc.count1++;
/* remain in/go to the FTP_PASV state */
state(conn, FTP_PASV);
}
- return result;
-}
-
+ return result;
+}
+
static char *control_address(struct connectdata *conn)
{
@@ -1800,146 +1800,146 @@ static char *control_address(struct connectdata *conn)
return conn->ip_addr_str;
}
-static CURLcode ftp_state_pasv_resp(struct connectdata *conn,
- int ftpcode)
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- CURLcode result;
+static CURLcode ftp_state_pasv_resp(struct connectdata *conn,
+ int ftpcode)
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ CURLcode result;
struct Curl_easy *data = conn->data;
struct Curl_dns_entry *addr = NULL;
enum resolve_t rc;
- unsigned short connectport; /* the local port connect() should use! */
+ unsigned short connectport; /* the local port connect() should use! */
char *str = &data->state.buffer[4]; /* start on the first letter */
-
+
/* if we come here again, make sure the former name is cleared */
Curl_safefree(ftpc->newhost);
-
- if((ftpc->count1 == 0) &&
- (ftpcode == 229)) {
- /* positive EPSV response */
- char *ptr = strchr(str, '(');
- if(ptr) {
- unsigned int num;
- char separator[4];
- ptr++;
+
+ if((ftpc->count1 == 0) &&
+ (ftpcode == 229)) {
+ /* positive EPSV response */
+ char *ptr = strchr(str, '(');
+ if(ptr) {
+ unsigned int num;
+ char separator[4];
+ ptr++;
if(5 == sscanf(ptr, "%c%c%c%u%c",
&separator[0],
&separator[1],
&separator[2],
&num,
&separator[3])) {
- const char sep1 = separator[0];
- int i;
-
- /* The four separators should be identical, or else this is an oddly
- formatted reply and we bail out immediately. */
+ const char sep1 = separator[0];
+ int i;
+
+ /* The four separators should be identical, or else this is an oddly
+ formatted reply and we bail out immediately. */
for(i = 1; i<4; i++) {
- if(separator[i] != sep1) {
+ if(separator[i] != sep1) {
ptr = NULL; /* set to NULL to signal error */
- break;
- }
- }
- if(num > 0xffff) {
- failf(data, "Illegal port number in EPSV reply");
- return CURLE_FTP_WEIRD_PASV_REPLY;
- }
- if(ptr) {
+ break;
+ }
+ }
+ if(num > 0xffff) {
+ failf(data, "Illegal port number in EPSV reply");
+ return CURLE_FTP_WEIRD_PASV_REPLY;
+ }
+ if(ptr) {
ftpc->newport = (unsigned short)(num & 0xffff);
ftpc->newhost = strdup(control_address(conn));
if(!ftpc->newhost)
return CURLE_OUT_OF_MEMORY;
- }
- }
- else
+ }
+ }
+ else
ptr = NULL;
- }
- if(!ptr) {
- failf(data, "Weirdly formatted EPSV reply");
- return CURLE_FTP_WEIRD_PASV_REPLY;
- }
- }
- else if((ftpc->count1 == 1) &&
- (ftpcode == 227)) {
- /* positive PASV response */
+ }
+ if(!ptr) {
+ failf(data, "Weirdly formatted EPSV reply");
+ return CURLE_FTP_WEIRD_PASV_REPLY;
+ }
+ }
+ else if((ftpc->count1 == 1) &&
+ (ftpcode == 227)) {
+ /* positive PASV response */
unsigned int ip[4] = {0, 0, 0, 0};
unsigned int port[2] = {0, 0};
-
- /*
- * Scan for a sequence of six comma-separated numbers and use them as
- * IP+port indicators.
- *
- * Found reply-strings include:
- * "227 Entering Passive Mode (127,0,0,1,4,51)"
- * "227 Data transfer will passively listen to 127,0,0,1,4,51"
- * "227 Entering passive mode. 127,0,0,1,4,51"
- */
- while(*str) {
+
+ /*
+ * Scan for a sequence of six comma-separated numbers and use them as
+ * IP+port indicators.
+ *
+ * Found reply-strings include:
+ * "227 Entering Passive Mode (127,0,0,1,4,51)"
+ * "227 Data transfer will passively listen to 127,0,0,1,4,51"
+ * "227 Entering passive mode. 127,0,0,1,4,51"
+ */
+ while(*str) {
if(6 == sscanf(str, "%u,%u,%u,%u,%u,%u",
&ip[0], &ip[1], &ip[2], &ip[3],
&port[0], &port[1]))
- break;
- str++;
- }
-
+ break;
+ str++;
+ }
+
if(!*str || (ip[0] > 255) || (ip[1] > 255) || (ip[2] > 255) ||
(ip[3] > 255) || (port[0] > 255) || (port[1] > 255) ) {
- failf(data, "Couldn't interpret the 227-response");
- return CURLE_FTP_WEIRD_227_FORMAT;
- }
-
- /* we got OK from server */
- if(data->set.ftp_skip_ip) {
+ failf(data, "Couldn't interpret the 227-response");
+ return CURLE_FTP_WEIRD_227_FORMAT;
+ }
+
+ /* we got OK from server */
+ if(data->set.ftp_skip_ip) {
/* told to ignore the remotely given IP but instead use the host we used
- for the control connection */
+ for the control connection */
infof(data, "Skip %u.%u.%u.%u for data connection, re-use %s instead\n",
- ip[0], ip[1], ip[2], ip[3],
+ ip[0], ip[1], ip[2], ip[3],
conn->host.name);
ftpc->newhost = strdup(control_address(conn));
- }
- else
+ }
+ else
ftpc->newhost = aprintf("%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
if(!ftpc->newhost)
return CURLE_OUT_OF_MEMORY;
ftpc->newport = (unsigned short)(((port[0]<<8) + port[1]) & 0xffff);
- }
- else if(ftpc->count1 == 0) {
- /* EPSV failed, move on to PASV */
- return ftp_epsv_disable(conn);
- }
- else {
- failf(data, "Bad PASV/EPSV response: %03d", ftpcode);
- return CURLE_FTP_WEIRD_PASV_REPLY;
- }
-
+ }
+ else if(ftpc->count1 == 0) {
+ /* EPSV failed, move on to PASV */
+ return ftp_epsv_disable(conn);
+ }
+ else {
+ failf(data, "Bad PASV/EPSV response: %03d", ftpcode);
+ return CURLE_FTP_WEIRD_PASV_REPLY;
+ }
+
#ifndef CURL_DISABLE_PROXY
- if(conn->bits.proxy) {
- /*
- * This connection uses a proxy and we need to connect to the proxy again
- * here. We don't want to rely on a former host lookup that might've
- * expired now, instead we remake the lookup here and now!
- */
+ if(conn->bits.proxy) {
+ /*
+ * This connection uses a proxy and we need to connect to the proxy again
+ * here. We don't want to rely on a former host lookup that might've
+ * expired now, instead we remake the lookup here and now!
+ */
const char * const host_name = conn->bits.socksproxy ?
conn->socks_proxy.host.name : conn->http_proxy.host.name;
rc = Curl_resolv(conn, host_name, (int)conn->port, FALSE, &addr);
- if(rc == CURLRESOLV_PENDING)
- /* BLOCKING, ignores the return code but 'addr' will be NULL in
- case of failure */
- (void)Curl_resolver_wait_resolv(conn, &addr);
-
- connectport =
- (unsigned short)conn->port; /* we connect to the proxy's port */
-
- if(!addr) {
+ if(rc == CURLRESOLV_PENDING)
+ /* BLOCKING, ignores the return code but 'addr' will be NULL in
+ case of failure */
+ (void)Curl_resolver_wait_resolv(conn, &addr);
+
+ connectport =
+ (unsigned short)conn->port; /* we connect to the proxy's port */
+
+ if(!addr) {
failf(data, "Can't resolve proxy host %s:%hu", host_name, connectport);
return CURLE_COULDNT_RESOLVE_PROXY;
- }
- }
+ }
+ }
else
#endif
{
- /* normal, direct, ftp connection */
+ /* normal, direct, ftp connection */
DEBUGASSERT(ftpc->newhost);
/* postponed address resolution in case of tcp fastopen */
@@ -1952,133 +1952,133 @@ static CURLcode ftp_state_pasv_resp(struct connectdata *conn,
}
rc = Curl_resolv(conn, ftpc->newhost, ftpc->newport, FALSE, &addr);
- if(rc == CURLRESOLV_PENDING)
- /* BLOCKING */
- (void)Curl_resolver_wait_resolv(conn, &addr);
-
+ if(rc == CURLRESOLV_PENDING)
+ /* BLOCKING */
+ (void)Curl_resolver_wait_resolv(conn, &addr);
+
connectport = ftpc->newport; /* we connect to the remote port */
-
- if(!addr) {
+
+ if(!addr) {
failf(data, "Can't resolve new host %s:%hu", ftpc->newhost, connectport);
- return CURLE_FTP_CANT_GET_HOST;
- }
- }
-
+ return CURLE_FTP_CANT_GET_HOST;
+ }
+ }
+
conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE;
result = Curl_connecthost(conn, addr);
-
- if(result) {
+
+ if(result) {
Curl_resolv_unlock(data, addr); /* we're done using this address */
- if(ftpc->count1 == 0 && ftpcode == 229)
- return ftp_epsv_disable(conn);
-
- return result;
- }
-
-
- /*
- * When this is used from the multi interface, this might've returned with
- * the 'connected' set to FALSE and thus we are now awaiting a non-blocking
+ if(ftpc->count1 == 0 && ftpcode == 229)
+ return ftp_epsv_disable(conn);
+
+ return result;
+ }
+
+
+ /*
+ * When this is used from the multi interface, this might've returned with
+ * the 'connected' set to FALSE and thus we are now awaiting a non-blocking
* connect to connect.
- */
-
- if(data->set.verbose)
- /* this just dumps information about this second connection */
+ */
+
+ if(data->set.verbose)
+ /* this just dumps information about this second connection */
ftp_pasv_verbose(conn, addr->addr, ftpc->newhost, connectport);
-
+
Curl_resolv_unlock(data, addr); /* we're done using this address */
-
+
Curl_safefree(conn->secondaryhostname);
conn->secondary_port = ftpc->newport;
conn->secondaryhostname = strdup(ftpc->newhost);
if(!conn->secondaryhostname)
return CURLE_OUT_OF_MEMORY;
-
- conn->bits.do_more = TRUE;
- state(conn, FTP_STOP); /* this phase is completed */
-
- return result;
-}
-
-static CURLcode ftp_state_port_resp(struct connectdata *conn,
- int ftpcode)
-{
+
+ conn->bits.do_more = TRUE;
+ state(conn, FTP_STOP); /* this phase is completed */
+
+ return result;
+}
+
+static CURLcode ftp_state_port_resp(struct connectdata *conn,
+ int ftpcode)
+{
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- ftpport fcmd = (ftpport)ftpc->count1;
- CURLcode result = CURLE_OK;
-
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ ftpport fcmd = (ftpport)ftpc->count1;
+ CURLcode result = CURLE_OK;
+
/* The FTP spec tells a positive response should have code 200.
Be more permissive here to tolerate deviant servers. */
if(ftpcode / 100 != 2) {
- /* the command failed */
-
- if(EPRT == fcmd) {
- infof(data, "disabling EPRT usage\n");
- conn->bits.ftp_use_eprt = FALSE;
- }
- fcmd++;
-
- if(fcmd == DONE) {
- failf(data, "Failed to do PORT");
- result = CURLE_FTP_PORT_FAILED;
- }
- else
- /* try next */
- result = ftp_state_use_port(conn, fcmd);
- }
- else {
- infof(data, "Connect data stream actively\n");
- state(conn, FTP_STOP); /* end of DO phase */
- result = ftp_dophase_done(conn, FALSE);
- }
-
- return result;
-}
-
-static CURLcode ftp_state_mdtm_resp(struct connectdata *conn,
- int ftpcode)
-{
- CURLcode result = CURLE_OK;
+ /* the command failed */
+
+ if(EPRT == fcmd) {
+ infof(data, "disabling EPRT usage\n");
+ conn->bits.ftp_use_eprt = FALSE;
+ }
+ fcmd++;
+
+ if(fcmd == DONE) {
+ failf(data, "Failed to do PORT");
+ result = CURLE_FTP_PORT_FAILED;
+ }
+ else
+ /* try next */
+ result = ftp_state_use_port(conn, fcmd);
+ }
+ else {
+ infof(data, "Connect data stream actively\n");
+ state(conn, FTP_STOP); /* end of DO phase */
+ result = ftp_dophase_done(conn, FALSE);
+ }
+
+ return result;
+}
+
+static CURLcode ftp_state_mdtm_resp(struct connectdata *conn,
+ int ftpcode)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- switch(ftpcode) {
- case 213:
- {
- /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the
- last .sss part is optional and means fractions of a second */
- int year, month, day, hour, minute, second;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ switch(ftpcode) {
+ case 213:
+ {
+ /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the
+ last .sss part is optional and means fractions of a second */
+ int year, month, day, hour, minute, second;
if(6 == sscanf(&data->state.buffer[4], "%04d%02d%02d%02d%02d%02d",
- &year, &month, &day, &hour, &minute, &second)) {
- /* we have a time, reformat it */
+ &year, &month, &day, &hour, &minute, &second)) {
+ /* we have a time, reformat it */
char timebuf[24];
msnprintf(timebuf, sizeof(timebuf),
"%04d%02d%02d %02d:%02d:%02d GMT",
year, month, day, hour, minute, second);
- /* now, convert this into a time() value: */
+ /* now, convert this into a time() value: */
data->info.filetime = Curl_getdate_capped(timebuf);
- }
-
-#ifdef CURL_FTP_HTTPSTYLE_HEAD
- /* If we asked for a time of the file and we actually got one as well,
- we "emulate" a HTTP-style header in our output. */
-
- if(data->set.opt_no_body &&
- ftpc->file &&
- data->set.get_filetime &&
+ }
+
+#ifdef CURL_FTP_HTTPSTYLE_HEAD
+ /* If we asked for a time of the file and we actually got one as well,
+ we "emulate" a HTTP-style header in our output. */
+
+ if(data->set.opt_no_body &&
+ ftpc->file &&
+ data->set.get_filetime &&
(data->info.filetime >= 0) ) {
char headerbuf[128];
time_t filetime = data->info.filetime;
- struct tm buffer;
- const struct tm *tm = &buffer;
-
- result = Curl_gmtime(filetime, &buffer);
- if(result)
- return result;
-
- /* format: "Tue, 15 Nov 1994 12:45:26" */
+ struct tm buffer;
+ const struct tm *tm = &buffer;
+
+ result = Curl_gmtime(filetime, &buffer);
+ if(result)
+ return result;
+
+ /* format: "Tue, 15 Nov 1994 12:45:26" */
msnprintf(headerbuf, sizeof(headerbuf),
"Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
@@ -2089,179 +2089,179 @@ static CURLcode ftp_state_mdtm_resp(struct connectdata *conn,
tm->tm_min,
tm->tm_sec);
result = Curl_client_write(conn, CLIENTWRITE_BOTH, headerbuf, 0);
- if(result)
- return result;
- } /* end of a ridiculous amount of conditionals */
-#endif
- }
- break;
- default:
- infof(data, "unsupported MDTM reply format\n");
- break;
- case 550: /* "No such file or directory" */
- failf(data, "Given file does not exist");
+ if(result)
+ return result;
+ } /* end of a ridiculous amount of conditionals */
+#endif
+ }
+ break;
+ default:
+ infof(data, "unsupported MDTM reply format\n");
+ break;
+ case 550: /* "No such file or directory" */
+ failf(data, "Given file does not exist");
result = CURLE_REMOTE_FILE_NOT_FOUND;
- break;
- }
-
- if(data->set.timecondition) {
- if((data->info.filetime > 0) && (data->set.timevalue > 0)) {
- switch(data->set.timecondition) {
- case CURL_TIMECOND_IFMODSINCE:
- default:
- if(data->info.filetime <= data->set.timevalue) {
- infof(data, "The requested document is not new enough\n");
- ftp->transfer = FTPTRANSFER_NONE; /* mark to not transfer data */
- data->info.timecond = TRUE;
- state(conn, FTP_STOP);
- return CURLE_OK;
- }
- break;
- case CURL_TIMECOND_IFUNMODSINCE:
- if(data->info.filetime > data->set.timevalue) {
- infof(data, "The requested document is not old enough\n");
- ftp->transfer = FTPTRANSFER_NONE; /* mark to not transfer data */
- data->info.timecond = TRUE;
- state(conn, FTP_STOP);
- return CURLE_OK;
- }
- break;
- } /* switch */
- }
- else {
- infof(data, "Skipping time comparison\n");
- }
- }
-
- if(!result)
- result = ftp_state_type(conn);
-
- return result;
-}
-
-static CURLcode ftp_state_type_resp(struct connectdata *conn,
- int ftpcode,
- ftpstate instate)
-{
- CURLcode result = CURLE_OK;
+ break;
+ }
+
+ if(data->set.timecondition) {
+ if((data->info.filetime > 0) && (data->set.timevalue > 0)) {
+ switch(data->set.timecondition) {
+ case CURL_TIMECOND_IFMODSINCE:
+ default:
+ if(data->info.filetime <= data->set.timevalue) {
+ infof(data, "The requested document is not new enough\n");
+ ftp->transfer = FTPTRANSFER_NONE; /* mark to not transfer data */
+ data->info.timecond = TRUE;
+ state(conn, FTP_STOP);
+ return CURLE_OK;
+ }
+ break;
+ case CURL_TIMECOND_IFUNMODSINCE:
+ if(data->info.filetime > data->set.timevalue) {
+ infof(data, "The requested document is not old enough\n");
+ ftp->transfer = FTPTRANSFER_NONE; /* mark to not transfer data */
+ data->info.timecond = TRUE;
+ state(conn, FTP_STOP);
+ return CURLE_OK;
+ }
+ break;
+ } /* switch */
+ }
+ else {
+ infof(data, "Skipping time comparison\n");
+ }
+ }
+
+ if(!result)
+ result = ftp_state_type(conn);
+
+ return result;
+}
+
+static CURLcode ftp_state_type_resp(struct connectdata *conn,
+ int ftpcode,
+ ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- if(ftpcode/100 != 2) {
- /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a
- successful 'TYPE I'. While that is not as RFC959 says, it is still a
- positive response code and we allow that. */
- failf(data, "Couldn't set desired mode");
- return CURLE_FTP_COULDNT_SET_TYPE;
- }
- if(ftpcode != 200)
- infof(data, "Got a %03d response code instead of the assumed 200\n",
- ftpcode);
-
- if(instate == FTP_TYPE)
- result = ftp_state_size(conn);
- else if(instate == FTP_LIST_TYPE)
- result = ftp_state_list(conn);
- else if(instate == FTP_RETR_TYPE)
- result = ftp_state_retr_prequote(conn);
- else if(instate == FTP_STOR_TYPE)
- result = ftp_state_stor_prequote(conn);
-
- return result;
-}
-
-static CURLcode ftp_state_retr(struct connectdata *conn,
- curl_off_t filesize)
-{
- CURLcode result = CURLE_OK;
+
+ if(ftpcode/100 != 2) {
+ /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a
+ successful 'TYPE I'. While that is not as RFC959 says, it is still a
+ positive response code and we allow that. */
+ failf(data, "Couldn't set desired mode");
+ return CURLE_FTP_COULDNT_SET_TYPE;
+ }
+ if(ftpcode != 200)
+ infof(data, "Got a %03d response code instead of the assumed 200\n",
+ ftpcode);
+
+ if(instate == FTP_TYPE)
+ result = ftp_state_size(conn);
+ else if(instate == FTP_LIST_TYPE)
+ result = ftp_state_list(conn);
+ else if(instate == FTP_RETR_TYPE)
+ result = ftp_state_retr_prequote(conn);
+ else if(instate == FTP_STOR_TYPE)
+ result = ftp_state_stor_prequote(conn);
+
+ return result;
+}
+
+static CURLcode ftp_state_retr(struct connectdata *conn,
+ curl_off_t filesize)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- if(data->set.max_filesize && (filesize > data->set.max_filesize)) {
- failf(data, "Maximum file size exceeded");
- return CURLE_FILESIZE_EXCEEDED;
- }
- ftp->downloadsize = filesize;
-
- if(data->state.resume_from) {
- /* We always (attempt to) get the size of downloads, so it is done before
- this even when not doing resumes. */
- if(filesize == -1) {
- infof(data, "ftp server doesn't support SIZE\n");
- /* We couldn't get the size and therefore we can't know if there really
- is a part of the file left to get, although the server will just
- close the connection when we start the connection so it won't cause
- us any harm, just not make us exit as nicely. */
- }
- else {
- /* We got a file size report, so we check that there actually is a
- part of the file left to get, or else we go home. */
- if(data->state.resume_from< 0) {
- /* We're supposed to download the last abs(from) bytes */
- if(filesize < -data->state.resume_from) {
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ if(data->set.max_filesize && (filesize > data->set.max_filesize)) {
+ failf(data, "Maximum file size exceeded");
+ return CURLE_FILESIZE_EXCEEDED;
+ }
+ ftp->downloadsize = filesize;
+
+ if(data->state.resume_from) {
+ /* We always (attempt to) get the size of downloads, so it is done before
+ this even when not doing resumes. */
+ if(filesize == -1) {
+ infof(data, "ftp server doesn't support SIZE\n");
+ /* We couldn't get the size and therefore we can't know if there really
+ is a part of the file left to get, although the server will just
+ close the connection when we start the connection so it won't cause
+ us any harm, just not make us exit as nicely. */
+ }
+ else {
+ /* We got a file size report, so we check that there actually is a
+ part of the file left to get, or else we go home. */
+ if(data->state.resume_from< 0) {
+ /* We're supposed to download the last abs(from) bytes */
+ if(filesize < -data->state.resume_from) {
failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T
") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")",
- data->state.resume_from, filesize);
- return CURLE_BAD_DOWNLOAD_RESUME;
- }
- /* convert to size to download */
- ftp->downloadsize = -data->state.resume_from;
- /* download from where? */
- data->state.resume_from = filesize - ftp->downloadsize;
- }
- else {
- if(filesize < data->state.resume_from) {
+ data->state.resume_from, filesize);
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+ /* convert to size to download */
+ ftp->downloadsize = -data->state.resume_from;
+ /* download from where? */
+ data->state.resume_from = filesize - ftp->downloadsize;
+ }
+ else {
+ if(filesize < data->state.resume_from) {
failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T
") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")",
- data->state.resume_from, filesize);
- return CURLE_BAD_DOWNLOAD_RESUME;
- }
- /* Now store the number of bytes we are expected to download */
- ftp->downloadsize = filesize-data->state.resume_from;
- }
- }
-
- if(ftp->downloadsize == 0) {
- /* no data to transfer */
+ data->state.resume_from, filesize);
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+ /* Now store the number of bytes we are expected to download */
+ ftp->downloadsize = filesize-data->state.resume_from;
+ }
+ }
+
+ if(ftp->downloadsize == 0) {
+ /* no data to transfer */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
- infof(data, "File already completely downloaded\n");
-
- /* Set ->transfer so that we won't get any error in ftp_done()
- * because we didn't transfer the any file */
- ftp->transfer = FTPTRANSFER_NONE;
- state(conn, FTP_STOP);
- return CURLE_OK;
- }
-
- /* Set resume file transfer offset */
+ infof(data, "File already completely downloaded\n");
+
+ /* Set ->transfer so that we won't get any error in ftp_done()
+ * because we didn't transfer the any file */
+ ftp->transfer = FTPTRANSFER_NONE;
+ state(conn, FTP_STOP);
+ return CURLE_OK;
+ }
+
+ /* Set resume file transfer offset */
infof(data, "Instructs server to resume from offset %"
CURL_FORMAT_CURL_OFF_T "\n", data->state.resume_from);
-
+
result = Curl_pp_sendf(&ftpc->pp, "REST %" CURL_FORMAT_CURL_OFF_T,
data->state.resume_from);
if(!result)
state(conn, FTP_RETR_REST);
- }
- else {
- /* no resume */
+ }
+ else {
+ /* no resume */
result = Curl_pp_sendf(&ftpc->pp, "RETR %s", ftpc->file);
if(!result)
state(conn, FTP_RETR);
- }
-
- return result;
-}
-
-static CURLcode ftp_state_size_resp(struct connectdata *conn,
- int ftpcode,
- ftpstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+
+ return result;
+}
+
+static CURLcode ftp_state_size_resp(struct connectdata *conn,
+ int ftpcode,
+ ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
curl_off_t filesize = -1;
- char *buf = data->state.buffer;
-
- /* get the size from the ascii string: */
+ char *buf = data->state.buffer;
+
+ /* get the size from the ascii string: */
if(ftpcode == 213) {
/* To allow servers to prepend "rubbish" in the response string, we scan
for all the digits at the end of the response and parse only those as a
@@ -2279,314 +2279,314 @@ static CURLcode ftp_state_size_resp(struct connectdata *conn,
fdigit = start;
/* ignores parsing errors, which will make the size remain unknown */
(void)curlx_strtoofft(fdigit, NULL, 0, &filesize);
-
+
}
else if(ftpcode == 550) { /* "No such file or directory" */
failf(data, "The file does not exist");
return CURLE_REMOTE_FILE_NOT_FOUND;
}
- if(instate == FTP_SIZE) {
-#ifdef CURL_FTP_HTTPSTYLE_HEAD
- if(-1 != filesize) {
+ if(instate == FTP_SIZE) {
+#ifdef CURL_FTP_HTTPSTYLE_HEAD
+ if(-1 != filesize) {
char clbuf[128];
msnprintf(clbuf, sizeof(clbuf),
"Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", filesize);
result = Curl_client_write(conn, CLIENTWRITE_BOTH, clbuf, 0);
- if(result)
- return result;
- }
-#endif
- Curl_pgrsSetDownloadSize(data, filesize);
- result = ftp_state_rest(conn);
- }
- else if(instate == FTP_RETR_SIZE) {
- Curl_pgrsSetDownloadSize(data, filesize);
- result = ftp_state_retr(conn, filesize);
- }
- else if(instate == FTP_STOR_SIZE) {
- data->state.resume_from = filesize;
- result = ftp_state_ul_setup(conn, TRUE);
- }
-
- return result;
-}
-
-static CURLcode ftp_state_rest_resp(struct connectdata *conn,
- int ftpcode,
- ftpstate instate)
-{
- CURLcode result = CURLE_OK;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- switch(instate) {
- case FTP_REST:
- default:
-#ifdef CURL_FTP_HTTPSTYLE_HEAD
- if(ftpcode == 350) {
- char buffer[24]= { "Accept-ranges: bytes\r\n" };
- result = Curl_client_write(conn, CLIENTWRITE_BOTH, buffer, 0);
- if(result)
- return result;
- }
-#endif
- result = ftp_state_prepare_transfer(conn);
- break;
-
- case FTP_RETR_REST:
- if(ftpcode != 350) {
- failf(conn->data, "Couldn't use REST");
- result = CURLE_FTP_COULDNT_USE_REST;
- }
- else {
+ if(result)
+ return result;
+ }
+#endif
+ Curl_pgrsSetDownloadSize(data, filesize);
+ result = ftp_state_rest(conn);
+ }
+ else if(instate == FTP_RETR_SIZE) {
+ Curl_pgrsSetDownloadSize(data, filesize);
+ result = ftp_state_retr(conn, filesize);
+ }
+ else if(instate == FTP_STOR_SIZE) {
+ data->state.resume_from = filesize;
+ result = ftp_state_ul_setup(conn, TRUE);
+ }
+
+ return result;
+}
+
+static CURLcode ftp_state_rest_resp(struct connectdata *conn,
+ int ftpcode,
+ ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ switch(instate) {
+ case FTP_REST:
+ default:
+#ifdef CURL_FTP_HTTPSTYLE_HEAD
+ if(ftpcode == 350) {
+ char buffer[24]= { "Accept-ranges: bytes\r\n" };
+ result = Curl_client_write(conn, CLIENTWRITE_BOTH, buffer, 0);
+ if(result)
+ return result;
+ }
+#endif
+ result = ftp_state_prepare_transfer(conn);
+ break;
+
+ case FTP_RETR_REST:
+ if(ftpcode != 350) {
+ failf(conn->data, "Couldn't use REST");
+ result = CURLE_FTP_COULDNT_USE_REST;
+ }
+ else {
result = Curl_pp_sendf(&ftpc->pp, "RETR %s", ftpc->file);
if(!result)
state(conn, FTP_RETR);
- }
- break;
- }
-
- return result;
-}
-
-static CURLcode ftp_state_stor_resp(struct connectdata *conn,
- int ftpcode, ftpstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+ break;
+ }
+
+ return result;
+}
+
+static CURLcode ftp_state_stor_resp(struct connectdata *conn,
+ int ftpcode, ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
+
if(ftpcode >= 400) {
- failf(data, "Failed FTP upload: %0d", ftpcode);
- state(conn, FTP_STOP);
- /* oops, we never close the sockets! */
- return CURLE_UPLOAD_FAILED;
- }
-
- conn->proto.ftpc.state_saved = instate;
-
- /* PORT means we are now awaiting the server to connect to us. */
- if(data->set.ftp_use_port) {
- bool connected;
-
- state(conn, FTP_STOP); /* no longer in STOR state */
-
- result = AllowServerConnect(conn, &connected);
- if(result)
- return result;
-
- if(!connected) {
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- infof(data, "Data conn was not available immediately\n");
- ftpc->wait_data_conn = TRUE;
- }
-
- return CURLE_OK;
- }
+ failf(data, "Failed FTP upload: %0d", ftpcode);
+ state(conn, FTP_STOP);
+ /* oops, we never close the sockets! */
+ return CURLE_UPLOAD_FAILED;
+ }
+
+ conn->proto.ftpc.state_saved = instate;
+
+ /* PORT means we are now awaiting the server to connect to us. */
+ if(data->set.ftp_use_port) {
+ bool connected;
+
+ state(conn, FTP_STOP); /* no longer in STOR state */
+
+ result = AllowServerConnect(conn, &connected);
+ if(result)
+ return result;
+
+ if(!connected) {
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ infof(data, "Data conn was not available immediately\n");
+ ftpc->wait_data_conn = TRUE;
+ }
+
+ return CURLE_OK;
+ }
return InitiateTransfer(conn);
-}
-
-/* for LIST and RETR responses */
-static CURLcode ftp_state_get_resp(struct connectdata *conn,
- int ftpcode,
- ftpstate instate)
-{
- CURLcode result = CURLE_OK;
+}
+
+/* for LIST and RETR responses */
+static CURLcode ftp_state_get_resp(struct connectdata *conn,
+ int ftpcode,
+ ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.p.ftp;
-
- if((ftpcode == 150) || (ftpcode == 125)) {
-
- /*
- A;
- 150 Opening BINARY mode data connection for /etc/passwd (2241
- bytes). (ok, the file is being transferred)
-
- B:
- 150 Opening ASCII mode data connection for /bin/ls
-
- C:
- 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
-
- D:
- 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes)
-
- E:
- 125 Data connection already open; Transfer starting. */
-
+
+ if((ftpcode == 150) || (ftpcode == 125)) {
+
+ /*
+ A;
+ 150 Opening BINARY mode data connection for /etc/passwd (2241
+ bytes). (ok, the file is being transferred)
+
+ B:
+ 150 Opening ASCII mode data connection for /bin/ls
+
+ C:
+ 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
+
+ D:
+ 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes)
+
+ E:
+ 125 Data connection already open; Transfer starting. */
+
curl_off_t size = -1; /* default unknown size */
-
-
- /*
- * It appears that there are FTP-servers that return size 0 for files when
- * SIZE is used on the file while being in BINARY mode. To work around
- * that (stupid) behavior, we attempt to parse the RETR response even if
- * the SIZE returned size zero.
- *
- * Debugging help from Salvatore Sorrentino on February 26, 2003.
- */
-
- if((instate != FTP_LIST) &&
- !data->set.prefer_ascii &&
- (ftp->downloadsize < 1)) {
- /*
- * It seems directory listings either don't show the size or very
- * often uses size 0 anyway. ASCII transfers may very well turn out
- * that the transferred amount of data is not the same as this line
- * tells, why using this number in those cases only confuses us.
- *
- * Example D above makes this parsing a little tricky */
- char *bytes;
+
+
+ /*
+ * It appears that there are FTP-servers that return size 0 for files when
+ * SIZE is used on the file while being in BINARY mode. To work around
+ * that (stupid) behavior, we attempt to parse the RETR response even if
+ * the SIZE returned size zero.
+ *
+ * Debugging help from Salvatore Sorrentino on February 26, 2003.
+ */
+
+ if((instate != FTP_LIST) &&
+ !data->set.prefer_ascii &&
+ (ftp->downloadsize < 1)) {
+ /*
+ * It seems directory listings either don't show the size or very
+ * often uses size 0 anyway. ASCII transfers may very well turn out
+ * that the transferred amount of data is not the same as this line
+ * tells, why using this number in those cases only confuses us.
+ *
+ * Example D above makes this parsing a little tricky */
+ char *bytes;
char *buf = data->state.buffer;
bytes = strstr(buf, " bytes");
if(bytes) {
long in = (long)(--bytes-buf);
- /* this is a hint there is size information in there! ;-) */
- while(--in) {
- /* scan for the left parenthesis and break there */
- if('(' == *bytes)
- break;
- /* skip only digits */
- if(!ISDIGIT(*bytes)) {
+ /* this is a hint there is size information in there! ;-) */
+ while(--in) {
+ /* scan for the left parenthesis and break there */
+ if('(' == *bytes)
+ break;
+ /* skip only digits */
+ if(!ISDIGIT(*bytes)) {
bytes = NULL;
- break;
- }
- /* one more estep backwards */
- bytes--;
- }
- /* if we have nothing but digits: */
- if(bytes++) {
- /* get the number! */
+ break;
+ }
+ /* one more estep backwards */
+ bytes--;
+ }
+ /* if we have nothing but digits: */
+ if(bytes++) {
+ /* get the number! */
(void)curlx_strtoofft(bytes, NULL, 0, &size);
- }
- }
- }
- else if(ftp->downloadsize > -1)
- size = ftp->downloadsize;
-
- if(size > data->req.maxdownload && data->req.maxdownload > 0)
- size = data->req.size = data->req.maxdownload;
- else if((instate != FTP_LIST) && (data->set.prefer_ascii))
- size = -1; /* kludge for servers that understate ASCII mode file size */
-
+ }
+ }
+ }
+ else if(ftp->downloadsize > -1)
+ size = ftp->downloadsize;
+
+ if(size > data->req.maxdownload && data->req.maxdownload > 0)
+ size = data->req.size = data->req.maxdownload;
+ else if((instate != FTP_LIST) && (data->set.prefer_ascii))
+ size = -1; /* kludge for servers that understate ASCII mode file size */
+
infof(data, "Maxdownload = %" CURL_FORMAT_CURL_OFF_T "\n",
data->req.maxdownload);
-
- if(instate != FTP_LIST)
+
+ if(instate != FTP_LIST)
infof(data, "Getting file with size: %" CURL_FORMAT_CURL_OFF_T "\n",
size);
-
- /* FTP download: */
- conn->proto.ftpc.state_saved = instate;
- conn->proto.ftpc.retr_size_saved = size;
-
- if(data->set.ftp_use_port) {
- bool connected;
-
- result = AllowServerConnect(conn, &connected);
- if(result)
- return result;
-
- if(!connected) {
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- infof(data, "Data conn was not available immediately\n");
- state(conn, FTP_STOP);
- ftpc->wait_data_conn = TRUE;
- }
- }
- else
- return InitiateTransfer(conn);
- }
- else {
- if((instate == FTP_LIST) && (ftpcode == 450)) {
- /* simply no matching files in the dir listing */
- ftp->transfer = FTPTRANSFER_NONE; /* don't download anything */
- state(conn, FTP_STOP); /* this phase is over */
- }
- else {
- failf(data, "RETR response: %03d", ftpcode);
- return instate == FTP_RETR && ftpcode == 550?
- CURLE_REMOTE_FILE_NOT_FOUND:
- CURLE_FTP_COULDNT_RETR_FILE;
- }
- }
-
- return result;
-}
-
-/* after USER, PASS and ACCT */
-static CURLcode ftp_state_loggedin(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
-
+
+ /* FTP download: */
+ conn->proto.ftpc.state_saved = instate;
+ conn->proto.ftpc.retr_size_saved = size;
+
+ if(data->set.ftp_use_port) {
+ bool connected;
+
+ result = AllowServerConnect(conn, &connected);
+ if(result)
+ return result;
+
+ if(!connected) {
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ infof(data, "Data conn was not available immediately\n");
+ state(conn, FTP_STOP);
+ ftpc->wait_data_conn = TRUE;
+ }
+ }
+ else
+ return InitiateTransfer(conn);
+ }
+ else {
+ if((instate == FTP_LIST) && (ftpcode == 450)) {
+ /* simply no matching files in the dir listing */
+ ftp->transfer = FTPTRANSFER_NONE; /* don't download anything */
+ state(conn, FTP_STOP); /* this phase is over */
+ }
+ else {
+ failf(data, "RETR response: %03d", ftpcode);
+ return instate == FTP_RETR && ftpcode == 550?
+ CURLE_REMOTE_FILE_NOT_FOUND:
+ CURLE_FTP_COULDNT_RETR_FILE;
+ }
+ }
+
+ return result;
+}
+
+/* after USER, PASS and ACCT */
+static CURLcode ftp_state_loggedin(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+
if(conn->bits.ftp_use_control_ssl) {
- /* PBSZ = PROTECTION BUFFER SIZE.
-
- The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says:
-
- Specifically, the PROT command MUST be preceded by a PBSZ
- command and a PBSZ command MUST be preceded by a successful
- security data exchange (the TLS negotiation in this case)
-
- ... (and on page 8):
-
- Thus the PBSZ command must still be issued, but must have a
- parameter of '0' to indicate that no buffering is taking place
- and the data connection should not be encapsulated.
- */
+ /* PBSZ = PROTECTION BUFFER SIZE.
+
+ The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says:
+
+ Specifically, the PROT command MUST be preceded by a PBSZ
+ command and a PBSZ command MUST be preceded by a successful
+ security data exchange (the TLS negotiation in this case)
+
+ ... (and on page 8):
+
+ Thus the PBSZ command must still be issued, but must have a
+ parameter of '0' to indicate that no buffering is taking place
+ and the data connection should not be encapsulated.
+ */
result = Curl_pp_sendf(&conn->proto.ftpc.pp, "PBSZ %d", 0);
if(!result)
state(conn, FTP_PBSZ);
- }
- else {
- result = ftp_state_pwd(conn);
- }
- return result;
-}
-
-/* for USER and PASS responses */
-static CURLcode ftp_state_user_resp(struct connectdata *conn,
- int ftpcode,
- ftpstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+ else {
+ result = ftp_state_pwd(conn);
+ }
+ return result;
+}
+
+/* for USER and PASS responses */
+static CURLcode ftp_state_user_resp(struct connectdata *conn,
+ int ftpcode,
+ ftpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- (void)instate; /* no use for this yet */
-
- /* some need password anyway, and others just return 2xx ignored */
- if((ftpcode == 331) && (ftpc->state == FTP_USER)) {
- /* 331 Password required for ...
- (the server requires to send the user's password too) */
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ (void)instate; /* no use for this yet */
+
+ /* some need password anyway, and others just return 2xx ignored */
+ if((ftpcode == 331) && (ftpc->state == FTP_USER)) {
+ /* 331 Password required for ...
+ (the server requires to send the user's password too) */
result = Curl_pp_sendf(&ftpc->pp, "PASS %s", conn->passwd?conn->passwd:"");
if(!result)
state(conn, FTP_PASS);
- }
- else if(ftpcode/100 == 2) {
- /* 230 User ... logged in.
- (the user logged in with or without password) */
- result = ftp_state_loggedin(conn);
- }
- else if(ftpcode == 332) {
- if(data->set.str[STRING_FTP_ACCOUNT]) {
+ }
+ else if(ftpcode/100 == 2) {
+ /* 230 User ... logged in.
+ (the user logged in with or without password) */
+ result = ftp_state_loggedin(conn);
+ }
+ else if(ftpcode == 332) {
+ if(data->set.str[STRING_FTP_ACCOUNT]) {
result = Curl_pp_sendf(&ftpc->pp, "ACCT %s",
data->set.str[STRING_FTP_ACCOUNT]);
if(!result)
state(conn, FTP_ACCT);
- }
- else {
- failf(data, "ACCT requested but none available");
- result = CURLE_LOGIN_DENIED;
- }
- }
- else {
- /* All other response codes, like:
-
- 530 User ... access denied
- (the server denies to log the specified user) */
-
- if(conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] &&
- !conn->data->state.ftp_trying_alternative) {
- /* Ok, USER failed. Let's try the supplied command. */
+ }
+ else {
+ failf(data, "ACCT requested but none available");
+ result = CURLE_LOGIN_DENIED;
+ }
+ }
+ else {
+ /* All other response codes, like:
+
+ 530 User ... access denied
+ (the server denies to log the specified user) */
+
+ if(conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] &&
+ !conn->data->state.ftp_trying_alternative) {
+ /* Ok, USER failed. Let's try the supplied command. */
result =
Curl_pp_sendf(&ftpc->pp, "%s",
conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]);
@@ -2594,609 +2594,609 @@ static CURLcode ftp_state_user_resp(struct connectdata *conn,
conn->data->state.ftp_trying_alternative = TRUE;
state(conn, FTP_USER);
}
- }
- else {
- failf(data, "Access denied: %03d", ftpcode);
- result = CURLE_LOGIN_DENIED;
- }
- }
- return result;
-}
-
-/* for ACCT response */
-static CURLcode ftp_state_acct_resp(struct connectdata *conn,
- int ftpcode)
-{
- CURLcode result = CURLE_OK;
+ }
+ else {
+ failf(data, "Access denied: %03d", ftpcode);
+ result = CURLE_LOGIN_DENIED;
+ }
+ }
+ return result;
+}
+
+/* for ACCT response */
+static CURLcode ftp_state_acct_resp(struct connectdata *conn,
+ int ftpcode)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- if(ftpcode != 230) {
- failf(data, "ACCT rejected by server: %03d", ftpcode);
- result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */
- }
- else
- result = ftp_state_loggedin(conn);
-
- return result;
-}
-
-
-static CURLcode ftp_statemach_act(struct connectdata *conn)
-{
- CURLcode result;
- curl_socket_t sock = conn->sock[FIRSTSOCKET];
+ if(ftpcode != 230) {
+ failf(data, "ACCT rejected by server: %03d", ftpcode);
+ result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */
+ }
+ else
+ result = ftp_state_loggedin(conn);
+
+ return result;
+}
+
+
+static CURLcode ftp_statemach_act(struct connectdata *conn)
+{
+ CURLcode result;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct Curl_easy *data = conn->data;
- int ftpcode;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
- static const char ftpauth[][4] = { "SSL", "TLS" };
- size_t nread = 0;
-
- if(pp->sendleft)
- return Curl_pp_flushsend(pp);
-
- result = ftp_readresp(sock, pp, &ftpcode, &nread);
- if(result)
- return result;
-
- if(ftpcode) {
- /* we have now received a full FTP server response */
- switch(ftpc->state) {
- case FTP_WAIT220:
- if(ftpcode == 230)
- /* 230 User logged in - already! */
- return ftp_state_user_resp(conn, ftpcode, ftpc->state);
- else if(ftpcode != 220) {
- failf(data, "Got a %03d ftp-server response when 220 was expected",
- ftpcode);
+ int ftpcode;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+ static const char ftpauth[][4] = { "SSL", "TLS" };
+ size_t nread = 0;
+
+ if(pp->sendleft)
+ return Curl_pp_flushsend(pp);
+
+ result = ftp_readresp(sock, pp, &ftpcode, &nread);
+ if(result)
+ return result;
+
+ if(ftpcode) {
+ /* we have now received a full FTP server response */
+ switch(ftpc->state) {
+ case FTP_WAIT220:
+ if(ftpcode == 230)
+ /* 230 User logged in - already! */
+ return ftp_state_user_resp(conn, ftpcode, ftpc->state);
+ else if(ftpcode != 220) {
+ failf(data, "Got a %03d ftp-server response when 220 was expected",
+ ftpcode);
return CURLE_WEIRD_SERVER_REPLY;
- }
-
- /* We have received a 220 response fine, now we proceed. */
-#ifdef HAVE_GSSAPI
- if(data->set.krb) {
- /* If not anonymous login, try a secure login. Note that this
- procedure is still BLOCKING. */
-
- Curl_sec_request_prot(conn, "private");
- /* We set private first as default, in case the line below fails to
- set a valid level */
- Curl_sec_request_prot(conn, data->set.str[STRING_KRB_LEVEL]);
-
+ }
+
+ /* We have received a 220 response fine, now we proceed. */
+#ifdef HAVE_GSSAPI
+ if(data->set.krb) {
+ /* If not anonymous login, try a secure login. Note that this
+ procedure is still BLOCKING. */
+
+ Curl_sec_request_prot(conn, "private");
+ /* We set private first as default, in case the line below fails to
+ set a valid level */
+ Curl_sec_request_prot(conn, data->set.str[STRING_KRB_LEVEL]);
+
if(Curl_sec_login(conn))
- infof(data, "Logging in with password in cleartext!\n");
- else
- infof(data, "Authentication successful\n");
- }
-#endif
-
+ infof(data, "Logging in with password in cleartext!\n");
+ else
+ infof(data, "Authentication successful\n");
+ }
+#endif
+
if(data->set.use_ssl && !conn->bits.ftp_use_control_ssl) {
/* We don't have a SSL/TLS control connection yet, but FTPS is
- requested. Try a FTPS connection now */
-
+ requested. Try a FTPS connection now */
+
ftpc->count3 = 0;
- switch(data->set.ftpsslauth) {
- case CURLFTPAUTH_DEFAULT:
- case CURLFTPAUTH_SSL:
- ftpc->count2 = 1; /* add one to get next */
- ftpc->count1 = 0;
- break;
- case CURLFTPAUTH_TLS:
- ftpc->count2 = -1; /* subtract one to get next */
- ftpc->count1 = 1;
- break;
- default:
- failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d",
- (int)data->set.ftpsslauth);
- return CURLE_UNKNOWN_OPTION; /* we don't know what to do */
- }
+ switch(data->set.ftpsslauth) {
+ case CURLFTPAUTH_DEFAULT:
+ case CURLFTPAUTH_SSL:
+ ftpc->count2 = 1; /* add one to get next */
+ ftpc->count1 = 0;
+ break;
+ case CURLFTPAUTH_TLS:
+ ftpc->count2 = -1; /* subtract one to get next */
+ ftpc->count1 = 1;
+ break;
+ default:
+ failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d",
+ (int)data->set.ftpsslauth);
+ return CURLE_UNKNOWN_OPTION; /* we don't know what to do */
+ }
result = Curl_pp_sendf(&ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]);
if(!result)
state(conn, FTP_AUTH);
- }
+ }
else
- result = ftp_state_user(conn);
- break;
-
- case FTP_AUTH:
- /* we have gotten the response to a previous AUTH command */
-
- /* RFC2228 (page 5) says:
- *
- * If the server is willing to accept the named security mechanism,
- * and does not require any security data, it must respond with
- * reply code 234/334.
- */
-
- if((ftpcode == 234) || (ftpcode == 334)) {
- /* Curl_ssl_connect is BLOCKING */
- result = Curl_ssl_connect(conn, FIRSTSOCKET);
+ result = ftp_state_user(conn);
+ break;
+
+ case FTP_AUTH:
+ /* we have gotten the response to a previous AUTH command */
+
+ /* RFC2228 (page 5) says:
+ *
+ * If the server is willing to accept the named security mechanism,
+ * and does not require any security data, it must respond with
+ * reply code 234/334.
+ */
+
+ if((ftpcode == 234) || (ftpcode == 334)) {
+ /* Curl_ssl_connect is BLOCKING */
+ result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(!result) {
conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */
conn->bits.ftp_use_control_ssl = TRUE; /* SSL on control */
- result = ftp_state_user(conn);
- }
- }
- else if(ftpc->count3 < 1) {
- ftpc->count3++;
- ftpc->count1 += ftpc->count2; /* get next attempt */
- result = Curl_pp_sendf(&ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]);
- /* remain in this same state */
- }
- else {
- if(data->set.use_ssl > CURLUSESSL_TRY)
- /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */
- result = CURLE_USE_SSL_FAILED;
- else
- /* ignore the failure and continue */
- result = ftp_state_user(conn);
- }
- break;
-
- case FTP_USER:
- case FTP_PASS:
- result = ftp_state_user_resp(conn, ftpcode, ftpc->state);
- break;
-
- case FTP_ACCT:
- result = ftp_state_acct_resp(conn, ftpcode);
- break;
-
- case FTP_PBSZ:
+ result = ftp_state_user(conn);
+ }
+ }
+ else if(ftpc->count3 < 1) {
+ ftpc->count3++;
+ ftpc->count1 += ftpc->count2; /* get next attempt */
+ result = Curl_pp_sendf(&ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]);
+ /* remain in this same state */
+ }
+ else {
+ if(data->set.use_ssl > CURLUSESSL_TRY)
+ /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */
+ result = CURLE_USE_SSL_FAILED;
+ else
+ /* ignore the failure and continue */
+ result = ftp_state_user(conn);
+ }
+ break;
+
+ case FTP_USER:
+ case FTP_PASS:
+ result = ftp_state_user_resp(conn, ftpcode, ftpc->state);
+ break;
+
+ case FTP_ACCT:
+ result = ftp_state_acct_resp(conn, ftpcode);
+ break;
+
+ case FTP_PBSZ:
result =
Curl_pp_sendf(&ftpc->pp, "PROT %c",
data->set.use_ssl == CURLUSESSL_CONTROL ? 'C' : 'P');
if(!result)
state(conn, FTP_PROT);
- break;
-
- case FTP_PROT:
- if(ftpcode/100 == 2)
- /* We have enabled SSL for the data connection! */
+ break;
+
+ case FTP_PROT:
+ if(ftpcode/100 == 2)
+ /* We have enabled SSL for the data connection! */
conn->bits.ftp_use_data_ssl =
- (data->set.use_ssl != CURLUSESSL_CONTROL) ? TRUE : FALSE;
- /* FTP servers typically responds with 500 if they decide to reject
- our 'P' request */
- else if(data->set.use_ssl > CURLUSESSL_CONTROL)
- /* we failed and bails out */
- return CURLE_USE_SSL_FAILED;
-
- if(data->set.ftp_ccc) {
- /* CCC - Clear Command Channel
- */
+ (data->set.use_ssl != CURLUSESSL_CONTROL) ? TRUE : FALSE;
+ /* FTP servers typically responds with 500 if they decide to reject
+ our 'P' request */
+ else if(data->set.use_ssl > CURLUSESSL_CONTROL)
+ /* we failed and bails out */
+ return CURLE_USE_SSL_FAILED;
+
+ if(data->set.ftp_ccc) {
+ /* CCC - Clear Command Channel
+ */
result = Curl_pp_sendf(&ftpc->pp, "%s", "CCC");
if(!result)
state(conn, FTP_CCC);
- }
+ }
else
- result = ftp_state_pwd(conn);
- break;
-
- case FTP_CCC:
- if(ftpcode < 500) {
- /* First shut down the SSL layer (note: this call will block) */
- result = Curl_ssl_shutdown(conn, FIRSTSOCKET);
-
+ result = ftp_state_pwd(conn);
+ break;
+
+ case FTP_CCC:
+ if(ftpcode < 500) {
+ /* First shut down the SSL layer (note: this call will block) */
+ result = Curl_ssl_shutdown(conn, FIRSTSOCKET);
+
if(result)
- failf(conn->data, "Failed to clear the command channel (CCC)");
- }
+ failf(conn->data, "Failed to clear the command channel (CCC)");
+ }
if(!result)
/* Then continue as normal */
result = ftp_state_pwd(conn);
- break;
-
- case FTP_PWD:
- if(ftpcode == 257) {
+ break;
+
+ case FTP_PWD:
+ if(ftpcode == 257) {
char *ptr = &data->state.buffer[4]; /* start on the first letter */
const size_t buf_size = data->set.buffer_size;
- char *dir;
+ char *dir;
bool entry_extracted = FALSE;
-
- dir = malloc(nread + 1);
- if(!dir)
- return CURLE_OUT_OF_MEMORY;
-
- /* Reply format is like
- 257<space>[rubbish]"<directory-name>"<space><commentary> and the
- RFC959 says
-
- The directory name can contain any character; embedded
- double-quotes should be escaped by double-quotes (the
- "quote-doubling" convention).
- */
-
- /* scan for the first double-quote for non-standard responses */
+
+ dir = malloc(nread + 1);
+ if(!dir)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Reply format is like
+ 257<space>[rubbish]"<directory-name>"<space><commentary> and the
+ RFC959 says
+
+ The directory name can contain any character; embedded
+ double-quotes should be escaped by double-quotes (the
+ "quote-doubling" convention).
+ */
+
+ /* scan for the first double-quote for non-standard responses */
while(ptr < &data->state.buffer[buf_size]
- && *ptr != '\n' && *ptr != '\0' && *ptr != '"')
- ptr++;
-
- if('\"' == *ptr) {
- /* it started good */
+ && *ptr != '\n' && *ptr != '\0' && *ptr != '"')
+ ptr++;
+
+ if('\"' == *ptr) {
+ /* it started good */
char *store;
- ptr++;
- for(store = dir; *ptr;) {
- if('\"' == *ptr) {
- if('\"' == ptr[1]) {
- /* "quote-doubling" */
- *store = ptr[1];
- ptr++;
- }
- else {
- /* end of path */
+ ptr++;
+ for(store = dir; *ptr;) {
+ if('\"' == *ptr) {
+ if('\"' == ptr[1]) {
+ /* "quote-doubling" */
+ *store = ptr[1];
+ ptr++;
+ }
+ else {
+ /* end of path */
entry_extracted = TRUE;
- break; /* get out of this loop */
- }
- }
- else
- *store = *ptr;
- store++;
- ptr++;
- }
+ break; /* get out of this loop */
+ }
+ }
+ else
+ *store = *ptr;
+ store++;
+ ptr++;
+ }
*store = '\0'; /* null-terminate */
}
if(entry_extracted) {
- /* If the path name does not look like an absolute path (i.e.: it
- does not start with a '/'), we probably need some server-dependent
- adjustments. For example, this is the case when connecting to
- an OS400 FTP server: this server supports two name syntaxes,
+ /* If the path name does not look like an absolute path (i.e.: it
+ does not start with a '/'), we probably need some server-dependent
+ adjustments. For example, this is the case when connecting to
+ an OS400 FTP server: this server supports two name syntaxes,
the default one being incompatible with standard paths. In
- addition, this server switches automatically to the regular path
- syntax when one is encountered in a command: this results in
- having an entrypath in the wrong syntax when later used in CWD.
- The method used here is to check the server OS: we do it only
- if the path name looks strange to minimize overhead on other
- systems. */
-
- if(!ftpc->server_os && dir[0] != '/') {
- result = Curl_pp_sendf(&ftpc->pp, "%s", "SYST");
+ addition, this server switches automatically to the regular path
+ syntax when one is encountered in a command: this results in
+ having an entrypath in the wrong syntax when later used in CWD.
+ The method used here is to check the server OS: we do it only
+ if the path name looks strange to minimize overhead on other
+ systems. */
+
+ if(!ftpc->server_os && dir[0] != '/') {
+ result = Curl_pp_sendf(&ftpc->pp, "%s", "SYST");
if(result) {
- free(dir);
- return result;
- }
- Curl_safefree(ftpc->entrypath);
- ftpc->entrypath = dir; /* remember this */
- infof(data, "Entry path is '%s'\n", ftpc->entrypath);
- /* also save it where getinfo can access it: */
- data->state.most_recent_ftp_entrypath = ftpc->entrypath;
- state(conn, FTP_SYST);
- break;
- }
-
- Curl_safefree(ftpc->entrypath);
- ftpc->entrypath = dir; /* remember this */
- infof(data, "Entry path is '%s'\n", ftpc->entrypath);
- /* also save it where getinfo can access it: */
- data->state.most_recent_ftp_entrypath = ftpc->entrypath;
- }
- else {
- /* couldn't get the path */
- free(dir);
- infof(data, "Failed to figure out path\n");
- }
- }
- state(conn, FTP_STOP); /* we are done with the CONNECT phase! */
- DEBUGF(infof(data, "protocol connect phase DONE\n"));
- break;
-
- case FTP_SYST:
- if(ftpcode == 215) {
+ free(dir);
+ return result;
+ }
+ Curl_safefree(ftpc->entrypath);
+ ftpc->entrypath = dir; /* remember this */
+ infof(data, "Entry path is '%s'\n", ftpc->entrypath);
+ /* also save it where getinfo can access it: */
+ data->state.most_recent_ftp_entrypath = ftpc->entrypath;
+ state(conn, FTP_SYST);
+ break;
+ }
+
+ Curl_safefree(ftpc->entrypath);
+ ftpc->entrypath = dir; /* remember this */
+ infof(data, "Entry path is '%s'\n", ftpc->entrypath);
+ /* also save it where getinfo can access it: */
+ data->state.most_recent_ftp_entrypath = ftpc->entrypath;
+ }
+ else {
+ /* couldn't get the path */
+ free(dir);
+ infof(data, "Failed to figure out path\n");
+ }
+ }
+ state(conn, FTP_STOP); /* we are done with the CONNECT phase! */
+ DEBUGF(infof(data, "protocol connect phase DONE\n"));
+ break;
+
+ case FTP_SYST:
+ if(ftpcode == 215) {
char *ptr = &data->state.buffer[4]; /* start on the first letter */
- char *os;
- char *store;
-
- os = malloc(nread + 1);
- if(!os)
- return CURLE_OUT_OF_MEMORY;
-
- /* Reply format is like
- 215<space><OS-name><space><commentary>
- */
- while(*ptr == ' ')
- ptr++;
- for(store = os; *ptr && *ptr != ' ';)
- *store++ = *ptr++;
+ char *os;
+ char *store;
+
+ os = malloc(nread + 1);
+ if(!os)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Reply format is like
+ 215<space><OS-name><space><commentary>
+ */
+ while(*ptr == ' ')
+ ptr++;
+ for(store = os; *ptr && *ptr != ' ';)
+ *store++ = *ptr++;
*store = '\0'; /* null-terminate */
-
- /* Check for special servers here. */
-
+
+ /* Check for special servers here. */
+
if(strcasecompare(os, "OS/400")) {
- /* Force OS400 name format 1. */
- result = Curl_pp_sendf(&ftpc->pp, "%s", "SITE NAMEFMT 1");
+ /* Force OS400 name format 1. */
+ result = Curl_pp_sendf(&ftpc->pp, "%s", "SITE NAMEFMT 1");
if(result) {
- free(os);
- return result;
- }
- /* remember target server OS */
- Curl_safefree(ftpc->server_os);
- ftpc->server_os = os;
- state(conn, FTP_NAMEFMT);
- break;
- }
+ free(os);
+ return result;
+ }
+ /* remember target server OS */
+ Curl_safefree(ftpc->server_os);
+ ftpc->server_os = os;
+ state(conn, FTP_NAMEFMT);
+ break;
+ }
/* Nothing special for the target server. */
/* remember target server OS */
Curl_safefree(ftpc->server_os);
ftpc->server_os = os;
- }
- else {
- /* Cannot identify server OS. Continue anyway and cross fingers. */
- }
-
- state(conn, FTP_STOP); /* we are done with the CONNECT phase! */
- DEBUGF(infof(data, "protocol connect phase DONE\n"));
- break;
-
- case FTP_NAMEFMT:
- if(ftpcode == 250) {
- /* Name format change successful: reload initial path. */
- ftp_state_pwd(conn);
- break;
- }
-
- state(conn, FTP_STOP); /* we are done with the CONNECT phase! */
- DEBUGF(infof(data, "protocol connect phase DONE\n"));
- break;
-
- case FTP_QUOTE:
- case FTP_POSTQUOTE:
- case FTP_RETR_PREQUOTE:
- case FTP_STOR_PREQUOTE:
- if((ftpcode >= 400) && !ftpc->count2) {
- /* failure response code, and not allowed to fail */
- failf(conn->data, "QUOT command failed with %03d", ftpcode);
+ }
+ else {
+ /* Cannot identify server OS. Continue anyway and cross fingers. */
+ }
+
+ state(conn, FTP_STOP); /* we are done with the CONNECT phase! */
+ DEBUGF(infof(data, "protocol connect phase DONE\n"));
+ break;
+
+ case FTP_NAMEFMT:
+ if(ftpcode == 250) {
+ /* Name format change successful: reload initial path. */
+ ftp_state_pwd(conn);
+ break;
+ }
+
+ state(conn, FTP_STOP); /* we are done with the CONNECT phase! */
+ DEBUGF(infof(data, "protocol connect phase DONE\n"));
+ break;
+
+ case FTP_QUOTE:
+ case FTP_POSTQUOTE:
+ case FTP_RETR_PREQUOTE:
+ case FTP_STOR_PREQUOTE:
+ if((ftpcode >= 400) && !ftpc->count2) {
+ /* failure response code, and not allowed to fail */
+ failf(conn->data, "QUOT command failed with %03d", ftpcode);
result = CURLE_QUOTE_ERROR;
- }
+ }
else
result = ftp_state_quote(conn, FALSE, ftpc->state);
- break;
-
- case FTP_CWD:
- if(ftpcode/100 != 2) {
- /* failure to CWD there */
- if(conn->data->set.ftp_create_missing_dirs &&
+ break;
+
+ case FTP_CWD:
+ if(ftpcode/100 != 2) {
+ /* failure to CWD there */
+ if(conn->data->set.ftp_create_missing_dirs &&
ftpc->cwdcount && !ftpc->count2) {
- /* try making it */
- ftpc->count2++; /* counter to prevent CWD-MKD loops */
+ /* try making it */
+ ftpc->count2++; /* counter to prevent CWD-MKD loops */
result = Curl_pp_sendf(&ftpc->pp, "MKD %s",
ftpc->dirs[ftpc->cwdcount - 1]);
if(!result)
state(conn, FTP_MKD);
- }
- else {
- /* return failure */
- failf(data, "Server denied you to change to the given directory");
- ftpc->cwdfail = TRUE; /* don't remember this path as we failed
- to enter it */
+ }
+ else {
+ /* return failure */
+ failf(data, "Server denied you to change to the given directory");
+ ftpc->cwdfail = TRUE; /* don't remember this path as we failed
+ to enter it */
result = CURLE_REMOTE_ACCESS_DENIED;
- }
- }
- else {
- /* success */
+ }
+ }
+ else {
+ /* success */
ftpc->count2 = 0;
if(++ftpc->cwdcount <= ftpc->dirdepth)
- /* send next CWD */
+ /* send next CWD */
result = Curl_pp_sendf(&ftpc->pp, "CWD %s",
ftpc->dirs[ftpc->cwdcount - 1]);
else
- result = ftp_state_mdtm(conn);
- }
- break;
-
- case FTP_MKD:
- if((ftpcode/100 != 2) && !ftpc->count3--) {
- /* failure to MKD the dir */
- failf(data, "Failed to MKD dir: %03d", ftpcode);
+ result = ftp_state_mdtm(conn);
+ }
+ break;
+
+ case FTP_MKD:
+ if((ftpcode/100 != 2) && !ftpc->count3--) {
+ /* failure to MKD the dir */
+ failf(data, "Failed to MKD dir: %03d", ftpcode);
result = CURLE_REMOTE_ACCESS_DENIED;
- }
+ }
else {
state(conn, FTP_CWD);
/* send CWD */
result = Curl_pp_sendf(&ftpc->pp, "CWD %s",
ftpc->dirs[ftpc->cwdcount - 1]);
}
- break;
-
- case FTP_MDTM:
- result = ftp_state_mdtm_resp(conn, ftpcode);
- break;
-
- case FTP_TYPE:
- case FTP_LIST_TYPE:
- case FTP_RETR_TYPE:
- case FTP_STOR_TYPE:
- result = ftp_state_type_resp(conn, ftpcode, ftpc->state);
- break;
-
- case FTP_SIZE:
- case FTP_RETR_SIZE:
- case FTP_STOR_SIZE:
- result = ftp_state_size_resp(conn, ftpcode, ftpc->state);
- break;
-
- case FTP_REST:
- case FTP_RETR_REST:
- result = ftp_state_rest_resp(conn, ftpcode, ftpc->state);
- break;
-
- case FTP_PRET:
- if(ftpcode != 200) {
- /* there only is this one standard OK return code. */
- failf(data, "PRET command not accepted: %03d", ftpcode);
- return CURLE_FTP_PRET_FAILED;
- }
- result = ftp_state_use_pasv(conn);
- break;
-
- case FTP_PASV:
- result = ftp_state_pasv_resp(conn, ftpcode);
- break;
-
- case FTP_PORT:
- result = ftp_state_port_resp(conn, ftpcode);
- break;
-
- case FTP_LIST:
- case FTP_RETR:
- result = ftp_state_get_resp(conn, ftpcode, ftpc->state);
- break;
-
- case FTP_STOR:
- result = ftp_state_stor_resp(conn, ftpcode, ftpc->state);
- break;
-
- case FTP_QUIT:
- /* fallthrough, just stop! */
- default:
- /* internal error */
- state(conn, FTP_STOP);
- break;
- }
- } /* if(ftpcode) */
-
- return result;
-}
-
-
-/* called repeatedly until done from multi.c */
-static CURLcode ftp_multi_statemach(struct connectdata *conn,
- bool *done)
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
+ break;
+
+ case FTP_MDTM:
+ result = ftp_state_mdtm_resp(conn, ftpcode);
+ break;
+
+ case FTP_TYPE:
+ case FTP_LIST_TYPE:
+ case FTP_RETR_TYPE:
+ case FTP_STOR_TYPE:
+ result = ftp_state_type_resp(conn, ftpcode, ftpc->state);
+ break;
+
+ case FTP_SIZE:
+ case FTP_RETR_SIZE:
+ case FTP_STOR_SIZE:
+ result = ftp_state_size_resp(conn, ftpcode, ftpc->state);
+ break;
+
+ case FTP_REST:
+ case FTP_RETR_REST:
+ result = ftp_state_rest_resp(conn, ftpcode, ftpc->state);
+ break;
+
+ case FTP_PRET:
+ if(ftpcode != 200) {
+ /* there only is this one standard OK return code. */
+ failf(data, "PRET command not accepted: %03d", ftpcode);
+ return CURLE_FTP_PRET_FAILED;
+ }
+ result = ftp_state_use_pasv(conn);
+ break;
+
+ case FTP_PASV:
+ result = ftp_state_pasv_resp(conn, ftpcode);
+ break;
+
+ case FTP_PORT:
+ result = ftp_state_port_resp(conn, ftpcode);
+ break;
+
+ case FTP_LIST:
+ case FTP_RETR:
+ result = ftp_state_get_resp(conn, ftpcode, ftpc->state);
+ break;
+
+ case FTP_STOR:
+ result = ftp_state_stor_resp(conn, ftpcode, ftpc->state);
+ break;
+
+ case FTP_QUIT:
+ /* fallthrough, just stop! */
+ default:
+ /* internal error */
+ state(conn, FTP_STOP);
+ break;
+ }
+ } /* if(ftpcode) */
+
+ return result;
+}
+
+
+/* called repeatedly until done from multi.c */
+static CURLcode ftp_multi_statemach(struct connectdata *conn,
+ bool *done)
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
CURLcode result = Curl_pp_statemach(&ftpc->pp, FALSE, FALSE);
-
+
/* Check for the state outside of the Curl_socket_check() return code checks
- since at times we are in fact already in this state when this function
- gets called. */
- *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE;
-
- return result;
-}
-
-static CURLcode ftp_block_statemach(struct connectdata *conn)
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
- CURLcode result = CURLE_OK;
-
- while(ftpc->state != FTP_STOP) {
+ since at times we are in fact already in this state when this function
+ gets called. */
+ *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE;
+
+ return result;
+}
+
+static CURLcode ftp_block_statemach(struct connectdata *conn)
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+ CURLcode result = CURLE_OK;
+
+ while(ftpc->state != FTP_STOP) {
result = Curl_pp_statemach(pp, TRUE, TRUE /* disconnecting */);
- if(result)
- break;
- }
-
- return result;
-}
-
-/*
- * ftp_connect() should do everything that is to be considered a part of
- * the connection phase.
- *
- * The variable 'done' points to will be TRUE if the protocol-layer connect
- * phase is done when this function returns, or FALSE if not.
- *
- */
-static CURLcode ftp_connect(struct connectdata *conn,
+ if(result)
+ break;
+ }
+
+ return result;
+}
+
+/*
+ * ftp_connect() should do everything that is to be considered a part of
+ * the connection phase.
+ *
+ * The variable 'done' points to will be TRUE if the protocol-layer connect
+ * phase is done when this function returns, or FALSE if not.
+ *
+ */
+static CURLcode ftp_connect(struct connectdata *conn,
bool *done) /* see description above */
-{
- CURLcode result;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
-
- *done = FALSE; /* default to not done yet */
-
- /* We always support persistent connections on ftp */
+{
+ CURLcode result;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+
+ *done = FALSE; /* default to not done yet */
+
+ /* We always support persistent connections on ftp */
connkeep(conn, "FTP default");
-
- pp->response_time = RESP_TIMEOUT; /* set default response time-out */
- pp->statemach_act = ftp_statemach_act;
- pp->endofresp = ftp_endofresp;
- pp->conn = conn;
-
- if(conn->handler->flags & PROTOPT_SSL) {
- /* BLOCKING */
- result = Curl_ssl_connect(conn, FIRSTSOCKET);
- if(result)
- return result;
+
+ pp->response_time = RESP_TIMEOUT; /* set default response time-out */
+ pp->statemach_act = ftp_statemach_act;
+ pp->endofresp = ftp_endofresp;
+ pp->conn = conn;
+
+ if(conn->handler->flags & PROTOPT_SSL) {
+ /* BLOCKING */
+ result = Curl_ssl_connect(conn, FIRSTSOCKET);
+ if(result)
+ return result;
conn->bits.ftp_use_control_ssl = TRUE;
- }
-
+ }
+
Curl_pp_setup(pp); /* once per transfer */
- Curl_pp_init(pp); /* init the generic pingpong data */
-
- /* When we connect, we start in the state where we await the 220
- response */
- state(conn, FTP_WAIT220);
-
- result = ftp_multi_statemach(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * ftp_done()
- *
- * The DONE function. This does what needs to be done after a single DO has
- * performed.
- *
- * Input argument is already checked for validity.
- */
-static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
+ Curl_pp_init(pp); /* init the generic pingpong data */
+
+ /* When we connect, we start in the state where we await the 220
+ response */
+ state(conn, FTP_WAIT220);
+
+ result = ftp_multi_statemach(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * ftp_done()
+ *
+ * The DONE function. This does what needs to be done after a single DO has
+ * performed.
+ *
+ * Input argument is already checked for validity.
+ */
+static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
bool premature)
-{
+{
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
- ssize_t nread;
- int ftpcode;
- CURLcode result = CURLE_OK;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+ ssize_t nread;
+ int ftpcode;
+ CURLcode result = CURLE_OK;
char *rawPath = NULL;
size_t pathLen = 0;
-
- if(!ftp)
- return CURLE_OK;
-
- switch(status) {
- case CURLE_BAD_DOWNLOAD_RESUME:
- case CURLE_FTP_WEIRD_PASV_REPLY:
- case CURLE_FTP_PORT_FAILED:
- case CURLE_FTP_ACCEPT_FAILED:
- case CURLE_FTP_ACCEPT_TIMEOUT:
- case CURLE_FTP_COULDNT_SET_TYPE:
- case CURLE_FTP_COULDNT_RETR_FILE:
- case CURLE_PARTIAL_FILE:
- case CURLE_UPLOAD_FAILED:
- case CURLE_REMOTE_ACCESS_DENIED:
- case CURLE_FILESIZE_EXCEEDED:
- case CURLE_REMOTE_FILE_NOT_FOUND:
- case CURLE_WRITE_ERROR:
- /* the connection stays alive fine even though this happened */
- /* fall-through */
- case CURLE_OK: /* doesn't affect the control connection's status */
+
+ if(!ftp)
+ return CURLE_OK;
+
+ switch(status) {
+ case CURLE_BAD_DOWNLOAD_RESUME:
+ case CURLE_FTP_WEIRD_PASV_REPLY:
+ case CURLE_FTP_PORT_FAILED:
+ case CURLE_FTP_ACCEPT_FAILED:
+ case CURLE_FTP_ACCEPT_TIMEOUT:
+ case CURLE_FTP_COULDNT_SET_TYPE:
+ case CURLE_FTP_COULDNT_RETR_FILE:
+ case CURLE_PARTIAL_FILE:
+ case CURLE_UPLOAD_FAILED:
+ case CURLE_REMOTE_ACCESS_DENIED:
+ case CURLE_FILESIZE_EXCEEDED:
+ case CURLE_REMOTE_FILE_NOT_FOUND:
+ case CURLE_WRITE_ERROR:
+ /* the connection stays alive fine even though this happened */
+ /* fall-through */
+ case CURLE_OK: /* doesn't affect the control connection's status */
if(!premature)
- break;
+ break;
- /* until we cope better with prematurely ended requests, let them
- * fallback as if in complete failure */
+ /* until we cope better with prematurely ended requests, let them
+ * fallback as if in complete failure */
/* FALLTHROUGH */
- default: /* by default, an error means the control connection is
- wedged and should not be used anymore */
- ftpc->ctl_valid = FALSE;
- ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the
- current path, as this connection is going */
+ default: /* by default, an error means the control connection is
+ wedged and should not be used anymore */
+ ftpc->ctl_valid = FALSE;
+ ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the
+ current path, as this connection is going */
connclose(conn, "FTP ended with bad error code");
- result = status; /* use the already set error code */
- break;
- }
-
+ result = status; /* use the already set error code */
+ break;
+ }
+
if(data->state.wildcardmatch) {
- if(data->set.chunk_end && ftpc->file) {
+ if(data->set.chunk_end && ftpc->file) {
Curl_set_in_callback(data, true);
- data->set.chunk_end(data->wildcard.customptr);
+ data->set.chunk_end(data->wildcard.customptr);
Curl_set_in_callback(data, false);
- }
- ftpc->known_filesize = -1;
- }
-
+ }
+ ftpc->known_filesize = -1;
+ }
+
if(!result)
/* get the url-decoded "raw" path */
result = Curl_urldecode(data, ftp->path, 0, &rawPath, &pathLen,
@@ -3204,11 +3204,11 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
if(result) {
/* We can limp along anyway (and should try to since we may already be in
* the error path) */
- ftpc->ctl_valid = FALSE; /* mark control connection as bad */
+ ftpc->ctl_valid = FALSE; /* mark control connection as bad */
connclose(conn, "FTP: out of memory!"); /* mark for connection closure */
free(ftpc->prevpath);
- ftpc->prevpath = NULL; /* no path remembering */
- }
+ ftpc->prevpath = NULL; /* no path remembering */
+ }
else { /* remember working directory for connection reuse */
if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
free(rawPath); /* full path => no CWDs happened => keep ftpc->prevpath */
@@ -3223,85 +3223,85 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
rawPath[pathLen] = '\0';
ftpc->prevpath = rawPath;
- }
- else {
+ }
+ else {
free(rawPath);
ftpc->prevpath = NULL; /* no path */
- }
- }
+ }
+ }
if(ftpc->prevpath)
infof(data, "Remembering we are in dir \"%s\"\n", ftpc->prevpath);
- }
-
- /* free the dir tree and file parts */
- freedirs(ftpc);
-
- /* shut down the socket to inform the server we're done */
-
-#ifdef _WIN32_WCE
+ }
+
+ /* free the dir tree and file parts */
+ freedirs(ftpc);
+
+ /* shut down the socket to inform the server we're done */
+
+#ifdef _WIN32_WCE
shutdown(conn->sock[SECONDARYSOCKET], 2); /* SD_BOTH */
-#endif
-
- if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) {
- if(!result && ftpc->dont_check && data->req.maxdownload > 0) {
- /* partial download completed */
- result = Curl_pp_sendf(pp, "%s", "ABOR");
- if(result) {
- failf(data, "Failure sending ABOR command: %s",
- curl_easy_strerror(result));
- ftpc->ctl_valid = FALSE; /* mark control connection as bad */
+#endif
+
+ if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) {
+ if(!result && ftpc->dont_check && data->req.maxdownload > 0) {
+ /* partial download completed */
+ result = Curl_pp_sendf(pp, "%s", "ABOR");
+ if(result) {
+ failf(data, "Failure sending ABOR command: %s",
+ curl_easy_strerror(result));
+ ftpc->ctl_valid = FALSE; /* mark control connection as bad */
connclose(conn, "ABOR command failed"); /* connection closure */
- }
- }
-
- if(conn->ssl[SECONDARYSOCKET].use) {
- /* The secondary socket is using SSL so we must close down that part
- first before we close the socket for real */
- Curl_ssl_close(conn, SECONDARYSOCKET);
-
- /* Note that we keep "use" set to TRUE since that (next) connection is
- still requested to use SSL */
- }
+ }
+ }
+
+ if(conn->ssl[SECONDARYSOCKET].use) {
+ /* The secondary socket is using SSL so we must close down that part
+ first before we close the socket for real */
+ Curl_ssl_close(conn, SECONDARYSOCKET);
+
+ /* Note that we keep "use" set to TRUE since that (next) connection is
+ still requested to use SSL */
+ }
close_secondarysocket(conn);
- }
-
- if(!result && (ftp->transfer == FTPTRANSFER_BODY) && ftpc->ctl_valid &&
- pp->pending_resp && !premature) {
- /*
- * Let's see what the server says about the transfer we just performed,
- * but lower the timeout as sometimes this connection has died while the
- * data has been transferred. This happens when doing through NATs etc that
- * abandon old silent connections.
- */
+ }
+
+ if(!result && (ftp->transfer == FTPTRANSFER_BODY) && ftpc->ctl_valid &&
+ pp->pending_resp && !premature) {
+ /*
+ * Let's see what the server says about the transfer we just performed,
+ * but lower the timeout as sometimes this connection has died while the
+ * data has been transferred. This happens when doing through NATs etc that
+ * abandon old silent connections.
+ */
timediff_t old_time = pp->response_time;
-
- pp->response_time = 60*1000; /* give it only a minute for now */
+
+ pp->response_time = 60*1000; /* give it only a minute for now */
pp->response = Curl_now(); /* timeout relative now */
-
- result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
-
- pp->response_time = old_time; /* set this back to previous value */
-
- if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) {
- failf(data, "control connection looks dead");
- ftpc->ctl_valid = FALSE; /* mark control connection as bad */
+
+ result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
+
+ pp->response_time = old_time; /* set this back to previous value */
+
+ if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) {
+ failf(data, "control connection looks dead");
+ ftpc->ctl_valid = FALSE; /* mark control connection as bad */
connclose(conn, "Timeout or similar in FTP DONE operation"); /* close */
- }
-
- if(result)
- return result;
-
- if(ftpc->dont_check && data->req.maxdownload > 0) {
- /* we have just sent ABOR and there is no reliable way to check if it was
- * successful or not; we have to close the connection now */
- infof(data, "partial download completed, closing connection\n");
+ }
+
+ if(result)
+ return result;
+
+ if(ftpc->dont_check && data->req.maxdownload > 0) {
+ /* we have just sent ABOR and there is no reliable way to check if it was
+ * successful or not; we have to close the connection now */
+ infof(data, "partial download completed, closing connection\n");
connclose(conn, "Partial download with no ability to check");
- return result;
- }
-
- if(!ftpc->dont_check) {
- /* 226 Transfer complete, 250 Requested file action okay, completed. */
+ return result;
+ }
+
+ if(!ftpc->dont_check) {
+ /* 226 Transfer complete, 250 Requested file action okay, completed. */
switch(ftpcode) {
case 226:
case 250:
@@ -3311,231 +3311,231 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
result = CURLE_REMOTE_DISK_FULL;
break;
default:
- failf(data, "server did not report OK, got %d", ftpcode);
- result = CURLE_PARTIAL_FILE;
+ failf(data, "server did not report OK, got %d", ftpcode);
+ result = CURLE_PARTIAL_FILE;
break;
- }
- }
- }
-
- if(result || premature)
- /* the response code from the transfer showed an error already so no
- use checking further */
- ;
- else if(data->set.upload) {
+ }
+ }
+ }
+
+ if(result || premature)
+ /* the response code from the transfer showed an error already so no
+ use checking further */
+ ;
+ else if(data->set.upload) {
if((-1 != data->state.infilesize) &&
(data->state.infilesize != data->req.writebytecount) &&
- !data->set.crlf &&
- (ftp->transfer == FTPTRANSFER_BODY)) {
+ !data->set.crlf &&
+ (ftp->transfer == FTPTRANSFER_BODY)) {
failf(data, "Uploaded unaligned file size (%" CURL_FORMAT_CURL_OFF_T
" out of %" CURL_FORMAT_CURL_OFF_T " bytes)",
data->req.bytecount, data->state.infilesize);
- result = CURLE_PARTIAL_FILE;
- }
- }
- else {
- if((-1 != data->req.size) &&
+ result = CURLE_PARTIAL_FILE;
+ }
+ }
+ else {
+ if((-1 != data->req.size) &&
(data->req.size != data->req.bytecount) &&
-#ifdef CURL_DO_LINEEND_CONV
- /* Most FTP servers don't adjust their file SIZE response for CRLFs, so
- * we'll check to see if the discrepancy can be explained by the number
- * of CRLFs we've changed to LFs.
- */
- ((data->req.size + data->state.crlf_conversions) !=
+#ifdef CURL_DO_LINEEND_CONV
+ /* Most FTP servers don't adjust their file SIZE response for CRLFs, so
+ * we'll check to see if the discrepancy can be explained by the number
+ * of CRLFs we've changed to LFs.
+ */
+ ((data->req.size + data->state.crlf_conversions) !=
data->req.bytecount) &&
-#endif /* CURL_DO_LINEEND_CONV */
+#endif /* CURL_DO_LINEEND_CONV */
(data->req.maxdownload != data->req.bytecount)) {
failf(data, "Received only partial file: %" CURL_FORMAT_CURL_OFF_T
" bytes", data->req.bytecount);
- result = CURLE_PARTIAL_FILE;
- }
- else if(!ftpc->dont_check &&
+ result = CURLE_PARTIAL_FILE;
+ }
+ else if(!ftpc->dont_check &&
!data->req.bytecount &&
- (data->req.size>0)) {
- failf(data, "No data was received!");
- result = CURLE_FTP_COULDNT_RETR_FILE;
- }
- }
-
- /* clear these for next connection */
- ftp->transfer = FTPTRANSFER_BODY;
- ftpc->dont_check = FALSE;
-
- /* Send any post-transfer QUOTE strings? */
- if(!status && !result && !premature && data->set.postquote)
- result = ftp_sendquote(conn, data->set.postquote);
+ (data->req.size>0)) {
+ failf(data, "No data was received!");
+ result = CURLE_FTP_COULDNT_RETR_FILE;
+ }
+ }
+
+ /* clear these for next connection */
+ ftp->transfer = FTPTRANSFER_BODY;
+ ftpc->dont_check = FALSE;
+
+ /* Send any post-transfer QUOTE strings? */
+ if(!status && !result && !premature && data->set.postquote)
+ result = ftp_sendquote(conn, data->set.postquote);
Curl_safefree(ftp->pathalloc);
- return result;
-}
-
-/***********************************************************************
- *
- * ftp_sendquote()
- *
- * Where a 'quote' means a list of custom commands to send to the server.
- * The quote list is passed as an argument.
- *
- * BLOCKING
- */
-
-static
-CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote)
-{
- struct curl_slist *item;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
-
- item = quote;
- while(item) {
- if(item->data) {
+ return result;
+}
+
+/***********************************************************************
+ *
+ * ftp_sendquote()
+ *
+ * Where a 'quote' means a list of custom commands to send to the server.
+ * The quote list is passed as an argument.
+ *
+ * BLOCKING
+ */
+
+static
+CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote)
+{
+ struct curl_slist *item;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct pingpong *pp = &ftpc->pp;
+
+ item = quote;
+ while(item) {
+ if(item->data) {
ssize_t nread;
- char *cmd = item->data;
- bool acceptfail = FALSE;
+ char *cmd = item->data;
+ bool acceptfail = FALSE;
CURLcode result;
int ftpcode = 0;
-
- /* if a command starts with an asterisk, which a legal FTP command never
- can, the command will be allowed to fail without it causing any
- aborts or cancels etc. It will cause libcurl to act as if the command
- is successful, whatever the server reponds. */
-
- if(cmd[0] == '*') {
- cmd++;
- acceptfail = TRUE;
- }
-
+
+ /* if a command starts with an asterisk, which a legal FTP command never
+ can, the command will be allowed to fail without it causing any
+ aborts or cancels etc. It will cause libcurl to act as if the command
+ is successful, whatever the server reponds. */
+
+ if(cmd[0] == '*') {
+ cmd++;
+ acceptfail = TRUE;
+ }
+
result = Curl_pp_sendf(&ftpc->pp, "%s", cmd);
if(!result) {
pp->response = Curl_now(); /* timeout relative now */
result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
}
- if(result)
- return result;
-
- if(!acceptfail && (ftpcode >= 400)) {
- failf(conn->data, "QUOT string not accepted: %s", cmd);
- return CURLE_QUOTE_ERROR;
- }
- }
-
- item = item->next;
- }
-
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * ftp_need_type()
- *
- * Returns TRUE if we in the current situation should send TYPE
- */
-static int ftp_need_type(struct connectdata *conn,
- bool ascii_wanted)
-{
- return conn->proto.ftpc.transfertype != (ascii_wanted?'A':'I');
-}
-
-/***********************************************************************
- *
- * ftp_nb_type()
- *
- * Set TYPE. We only deal with ASCII or BINARY so this function
- * sets one of them.
- * If the transfer type is not sent, simulate on OK response in newstate
- */
-static CURLcode ftp_nb_type(struct connectdata *conn,
- bool ascii, ftpstate newstate)
-{
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- CURLcode result;
- char want = (char)(ascii?'A':'I');
-
- if(ftpc->transfertype == want) {
- state(conn, newstate);
- return ftp_state_type_resp(conn, 200, newstate);
- }
-
+ if(result)
+ return result;
+
+ if(!acceptfail && (ftpcode >= 400)) {
+ failf(conn->data, "QUOT string not accepted: %s", cmd);
+ return CURLE_QUOTE_ERROR;
+ }
+ }
+
+ item = item->next;
+ }
+
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * ftp_need_type()
+ *
+ * Returns TRUE if we in the current situation should send TYPE
+ */
+static int ftp_need_type(struct connectdata *conn,
+ bool ascii_wanted)
+{
+ return conn->proto.ftpc.transfertype != (ascii_wanted?'A':'I');
+}
+
+/***********************************************************************
+ *
+ * ftp_nb_type()
+ *
+ * Set TYPE. We only deal with ASCII or BINARY so this function
+ * sets one of them.
+ * If the transfer type is not sent, simulate on OK response in newstate
+ */
+static CURLcode ftp_nb_type(struct connectdata *conn,
+ bool ascii, ftpstate newstate)
+{
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ CURLcode result;
+ char want = (char)(ascii?'A':'I');
+
+ if(ftpc->transfertype == want) {
+ state(conn, newstate);
+ return ftp_state_type_resp(conn, 200, newstate);
+ }
+
result = Curl_pp_sendf(&ftpc->pp, "TYPE %c", want);
if(!result) {
state(conn, newstate);
-
+
/* keep track of our current transfer type */
ftpc->transfertype = want;
}
return result;
-}
-
-/***************************************************************************
- *
- * ftp_pasv_verbose()
- *
- * This function only outputs some informationals about this second connection
- * when we've issued a PASV command before and thus we have connected to a
- * possibly new IP address.
- *
- */
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-static void
-ftp_pasv_verbose(struct connectdata *conn,
+}
+
+/***************************************************************************
+ *
+ * ftp_pasv_verbose()
+ *
+ * This function only outputs some informationals about this second connection
+ * when we've issued a PASV command before and thus we have connected to a
+ * possibly new IP address.
+ *
+ */
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+static void
+ftp_pasv_verbose(struct connectdata *conn,
struct Curl_addrinfo *ai,
- char *newhost, /* ascii version */
- int port)
-{
- char buf[256];
- Curl_printable_address(ai, buf, sizeof(buf));
- infof(conn->data, "Connecting to %s (%s) port %d\n", newhost, buf, port);
-}
-#endif
-
-/*
- * ftp_do_more()
- *
- * This function shall be called when the second FTP (data) connection is
- * connected.
- *
- * 'complete' can return 0 for incomplete, 1 for done and -1 for go back
- * (which basically is only for when PASV is being sent to retry a failed
- * EPSV).
- */
-
-static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
-{
+ char *newhost, /* ascii version */
+ int port)
+{
+ char buf[256];
+ Curl_printable_address(ai, buf, sizeof(buf));
+ infof(conn->data, "Connecting to %s (%s) port %d\n", newhost, buf, port);
+}
+#endif
+
+/*
+ * ftp_do_more()
+ *
+ * This function shall be called when the second FTP (data) connection is
+ * connected.
+ *
+ * 'complete' can return 0 for incomplete, 1 for done and -1 for go back
+ * (which basically is only for when PASV is being sent to retry a failed
+ * EPSV).
+ */
+
+static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
+{
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- CURLcode result = CURLE_OK;
- bool connected = FALSE;
- bool complete = FALSE;
-
- /* the ftp struct is inited in ftp_connect() */
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ CURLcode result = CURLE_OK;
+ bool connected = FALSE;
+ bool complete = FALSE;
+
+ /* the ftp struct is inited in ftp_connect() */
struct FTP *ftp = data->req.p.ftp;
-
- /* if the second connection isn't done yet, wait for it */
- if(!conn->bits.tcpconnect[SECONDARYSOCKET]) {
+
+ /* if the second connection isn't done yet, wait for it */
+ if(!conn->bits.tcpconnect[SECONDARYSOCKET]) {
if(Curl_connect_ongoing(conn)) {
- /* As we're in TUNNEL_CONNECT state now, we know the proxy name and port
+ /* As we're in TUNNEL_CONNECT state now, we know the proxy name and port
aren't used so we blank their arguments. */
- result = Curl_proxyCONNECT(conn, SECONDARYSOCKET, NULL, 0);
-
- return result;
- }
-
- result = Curl_is_connected(conn, SECONDARYSOCKET, &connected);
-
- /* Ready to do more? */
- if(connected) {
- DEBUGF(infof(data, "DO-MORE connected phase starts\n"));
- }
- else {
- if(result && (ftpc->count1 == 0)) {
- *completep = -1; /* go back to DOING please */
- /* this is a EPSV connect failing, try PASV instead */
- return ftp_epsv_disable(conn);
- }
- return result;
- }
- }
-
+ result = Curl_proxyCONNECT(conn, SECONDARYSOCKET, NULL, 0);
+
+ return result;
+ }
+
+ result = Curl_is_connected(conn, SECONDARYSOCKET, &connected);
+
+ /* Ready to do more? */
+ if(connected) {
+ DEBUGF(infof(data, "DO-MORE connected phase starts\n"));
+ }
+ else {
+ if(result && (ftpc->count1 == 0)) {
+ *completep = -1; /* go back to DOING please */
+ /* this is a EPSV connect failing, try PASV instead */
+ return ftp_epsv_disable(conn);
+ }
+ return result;
+ }
+ }
+
#ifndef CURL_DISABLE_PROXY
result = Curl_proxy_connect(conn, SECONDARYSOCKET);
if(result)
@@ -3549,62 +3549,62 @@ static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
return result;
#endif
- if(ftpc->state) {
+ if(ftpc->state) {
/* already in a state so skip the initial commands.
- They are only done to kickstart the do_more state */
- result = ftp_multi_statemach(conn, &complete);
-
- *completep = (int)complete;
-
- /* if we got an error or if we don't wait for a data connection return
- immediately */
+ They are only done to kickstart the do_more state */
+ result = ftp_multi_statemach(conn, &complete);
+
+ *completep = (int)complete;
+
+ /* if we got an error or if we don't wait for a data connection return
+ immediately */
if(result || !ftpc->wait_data_conn)
- return result;
-
+ return result;
+
/* if we reach the end of the FTP state machine here, *complete will be
TRUE but so is ftpc->wait_data_conn, which says we need to wait for the
data connection and therefore we're not actually complete */
*completep = 0;
- }
-
- if(ftp->transfer <= FTPTRANSFER_INFO) {
- /* a transfer is about to take place, or if not a file name was given
- so we'll do a SIZE on it later and then we need the right TYPE first */
-
- if(ftpc->wait_data_conn == TRUE) {
- bool serv_conned;
-
- result = ReceivedServerConnect(conn, &serv_conned);
- if(result)
- return result; /* Failed to accept data connection */
-
- if(serv_conned) {
- /* It looks data connection is established */
- result = AcceptServerConnect(conn);
- ftpc->wait_data_conn = FALSE;
- if(!result)
- result = InitiateTransfer(conn);
-
- if(result)
- return result;
-
- *completep = 1; /* this state is now complete when the server has
- connected back to us */
- }
- }
- else if(data->set.upload) {
- result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_STOR_TYPE);
- if(result)
- return result;
-
- result = ftp_multi_statemach(conn, &complete);
+ }
+
+ if(ftp->transfer <= FTPTRANSFER_INFO) {
+ /* a transfer is about to take place, or if not a file name was given
+ so we'll do a SIZE on it later and then we need the right TYPE first */
+
+ if(ftpc->wait_data_conn == TRUE) {
+ bool serv_conned;
+
+ result = ReceivedServerConnect(conn, &serv_conned);
+ if(result)
+ return result; /* Failed to accept data connection */
+
+ if(serv_conned) {
+ /* It looks data connection is established */
+ result = AcceptServerConnect(conn);
+ ftpc->wait_data_conn = FALSE;
+ if(!result)
+ result = InitiateTransfer(conn);
+
+ if(result)
+ return result;
+
+ *completep = 1; /* this state is now complete when the server has
+ connected back to us */
+ }
+ }
+ else if(data->set.upload) {
+ result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_STOR_TYPE);
+ if(result)
+ return result;
+
+ result = ftp_multi_statemach(conn, &complete);
/* ftpc->wait_data_conn is always false here */
*completep = (int)complete;
- }
- else {
- /* download */
- ftp->downloadsize = -1; /* unknown as of yet */
-
+ }
+ else {
+ /* download */
+ ftp->downloadsize = -1; /* unknown as of yet */
+
result = Curl_range(conn);
if(result == CURLE_OK && data->req.maxdownload >= 0) {
@@ -3612,182 +3612,182 @@ static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
ftpc->dont_check = TRUE;
}
- if(result)
- ;
- else if(data->set.ftp_list_only || !ftpc->file) {
- /* The specified path ends with a slash, and therefore we think this
- is a directory that is requested, use LIST. But before that we
- need to set ASCII transfer mode. */
-
- /* But only if a body transfer was requested. */
- if(ftp->transfer == FTPTRANSFER_BODY) {
- result = ftp_nb_type(conn, TRUE, FTP_LIST_TYPE);
- if(result)
- return result;
- }
- /* otherwise just fall through */
- }
- else {
- result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_RETR_TYPE);
- if(result)
- return result;
- }
-
- result = ftp_multi_statemach(conn, &complete);
- *completep = (int)complete;
- }
- return result;
- }
-
+ if(result)
+ ;
+ else if(data->set.ftp_list_only || !ftpc->file) {
+ /* The specified path ends with a slash, and therefore we think this
+ is a directory that is requested, use LIST. But before that we
+ need to set ASCII transfer mode. */
+
+ /* But only if a body transfer was requested. */
+ if(ftp->transfer == FTPTRANSFER_BODY) {
+ result = ftp_nb_type(conn, TRUE, FTP_LIST_TYPE);
+ if(result)
+ return result;
+ }
+ /* otherwise just fall through */
+ }
+ else {
+ result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_RETR_TYPE);
+ if(result)
+ return result;
+ }
+
+ result = ftp_multi_statemach(conn, &complete);
+ *completep = (int)complete;
+ }
+ return result;
+ }
+
/* no data to transfer */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
-
- if(!ftpc->wait_data_conn) {
- /* no waiting for the data connection so this is now complete */
- *completep = 1;
- DEBUGF(infof(data, "DO-MORE phase ends with %d\n", (int)result));
- }
-
- return result;
-}
-
-
-
-/***********************************************************************
- *
- * ftp_perform()
- *
- * This is the actual DO function for FTP. Get a file/directory according to
- * the options previously setup.
- */
-
-static
-CURLcode ftp_perform(struct connectdata *conn,
- bool *connected, /* connect status after PASV / PORT */
- bool *dophase_done)
-{
- /* this is FTP and no proxy */
+
+ if(!ftpc->wait_data_conn) {
+ /* no waiting for the data connection so this is now complete */
+ *completep = 1;
+ DEBUGF(infof(data, "DO-MORE phase ends with %d\n", (int)result));
+ }
+
+ return result;
+}
+
+
+
+/***********************************************************************
+ *
+ * ftp_perform()
+ *
+ * This is the actual DO function for FTP. Get a file/directory according to
+ * the options previously setup.
+ */
+
+static
+CURLcode ftp_perform(struct connectdata *conn,
+ bool *connected, /* connect status after PASV / PORT */
+ bool *dophase_done)
+{
+ /* this is FTP and no proxy */
CURLcode result = CURLE_OK;
-
- DEBUGF(infof(conn->data, "DO phase starts\n"));
-
- if(conn->data->set.opt_no_body) {
- /* requested no body means no transfer... */
+
+ DEBUGF(infof(conn->data, "DO phase starts\n"));
+
+ if(conn->data->set.opt_no_body) {
+ /* requested no body means no transfer... */
struct FTP *ftp = conn->data->req.p.ftp;
- ftp->transfer = FTPTRANSFER_INFO;
- }
-
- *dophase_done = FALSE; /* not done yet */
-
- /* start the first command in the DO phase */
- result = ftp_state_quote(conn, TRUE, FTP_QUOTE);
- if(result)
- return result;
-
- /* run the state-machine */
- result = ftp_multi_statemach(conn, dophase_done);
-
- *connected = conn->bits.tcpconnect[SECONDARYSOCKET];
-
- infof(conn->data, "ftp_perform ends with SECONDARY: %d\n", *connected);
-
- if(*dophase_done)
- DEBUGF(infof(conn->data, "DO phase is complete1\n"));
-
- return result;
-}
-
-static void wc_data_dtor(void *ptr)
-{
+ ftp->transfer = FTPTRANSFER_INFO;
+ }
+
+ *dophase_done = FALSE; /* not done yet */
+
+ /* start the first command in the DO phase */
+ result = ftp_state_quote(conn, TRUE, FTP_QUOTE);
+ if(result)
+ return result;
+
+ /* run the state-machine */
+ result = ftp_multi_statemach(conn, dophase_done);
+
+ *connected = conn->bits.tcpconnect[SECONDARYSOCKET];
+
+ infof(conn->data, "ftp_perform ends with SECONDARY: %d\n", *connected);
+
+ if(*dophase_done)
+ DEBUGF(infof(conn->data, "DO phase is complete1\n"));
+
+ return result;
+}
+
+static void wc_data_dtor(void *ptr)
+{
struct ftp_wc *ftpwc = ptr;
if(ftpwc && ftpwc->parser)
Curl_ftp_parselist_data_free(&ftpwc->parser);
free(ftpwc);
-}
-
-static CURLcode init_wc_data(struct connectdata *conn)
-{
- char *last_slash;
+}
+
+static CURLcode init_wc_data(struct connectdata *conn)
+{
+ char *last_slash;
struct FTP *ftp = conn->data->req.p.ftp;
char *path = ftp->path;
- struct WildcardData *wildcard = &(conn->data->wildcard);
+ struct WildcardData *wildcard = &(conn->data->wildcard);
CURLcode result = CURLE_OK;
struct ftp_wc *ftpwc = NULL;
-
+
last_slash = strrchr(ftp->path, '/');
- if(last_slash) {
- last_slash++;
- if(last_slash[0] == '\0') {
- wildcard->state = CURLWC_CLEAN;
+ if(last_slash) {
+ last_slash++;
+ if(last_slash[0] == '\0') {
+ wildcard->state = CURLWC_CLEAN;
result = ftp_parse_url_path(conn);
return result;
- }
+ }
wildcard->pattern = strdup(last_slash);
if(!wildcard->pattern)
return CURLE_OUT_OF_MEMORY;
last_slash[0] = '\0'; /* cut file from path */
- }
- else { /* there is only 'wildcard pattern' or nothing */
- if(path[0]) {
- wildcard->pattern = strdup(path);
- if(!wildcard->pattern)
- return CURLE_OUT_OF_MEMORY;
- path[0] = '\0';
- }
- else { /* only list */
- wildcard->state = CURLWC_CLEAN;
+ }
+ else { /* there is only 'wildcard pattern' or nothing */
+ if(path[0]) {
+ wildcard->pattern = strdup(path);
+ if(!wildcard->pattern)
+ return CURLE_OUT_OF_MEMORY;
+ path[0] = '\0';
+ }
+ else { /* only list */
+ wildcard->state = CURLWC_CLEAN;
result = ftp_parse_url_path(conn);
return result;
- }
- }
-
- /* program continues only if URL is not ending with slash, allocate needed
- resources for wildcard transfer */
-
+ }
+ }
+
+ /* program continues only if URL is not ending with slash, allocate needed
+ resources for wildcard transfer */
+
/* allocate ftp protocol specific wildcard data */
ftpwc = calloc(1, sizeof(struct ftp_wc));
if(!ftpwc) {
result = CURLE_OUT_OF_MEMORY;
goto fail;
- }
-
- /* INITIALIZE parselist structure */
+ }
+
+ /* INITIALIZE parselist structure */
ftpwc->parser = Curl_ftp_parselist_data_alloc();
if(!ftpwc->parser) {
result = CURLE_OUT_OF_MEMORY;
goto fail;
- }
-
+ }
+
wildcard->protdata = ftpwc; /* put it to the WildcardData tmp pointer */
wildcard->dtor = wc_data_dtor;
-
- /* wildcard does not support NOCWD option (assert it?) */
- if(conn->data->set.ftp_filemethod == FTPFILE_NOCWD)
- conn->data->set.ftp_filemethod = FTPFILE_MULTICWD;
-
- /* try to parse ftp url */
+
+ /* wildcard does not support NOCWD option (assert it?) */
+ if(conn->data->set.ftp_filemethod == FTPFILE_NOCWD)
+ conn->data->set.ftp_filemethod = FTPFILE_MULTICWD;
+
+ /* try to parse ftp url */
result = ftp_parse_url_path(conn);
if(result) {
goto fail;
- }
-
+ }
+
wildcard->path = strdup(ftp->path);
- if(!wildcard->path) {
+ if(!wildcard->path) {
result = CURLE_OUT_OF_MEMORY;
goto fail;
- }
-
- /* backup old write_function */
+ }
+
+ /* backup old write_function */
ftpwc->backup.write_function = conn->data->set.fwrite_func;
- /* parsing write function */
- conn->data->set.fwrite_func = Curl_ftp_parselist;
- /* backup old file descriptor */
+ /* parsing write function */
+ conn->data->set.fwrite_func = Curl_ftp_parselist;
+ /* backup old file descriptor */
ftpwc->backup.file_descriptor = conn->data->set.out;
- /* let the writefunc callback know what curl pointer is working with */
- conn->data->set.out = conn;
-
- infof(conn->data, "Wildcard - Parsing started\n");
- return CURLE_OK;
+ /* let the writefunc callback know what curl pointer is working with */
+ conn->data->set.out = conn;
+
+ infof(conn->data, "Wildcard - Parsing started\n");
+ return CURLE_OK;
fail:
if(ftpwc) {
@@ -3798,13 +3798,13 @@ static CURLcode init_wc_data(struct connectdata *conn)
wildcard->dtor = ZERO_NULL;
wildcard->protdata = NULL;
return result;
-}
-
-static CURLcode wc_statemach(struct connectdata *conn)
-{
- struct WildcardData * const wildcard = &(conn->data->wildcard);
+}
+
+static CURLcode wc_statemach(struct connectdata *conn)
+{
+ struct WildcardData * const wildcard = &(conn->data->wildcard);
CURLcode result = CURLE_OK;
-
+
for(;;) {
switch(wildcard->state) {
case CURLWC_INIT:
@@ -3814,7 +3814,7 @@ static CURLcode wc_statemach(struct connectdata *conn)
return result;
wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING;
return result;
-
+
case CURLWC_MATCHING: {
/* In this state is LIST response successfully parsed, so lets restore
previous WRITEFUNCTION callback and WRITEDATA pointer */
@@ -3824,7 +3824,7 @@ static CURLcode wc_statemach(struct connectdata *conn)
ftpwc->backup.write_function = ZERO_NULL;
ftpwc->backup.file_descriptor = NULL;
wildcard->state = CURLWC_DOWNLOADING;
-
+
if(Curl_ftp_parselist_geterror(ftpwc->parser)) {
/* error found in LIST parsing */
wildcard->state = CURLWC_CLEAN;
@@ -3836,22 +3836,22 @@ static CURLcode wc_statemach(struct connectdata *conn)
return CURLE_REMOTE_FILE_NOT_FOUND;
}
continue;
- }
-
+ }
+
case CURLWC_DOWNLOADING: {
/* filelist has at least one file, lets get first one */
struct ftp_conn *ftpc = &conn->proto.ftpc;
struct curl_fileinfo *finfo = wildcard->filelist.head->ptr;
struct FTP *ftp = conn->data->req.p.ftp;
-
+
char *tmp_path = aprintf("%s%s", wildcard->path, finfo->filename);
if(!tmp_path)
return CURLE_OUT_OF_MEMORY;
-
+
/* switch default ftp->path and tmp_path */
free(ftp->pathalloc);
ftp->pathalloc = ftp->path = tmp_path;
-
+
infof(conn->data, "Wildcard - START of \"%s\"\n", finfo->filename);
if(conn->data->set.chunk_bgn) {
long userresponse;
@@ -3871,17 +3871,17 @@ static CURLcode wc_statemach(struct connectdata *conn)
}
if(finfo->filetype != CURLFILETYPE_FILE) {
- wildcard->state = CURLWC_SKIP;
+ wildcard->state = CURLWC_SKIP;
continue;
- }
-
+ }
+
if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE)
ftpc->known_filesize = finfo->size;
-
+
result = ftp_parse_url_path(conn);
if(result)
return result;
-
+
/* we don't need the Curl_fileinfo of first file anymore */
Curl_llist_remove(&wildcard->filelist, wildcard->filelist.head, NULL);
@@ -3892,8 +3892,8 @@ static CURLcode wc_statemach(struct connectdata *conn)
return CURLE_OK;
}
return result;
- }
-
+ }
+
case CURLWC_SKIP: {
if(conn->data->set.chunk_end) {
Curl_set_in_callback(conn->data, true);
@@ -3905,7 +3905,7 @@ static CURLcode wc_statemach(struct connectdata *conn)
CURLWC_CLEAN : CURLWC_DOWNLOADING;
continue;
}
-
+
case CURLWC_CLEAN: {
struct ftp_wc *ftpwc = wildcard->protdata;
result = CURLE_OK;
@@ -3915,7 +3915,7 @@ static CURLcode wc_statemach(struct connectdata *conn)
wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE;
return result;
}
-
+
case CURLWC_DONE:
case CURLWC_ERROR:
case CURLWC_CLEAR:
@@ -3923,153 +3923,153 @@ static CURLcode wc_statemach(struct connectdata *conn)
wildcard->dtor(wildcard->protdata);
return result;
}
- }
+ }
/* UNREACHABLE */
-}
-
-/***********************************************************************
- *
- * ftp_do()
- *
- * This function is registered as 'curl_do' function. It decodes the path
- * parts etc as a wrapper to the actual DO function (ftp_perform).
- *
- * The input argument is already checked for validity.
- */
-static CURLcode ftp_do(struct connectdata *conn, bool *done)
-{
+}
+
+/***********************************************************************
+ *
+ * ftp_do()
+ *
+ * This function is registered as 'curl_do' function. It decodes the path
+ * parts etc as a wrapper to the actual DO function (ftp_perform).
+ *
+ * The input argument is already checked for validity.
+ */
+static CURLcode ftp_do(struct connectdata *conn, bool *done)
+{
CURLcode result = CURLE_OK;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- *done = FALSE; /* default to false */
- ftpc->wait_data_conn = FALSE; /* default to no such wait */
-
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ *done = FALSE; /* default to false */
+ ftpc->wait_data_conn = FALSE; /* default to no such wait */
+
if(conn->data->state.wildcardmatch) {
result = wc_statemach(conn);
- if(conn->data->wildcard.state == CURLWC_SKIP ||
- conn->data->wildcard.state == CURLWC_DONE) {
- /* do not call ftp_regular_transfer */
- return CURLE_OK;
- }
+ if(conn->data->wildcard.state == CURLWC_SKIP ||
+ conn->data->wildcard.state == CURLWC_DONE) {
+ /* do not call ftp_regular_transfer */
+ return CURLE_OK;
+ }
if(result) /* error, loop or skipping the file */
return result;
- }
- else { /* no wildcard FSM needed */
+ }
+ else { /* no wildcard FSM needed */
result = ftp_parse_url_path(conn);
if(result)
return result;
- }
-
+ }
+
result = ftp_regular_transfer(conn, done);
-
+
return result;
-}
-
-/***********************************************************************
- *
- * ftp_quit()
- *
- * This should be called before calling sclose() on an ftp control connection
- * (not data connections). We should then wait for the response from the
- * server before returning. The calling code should then try to close the
- * connection.
- *
- */
-static CURLcode ftp_quit(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
-
- if(conn->proto.ftpc.ctl_valid) {
- result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", "QUIT");
- if(result) {
- failf(conn->data, "Failure sending QUIT command: %s",
- curl_easy_strerror(result));
- conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */
+}
+
+/***********************************************************************
+ *
+ * ftp_quit()
+ *
+ * This should be called before calling sclose() on an ftp control connection
+ * (not data connections). We should then wait for the response from the
+ * server before returning. The calling code should then try to close the
+ * connection.
+ *
+ */
+static CURLcode ftp_quit(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+
+ if(conn->proto.ftpc.ctl_valid) {
+ result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", "QUIT");
+ if(result) {
+ failf(conn->data, "Failure sending QUIT command: %s",
+ curl_easy_strerror(result));
+ conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */
connclose(conn, "QUIT command failed"); /* mark for connection closure */
- state(conn, FTP_STOP);
- return result;
- }
-
- state(conn, FTP_QUIT);
-
- result = ftp_block_statemach(conn);
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * ftp_disconnect()
- *
- * Disconnect from an FTP server. Cleanup protocol-specific per-connection
- * resources. BLOCKING.
- */
-static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection)
-{
+ state(conn, FTP_STOP);
+ return result;
+ }
+
+ state(conn, FTP_QUIT);
+
+ result = ftp_block_statemach(conn);
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * ftp_disconnect()
+ *
+ * Disconnect from an FTP server. Cleanup protocol-specific per-connection
+ * resources. BLOCKING.
+ */
+static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection)
+{
struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct pingpong *pp = &ftpc->pp;
-
- /* We cannot send quit unconditionally. If this connection is stale or
- bad in any way, sending quit and waiting around here will make the
- disconnect wait in vain and cause more problems than we need to.
-
- ftp_quit() will check the state of ftp->ctl_valid. If it's ok it
- will try to send the QUIT command, otherwise it will just return.
- */
- if(dead_connection)
- ftpc->ctl_valid = FALSE;
-
- /* The FTP session may or may not have been allocated/setup at this point! */
- (void)ftp_quit(conn); /* ignore errors on the QUIT */
-
- if(ftpc->entrypath) {
+ struct pingpong *pp = &ftpc->pp;
+
+ /* We cannot send quit unconditionally. If this connection is stale or
+ bad in any way, sending quit and waiting around here will make the
+ disconnect wait in vain and cause more problems than we need to.
+
+ ftp_quit() will check the state of ftp->ctl_valid. If it's ok it
+ will try to send the QUIT command, otherwise it will just return.
+ */
+ if(dead_connection)
+ ftpc->ctl_valid = FALSE;
+
+ /* The FTP session may or may not have been allocated/setup at this point! */
+ (void)ftp_quit(conn); /* ignore errors on the QUIT */
+
+ if(ftpc->entrypath) {
struct Curl_easy *data = conn->data;
- if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) {
- data->state.most_recent_ftp_entrypath = NULL;
- }
+ if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) {
+ data->state.most_recent_ftp_entrypath = NULL;
+ }
Curl_safefree(ftpc->entrypath);
- }
-
- freedirs(ftpc);
+ }
+
+ freedirs(ftpc);
Curl_safefree(ftpc->prevpath);
Curl_safefree(ftpc->server_os);
- Curl_pp_disconnect(pp);
- Curl_sec_end(conn);
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * ftp_parse_url_path()
- *
- * Parse the URL path into separate path components.
- *
- */
-static
-CURLcode ftp_parse_url_path(struct connectdata *conn)
-{
+ Curl_pp_disconnect(pp);
+ Curl_sec_end(conn);
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * ftp_parse_url_path()
+ *
+ * Parse the URL path into separate path components.
+ *
+ */
+static
+CURLcode ftp_parse_url_path(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- /* the ftp struct is already inited in ftp_connect() */
+ /* the ftp struct is already inited in ftp_connect() */
struct FTP *ftp = data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
const char *slashPos = NULL;
const char *fileName = NULL;
CURLcode result = CURLE_OK;
char *rawPath = NULL; /* url-decoded "raw" path */
size_t pathLen = 0;
-
- ftpc->ctl_valid = FALSE;
- ftpc->cwdfail = FALSE;
-
+
+ ftpc->ctl_valid = FALSE;
+ ftpc->cwdfail = FALSE;
+
/* url-decode ftp path before further evaluation */
result = Curl_urldecode(data, ftp->path, 0, &rawPath, &pathLen, REJECT_CTRL);
if(result)
return result;
- switch(data->set.ftp_filemethod) {
+ switch(data->set.ftp_filemethod) {
case FTPFILE_NOCWD: /* fastest, but less standard-compliant */
-
+
if((pathLen > 0) && (rawPath[pathLen - 1] != '/'))
fileName = rawPath; /* this is a full file path */
/*
@@ -4079,7 +4079,7 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
argument in dir/file decisions.
*/
break;
-
+
case FTPFILE_SINGLECWD:
slashPos = strrchr(rawPath, '/');
if(slashPos) {
@@ -4106,70 +4106,70 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
}
else
fileName = rawPath; /* file name only (or empty) */
- break;
-
+ break;
+
default: /* allow pretty much anything */
case FTPFILE_MULTICWD: {
/* current position: begin of next path component */
const char *curPos = rawPath;
-
+
int dirAlloc = 0; /* number of entries allocated for the 'dirs' array */
const char *str = rawPath;
for(; *str != 0; ++str)
if (*str == '/')
++dirAlloc;
-
+
if(dirAlloc > 0) {
ftpc->dirs = calloc(dirAlloc, sizeof(ftpc->dirs[0]));
if(!ftpc->dirs) {
free(rawPath);
return CURLE_OUT_OF_MEMORY;
}
-
+
/* parse the URL path into separate path components */
while((slashPos = strchr(curPos, '/')) != NULL) {
size_t compLen = slashPos - curPos;
-
+
/* path starts with a slash: add that as a directory */
if((compLen == 0) && (ftpc->dirdepth == 0))
++compLen;
-
- /* we skip empty path components, like "x//y" since the FTP command
- CWD requires a parameter and a non-existent parameter a) doesn't
- work on many servers and b) has no effect on the others. */
+
+ /* we skip empty path components, like "x//y" since the FTP command
+ CWD requires a parameter and a non-existent parameter a) doesn't
+ work on many servers and b) has no effect on the others. */
if(compLen > 0) {
char *comp = calloc(1, compLen + 1);
if(!comp) {
free(rawPath);
- return CURLE_OUT_OF_MEMORY;
- }
+ return CURLE_OUT_OF_MEMORY;
+ }
strncpy(comp, curPos, compLen);
ftpc->dirs[ftpc->dirdepth++] = comp;
- }
+ }
curPos = slashPos + 1;
- }
- }
+ }
+ }
DEBUGASSERT(ftpc->dirdepth <= dirAlloc);
fileName = curPos; /* the rest is the file name (or empty) */
- }
- break;
- } /* switch */
-
+ }
+ break;
+ } /* switch */
+
if(fileName && *fileName)
ftpc->file = strdup(fileName);
- else
+ else
ftpc->file = NULL; /* instead of point to a zero byte,
we make it a NULL pointer */
-
- if(data->set.upload && !ftpc->file && (ftp->transfer == FTPTRANSFER_BODY)) {
- /* We need a file name when uploading. Return error! */
- failf(data, "Uploading to a URL without a file name!");
+
+ if(data->set.upload && !ftpc->file && (ftp->transfer == FTPTRANSFER_BODY)) {
+ /* We need a file name when uploading. Return error! */
+ failf(data, "Uploading to a URL without a file name!");
free(rawPath);
- return CURLE_URL_MALFORMAT;
- }
-
- ftpc->cwddone = FALSE; /* default to not done */
-
+ return CURLE_URL_MALFORMAT;
+ }
+
+ ftpc->cwddone = FALSE; /* default to not done */
+
if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
ftpc->cwddone = TRUE; /* skip CWD for absolute paths */
else { /* newly created FTP connections are already in entry path */
@@ -4180,160 +4180,160 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
n = 0; /* CWD to entry for relative paths */
else
n -= ftpc->file?strlen(ftpc->file):0;
-
+
if((strlen(oldPath) == n) && !strncmp(rawPath, oldPath, n)) {
infof(data, "Request has same path as previous transfer\n");
ftpc->cwddone = TRUE;
}
- }
- }
-
+ }
+ }
+
free(rawPath);
- return CURLE_OK;
-}
-
-/* call this when the DO phase has completed */
-static CURLcode ftp_dophase_done(struct connectdata *conn,
- bool connected)
-{
+ return CURLE_OK;
+}
+
+/* call this when the DO phase has completed */
+static CURLcode ftp_dophase_done(struct connectdata *conn,
+ bool connected)
+{
struct FTP *ftp = conn->data->req.p.ftp;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
-
- if(connected) {
- int completed;
- CURLcode result = ftp_do_more(conn, &completed);
-
- if(result) {
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+
+ if(connected) {
+ int completed;
+ CURLcode result = ftp_do_more(conn, &completed);
+
+ if(result) {
close_secondarysocket(conn);
- return result;
- }
- }
-
- if(ftp->transfer != FTPTRANSFER_BODY)
- /* no data to transfer */
+ return result;
+ }
+ }
+
+ if(ftp->transfer != FTPTRANSFER_BODY)
+ /* no data to transfer */
Curl_setup_transfer(conn->data, -1, -1, FALSE, -1);
- else if(!connected)
- /* since we didn't connect now, we want do_more to get called */
- conn->bits.do_more = TRUE;
-
- ftpc->ctl_valid = TRUE; /* seems good */
-
- return CURLE_OK;
-}
-
-/* called from multi.c while DOing */
-static CURLcode ftp_doing(struct connectdata *conn,
- bool *dophase_done)
-{
- CURLcode result = ftp_multi_statemach(conn, dophase_done);
-
- if(result)
- DEBUGF(infof(conn->data, "DO phase failed\n"));
- else if(*dophase_done) {
- result = ftp_dophase_done(conn, FALSE /* not connected */);
-
- DEBUGF(infof(conn->data, "DO phase is complete2\n"));
- }
- return result;
-}
-
-/***********************************************************************
- *
- * ftp_regular_transfer()
- *
- * The input argument is already checked for validity.
- *
- * Performs all commands done before a regular transfer between a local and a
- * remote host.
- *
- * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the
- * ftp_done() function without finding any major problem.
- */
-static
-CURLcode ftp_regular_transfer(struct connectdata *conn,
- bool *dophase_done)
-{
+ else if(!connected)
+ /* since we didn't connect now, we want do_more to get called */
+ conn->bits.do_more = TRUE;
+
+ ftpc->ctl_valid = TRUE; /* seems good */
+
+ return CURLE_OK;
+}
+
+/* called from multi.c while DOing */
+static CURLcode ftp_doing(struct connectdata *conn,
+ bool *dophase_done)
+{
+ CURLcode result = ftp_multi_statemach(conn, dophase_done);
+
+ if(result)
+ DEBUGF(infof(conn->data, "DO phase failed\n"));
+ else if(*dophase_done) {
+ result = ftp_dophase_done(conn, FALSE /* not connected */);
+
+ DEBUGF(infof(conn->data, "DO phase is complete2\n"));
+ }
+ return result;
+}
+
+/***********************************************************************
+ *
+ * ftp_regular_transfer()
+ *
+ * The input argument is already checked for validity.
+ *
+ * Performs all commands done before a regular transfer between a local and a
+ * remote host.
+ *
+ * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the
+ * ftp_done() function without finding any major problem.
+ */
+static
+CURLcode ftp_regular_transfer(struct connectdata *conn,
+ bool *dophase_done)
+{
CURLcode result = CURLE_OK;
bool connected = FALSE;
struct Curl_easy *data = conn->data;
- struct ftp_conn *ftpc = &conn->proto.ftpc;
- data->req.size = -1; /* make sure this is unknown at this point */
-
- Curl_pgrsSetUploadCounter(data, 0);
- Curl_pgrsSetDownloadCounter(data, 0);
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
+ data->req.size = -1; /* make sure this is unknown at this point */
+
+ Curl_pgrsSetUploadCounter(data, 0);
+ Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, -1);
Curl_pgrsSetDownloadSize(data, -1);
-
- ftpc->ctl_valid = TRUE; /* starts good */
-
- result = ftp_perform(conn,
- &connected, /* have we connected after PASV/PORT */
- dophase_done); /* all commands in the DO-phase done? */
-
+
+ ftpc->ctl_valid = TRUE; /* starts good */
+
+ result = ftp_perform(conn,
+ &connected, /* have we connected after PASV/PORT */
+ dophase_done); /* all commands in the DO-phase done? */
+
if(!result) {
-
- if(!*dophase_done)
- /* the DO phase has not completed yet */
- return CURLE_OK;
-
- result = ftp_dophase_done(conn, connected);
-
- if(result)
- return result;
- }
- else
- freedirs(ftpc);
-
- return result;
-}
-
-static CURLcode ftp_setup_connection(struct connectdata *conn)
-{
+
+ if(!*dophase_done)
+ /* the DO phase has not completed yet */
+ return CURLE_OK;
+
+ result = ftp_dophase_done(conn, connected);
+
+ if(result)
+ return result;
+ }
+ else
+ freedirs(ftpc);
+
+ return result;
+}
+
+static CURLcode ftp_setup_connection(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- char *type;
- struct FTP *ftp;
-
+ char *type;
+ struct FTP *ftp;
+
conn->data->req.p.ftp = ftp = calloc(sizeof(struct FTP), 1);
- if(NULL == ftp)
- return CURLE_OUT_OF_MEMORY;
-
+ if(NULL == ftp)
+ return CURLE_OUT_OF_MEMORY;
+
ftp->path = &data->state.up.path[1]; /* don't include the initial slash */
-
- /* FTP URLs support an extension like ";type=<typecode>" that
- * we'll try to get now! */
+
+ /* FTP URLs support an extension like ";type=<typecode>" that
+ * we'll try to get now! */
type = strstr(ftp->path, ";type=");
-
- if(!type)
- type = strstr(conn->host.rawalloc, ";type=");
-
- if(type) {
+
+ if(!type)
+ type = strstr(conn->host.rawalloc, ";type=");
+
+ if(type) {
char command;
- *type = 0; /* it was in the middle of the hostname */
- command = Curl_raw_toupper(type[6]);
-
+ *type = 0; /* it was in the middle of the hostname */
+ command = Curl_raw_toupper(type[6]);
+
switch(command) {
- case 'A': /* ASCII mode */
- data->set.prefer_ascii = TRUE;
- break;
-
- case 'D': /* directory mode */
- data->set.ftp_list_only = TRUE;
- break;
-
- case 'I': /* binary mode */
- default:
- /* switch off ASCII */
- data->set.prefer_ascii = FALSE;
- break;
- }
- }
-
- /* get some initial data into the ftp struct */
- ftp->transfer = FTPTRANSFER_BODY;
- ftp->downloadsize = 0;
- conn->proto.ftpc.known_filesize = -1; /* unknown size for now */
-
- return CURLE_OK;
-}
-
-#endif /* CURL_DISABLE_FTP */
+ case 'A': /* ASCII mode */
+ data->set.prefer_ascii = TRUE;
+ break;
+
+ case 'D': /* directory mode */
+ data->set.ftp_list_only = TRUE;
+ break;
+
+ case 'I': /* binary mode */
+ default:
+ /* switch off ASCII */
+ data->set.prefer_ascii = FALSE;
+ break;
+ }
+ }
+
+ /* get some initial data into the ftp struct */
+ ftp->transfer = FTPTRANSFER_BODY;
+ ftp->downloadsize = 0;
+ conn->proto.ftpc.known_filesize = -1; /* unknown size for now */
+
+ return CURLE_OK;
+}
+
+#endif /* CURL_DISABLE_FTP */
diff --git a/contrib/libs/curl/lib/ftp.h b/contrib/libs/curl/lib/ftp.h
index a2c32f04a3..3ca1458ed8 100644
--- a/contrib/libs/curl/lib/ftp.h
+++ b/contrib/libs/curl/lib/ftp.h
@@ -1,156 +1,156 @@
-#ifndef HEADER_CURL_FTP_H
-#define HEADER_CURL_FTP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_FTP_H
+#define HEADER_CURL_FTP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "pingpong.h"
-
-#ifndef CURL_DISABLE_FTP
-extern const struct Curl_handler Curl_handler_ftp;
-
-#ifdef USE_SSL
-extern const struct Curl_handler Curl_handler_ftps;
-#endif
-
-CURLcode Curl_GetFTPResponse(ssize_t *nread, struct connectdata *conn,
- int *ftpcode);
-#endif /* CURL_DISABLE_FTP */
-
-/****************************************************************************
- * FTP unique setup
- ***************************************************************************/
-typedef enum {
- FTP_STOP, /* do nothing state, stops the state machine */
- FTP_WAIT220, /* waiting for the initial 220 response immediately after
- a connect */
- FTP_AUTH,
- FTP_USER,
- FTP_PASS,
- FTP_ACCT,
- FTP_PBSZ,
- FTP_PROT,
- FTP_CCC,
- FTP_PWD,
- FTP_SYST,
- FTP_NAMEFMT,
- FTP_QUOTE, /* waiting for a response to a command sent in a quote list */
- FTP_RETR_PREQUOTE,
- FTP_STOR_PREQUOTE,
- FTP_POSTQUOTE,
- FTP_CWD, /* change dir */
- FTP_MKD, /* if the dir didn't exist */
- FTP_MDTM, /* to figure out the datestamp */
- FTP_TYPE, /* to set type when doing a head-like request */
- FTP_LIST_TYPE, /* set type when about to do a dir list */
- FTP_RETR_TYPE, /* set type when about to RETR a file */
- FTP_STOR_TYPE, /* set type when about to STOR a file */
- FTP_SIZE, /* get the remote file's size for head-like request */
- FTP_RETR_SIZE, /* get the remote file's size for RETR */
- FTP_STOR_SIZE, /* get the size for STOR */
- FTP_REST, /* when used to check if the server supports it in head-like */
- FTP_RETR_REST, /* when asking for "resume" in for RETR */
- FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */
- FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */
- FTP_PASV, /* generic state for PASV and EPSV, check count1 */
- FTP_LIST, /* generic state for LIST, NLST or a custom list command */
- FTP_RETR,
- FTP_STOR, /* generic state for STOR and APPE */
- FTP_QUIT,
- FTP_LAST /* never used */
-} ftpstate;
-
-struct ftp_parselist_data; /* defined later in ftplistparser.c */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "pingpong.h"
+
+#ifndef CURL_DISABLE_FTP
+extern const struct Curl_handler Curl_handler_ftp;
+
+#ifdef USE_SSL
+extern const struct Curl_handler Curl_handler_ftps;
+#endif
+
+CURLcode Curl_GetFTPResponse(ssize_t *nread, struct connectdata *conn,
+ int *ftpcode);
+#endif /* CURL_DISABLE_FTP */
+
+/****************************************************************************
+ * FTP unique setup
+ ***************************************************************************/
+typedef enum {
+ FTP_STOP, /* do nothing state, stops the state machine */
+ FTP_WAIT220, /* waiting for the initial 220 response immediately after
+ a connect */
+ FTP_AUTH,
+ FTP_USER,
+ FTP_PASS,
+ FTP_ACCT,
+ FTP_PBSZ,
+ FTP_PROT,
+ FTP_CCC,
+ FTP_PWD,
+ FTP_SYST,
+ FTP_NAMEFMT,
+ FTP_QUOTE, /* waiting for a response to a command sent in a quote list */
+ FTP_RETR_PREQUOTE,
+ FTP_STOR_PREQUOTE,
+ FTP_POSTQUOTE,
+ FTP_CWD, /* change dir */
+ FTP_MKD, /* if the dir didn't exist */
+ FTP_MDTM, /* to figure out the datestamp */
+ FTP_TYPE, /* to set type when doing a head-like request */
+ FTP_LIST_TYPE, /* set type when about to do a dir list */
+ FTP_RETR_TYPE, /* set type when about to RETR a file */
+ FTP_STOR_TYPE, /* set type when about to STOR a file */
+ FTP_SIZE, /* get the remote file's size for head-like request */
+ FTP_RETR_SIZE, /* get the remote file's size for RETR */
+ FTP_STOR_SIZE, /* get the size for STOR */
+ FTP_REST, /* when used to check if the server supports it in head-like */
+ FTP_RETR_REST, /* when asking for "resume" in for RETR */
+ FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */
+ FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */
+ FTP_PASV, /* generic state for PASV and EPSV, check count1 */
+ FTP_LIST, /* generic state for LIST, NLST or a custom list command */
+ FTP_RETR,
+ FTP_STOR, /* generic state for STOR and APPE */
+ FTP_QUIT,
+ FTP_LAST /* never used */
+} ftpstate;
+
+struct ftp_parselist_data; /* defined later in ftplistparser.c */
+
struct ftp_wc {
- struct ftp_parselist_data *parser;
-
- struct {
- curl_write_callback write_function;
- FILE *file_descriptor;
- } backup;
-};
-
-typedef enum {
- FTPFILE_MULTICWD = 1, /* as defined by RFC1738 */
- FTPFILE_NOCWD = 2, /* use SIZE / RETR / STOR on the full path */
- FTPFILE_SINGLECWD = 3 /* make one CWD, then SIZE / RETR / STOR on the
- file */
-} curl_ftpfile;
-
+ struct ftp_parselist_data *parser;
+
+ struct {
+ curl_write_callback write_function;
+ FILE *file_descriptor;
+ } backup;
+};
+
+typedef enum {
+ FTPFILE_MULTICWD = 1, /* as defined by RFC1738 */
+ FTPFILE_NOCWD = 2, /* use SIZE / RETR / STOR on the full path */
+ FTPFILE_SINGLECWD = 3 /* make one CWD, then SIZE / RETR / STOR on the
+ file */
+} curl_ftpfile;
+
/* This FTP struct is used in the Curl_easy. All FTP data that is
- connection-oriented must be in FTP_conn to properly deal with the fact that
+ connection-oriented must be in FTP_conn to properly deal with the fact that
perhaps the Curl_easy is changed between the times the connection is
- used. */
-struct FTP {
+ used. */
+struct FTP {
char *path; /* points to the urlpieces struct field */
char *pathalloc; /* if non-NULL a pointer to an allocated path */
-
- /* transfer a file/body or not, done as a typedefed enum just to make
- debuggers display the full symbol and not just the numerical value */
- curl_pp_transfer transfer;
- curl_off_t downloadsize;
-};
-
-
-/* ftp_conn is used for struct connection-oriented data in the connectdata
- struct */
-struct ftp_conn {
- struct pingpong pp;
- char *entrypath; /* the PWD reply when we logged on */
- char **dirs; /* realloc()ed array for path components */
- int dirdepth; /* number of entries used in the 'dirs' array */
+
+ /* transfer a file/body or not, done as a typedefed enum just to make
+ debuggers display the full symbol and not just the numerical value */
+ curl_pp_transfer transfer;
+ curl_off_t downloadsize;
+};
+
+
+/* ftp_conn is used for struct connection-oriented data in the connectdata
+ struct */
+struct ftp_conn {
+ struct pingpong pp;
+ char *entrypath; /* the PWD reply when we logged on */
+ char **dirs; /* realloc()ed array for path components */
+ int dirdepth; /* number of entries used in the 'dirs' array */
char *file; /* url-decoded file name (or path) */
- bool dont_check; /* Set to TRUE to prevent the final (post-transfer)
- file size and 226/250 status check. It should still
- read the line, just ignore the result. */
- bool ctl_valid; /* Tells Curl_ftp_quit() whether or not to do anything. If
- the connection has timed out or been closed, this
- should be FALSE when it gets to Curl_ftp_quit() */
- bool cwddone; /* if it has been determined that the proper CWD combo
- already has been done */
+ bool dont_check; /* Set to TRUE to prevent the final (post-transfer)
+ file size and 226/250 status check. It should still
+ read the line, just ignore the result. */
+ bool ctl_valid; /* Tells Curl_ftp_quit() whether or not to do anything. If
+ the connection has timed out or been closed, this
+ should be FALSE when it gets to Curl_ftp_quit() */
+ bool cwddone; /* if it has been determined that the proper CWD combo
+ already has been done */
int cwdcount; /* number of CWD commands issued */
- bool cwdfail; /* set TRUE if a CWD command fails, as then we must prevent
- caching the current directory */
- bool wait_data_conn; /* this is set TRUE if data connection is waited */
+ bool cwdfail; /* set TRUE if a CWD command fails, as then we must prevent
+ caching the current directory */
+ bool wait_data_conn; /* this is set TRUE if data connection is waited */
char *prevpath; /* url-decoded conn->path from the previous transfer */
- char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a
- and others (A/I or zero) */
- int count1; /* general purpose counter for the state machine */
- int count2; /* general purpose counter for the state machine */
- int count3; /* general purpose counter for the state machine */
- ftpstate state; /* always use ftp.c:state() to change state! */
- ftpstate state_saved; /* transfer type saved to be reloaded after
- data connection is established */
- curl_off_t retr_size_saved; /* Size of retrieved file saved */
+ char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a
+ and others (A/I or zero) */
+ int count1; /* general purpose counter for the state machine */
+ int count2; /* general purpose counter for the state machine */
+ int count3; /* general purpose counter for the state machine */
+ ftpstate state; /* always use ftp.c:state() to change state! */
+ ftpstate state_saved; /* transfer type saved to be reloaded after
+ data connection is established */
+ curl_off_t retr_size_saved; /* Size of retrieved file saved */
char *server_os; /* The target server operating system. */
- curl_off_t known_filesize; /* file size is different from -1, if wildcard
- LIST parsing was done and wc_statemach set
- it */
+ curl_off_t known_filesize; /* file size is different from -1, if wildcard
+ LIST parsing was done and wc_statemach set
+ it */
/* newhost is the (allocated) IP addr or host name to connect the data
connection to */
char *newhost; /* this is the pair to connect the DATA... */
unsigned short newport; /* connection to */
-};
-
-#define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */
-
-#endif /* HEADER_CURL_FTP_H */
+};
+
+#define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */
+
+#endif /* HEADER_CURL_FTP_H */
diff --git a/contrib/libs/curl/lib/ftplistparser.c b/contrib/libs/curl/lib/ftplistparser.c
index 98c89b8a6c..85b8a78d4f 100644
--- a/contrib/libs/curl/lib/ftplistparser.c
+++ b/contrib/libs/curl/lib/ftplistparser.c
@@ -1,610 +1,610 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/**
- * Now implemented:
- *
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/**
+ * Now implemented:
+ *
* 1) Unix version 1
- * drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog
+ * drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog
* 2) Unix version 2
- * drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog
+ * drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog
* 3) Unix version 3
- * drwxr-xr-x 1 1 1 512 Jan 29 23:32 prog
+ * drwxr-xr-x 1 1 1 512 Jan 29 23:32 prog
* 4) Unix symlink
- * lrwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog -> prog2000
- * 5) DOS style
- * 01-29-97 11:32PM <DIR> prog
- */
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_FTP
-
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "fileinfo.h"
-#include "llist.h"
-#include "strtoofft.h"
-#include "ftp.h"
-#include "ftplistparser.h"
-#include "curl_fnmatch.h"
-#include "curl_memory.h"
+ * lrwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog -> prog2000
+ * 5) DOS style
+ * 01-29-97 11:32PM <DIR> prog
+ */
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_FTP
+
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "fileinfo.h"
+#include "llist.h"
+#include "strtoofft.h"
+#include "ftp.h"
+#include "ftplistparser.h"
+#include "curl_fnmatch.h"
+#include "curl_memory.h"
#include "multiif.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/* allocs buffer which will contain one line of LIST command response */
-#define FTP_BUFFER_ALLOCSIZE 160
-
-typedef enum {
- PL_UNIX_TOTALSIZE = 0,
- PL_UNIX_FILETYPE,
- PL_UNIX_PERMISSION,
- PL_UNIX_HLINKS,
- PL_UNIX_USER,
- PL_UNIX_GROUP,
- PL_UNIX_SIZE,
- PL_UNIX_TIME,
- PL_UNIX_FILENAME,
- PL_UNIX_SYMLINK
-} pl_unix_mainstate;
-
-typedef union {
- enum {
- PL_UNIX_TOTALSIZE_INIT = 0,
- PL_UNIX_TOTALSIZE_READING
- } total_dirsize;
-
- enum {
- PL_UNIX_HLINKS_PRESPACE = 0,
- PL_UNIX_HLINKS_NUMBER
- } hlinks;
-
- enum {
- PL_UNIX_USER_PRESPACE = 0,
- PL_UNIX_USER_PARSING
- } user;
-
- enum {
- PL_UNIX_GROUP_PRESPACE = 0,
- PL_UNIX_GROUP_NAME
- } group;
-
- enum {
- PL_UNIX_SIZE_PRESPACE = 0,
- PL_UNIX_SIZE_NUMBER
- } size;
-
- enum {
- PL_UNIX_TIME_PREPART1 = 0,
- PL_UNIX_TIME_PART1,
- PL_UNIX_TIME_PREPART2,
- PL_UNIX_TIME_PART2,
- PL_UNIX_TIME_PREPART3,
- PL_UNIX_TIME_PART3
- } time;
-
- enum {
- PL_UNIX_FILENAME_PRESPACE = 0,
- PL_UNIX_FILENAME_NAME,
- PL_UNIX_FILENAME_WINDOWSEOL
- } filename;
-
- enum {
- PL_UNIX_SYMLINK_PRESPACE = 0,
- PL_UNIX_SYMLINK_NAME,
- PL_UNIX_SYMLINK_PRETARGET1,
- PL_UNIX_SYMLINK_PRETARGET2,
- PL_UNIX_SYMLINK_PRETARGET3,
- PL_UNIX_SYMLINK_PRETARGET4,
- PL_UNIX_SYMLINK_TARGET,
- PL_UNIX_SYMLINK_WINDOWSEOL
- } symlink;
-} pl_unix_substate;
-
-typedef enum {
- PL_WINNT_DATE = 0,
- PL_WINNT_TIME,
- PL_WINNT_DIRORSIZE,
- PL_WINNT_FILENAME
-} pl_winNT_mainstate;
-
-typedef union {
- enum {
- PL_WINNT_TIME_PRESPACE = 0,
- PL_WINNT_TIME_TIME
- } time;
- enum {
- PL_WINNT_DIRORSIZE_PRESPACE = 0,
- PL_WINNT_DIRORSIZE_CONTENT
- } dirorsize;
- enum {
- PL_WINNT_FILENAME_PRESPACE = 0,
- PL_WINNT_FILENAME_CONTENT,
- PL_WINNT_FILENAME_WINEOL
- } filename;
-} pl_winNT_substate;
-
-/* This struct is used in wildcard downloading - for parsing LIST response */
-struct ftp_parselist_data {
- enum {
- OS_TYPE_UNKNOWN = 0,
- OS_TYPE_UNIX,
- OS_TYPE_WIN_NT
- } os_type;
-
- union {
- struct {
- pl_unix_mainstate main;
- pl_unix_substate sub;
- } UNIX;
-
- struct {
- pl_winNT_mainstate main;
- pl_winNT_substate sub;
- } NT;
- } state;
-
- CURLcode error;
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/* allocs buffer which will contain one line of LIST command response */
+#define FTP_BUFFER_ALLOCSIZE 160
+
+typedef enum {
+ PL_UNIX_TOTALSIZE = 0,
+ PL_UNIX_FILETYPE,
+ PL_UNIX_PERMISSION,
+ PL_UNIX_HLINKS,
+ PL_UNIX_USER,
+ PL_UNIX_GROUP,
+ PL_UNIX_SIZE,
+ PL_UNIX_TIME,
+ PL_UNIX_FILENAME,
+ PL_UNIX_SYMLINK
+} pl_unix_mainstate;
+
+typedef union {
+ enum {
+ PL_UNIX_TOTALSIZE_INIT = 0,
+ PL_UNIX_TOTALSIZE_READING
+ } total_dirsize;
+
+ enum {
+ PL_UNIX_HLINKS_PRESPACE = 0,
+ PL_UNIX_HLINKS_NUMBER
+ } hlinks;
+
+ enum {
+ PL_UNIX_USER_PRESPACE = 0,
+ PL_UNIX_USER_PARSING
+ } user;
+
+ enum {
+ PL_UNIX_GROUP_PRESPACE = 0,
+ PL_UNIX_GROUP_NAME
+ } group;
+
+ enum {
+ PL_UNIX_SIZE_PRESPACE = 0,
+ PL_UNIX_SIZE_NUMBER
+ } size;
+
+ enum {
+ PL_UNIX_TIME_PREPART1 = 0,
+ PL_UNIX_TIME_PART1,
+ PL_UNIX_TIME_PREPART2,
+ PL_UNIX_TIME_PART2,
+ PL_UNIX_TIME_PREPART3,
+ PL_UNIX_TIME_PART3
+ } time;
+
+ enum {
+ PL_UNIX_FILENAME_PRESPACE = 0,
+ PL_UNIX_FILENAME_NAME,
+ PL_UNIX_FILENAME_WINDOWSEOL
+ } filename;
+
+ enum {
+ PL_UNIX_SYMLINK_PRESPACE = 0,
+ PL_UNIX_SYMLINK_NAME,
+ PL_UNIX_SYMLINK_PRETARGET1,
+ PL_UNIX_SYMLINK_PRETARGET2,
+ PL_UNIX_SYMLINK_PRETARGET3,
+ PL_UNIX_SYMLINK_PRETARGET4,
+ PL_UNIX_SYMLINK_TARGET,
+ PL_UNIX_SYMLINK_WINDOWSEOL
+ } symlink;
+} pl_unix_substate;
+
+typedef enum {
+ PL_WINNT_DATE = 0,
+ PL_WINNT_TIME,
+ PL_WINNT_DIRORSIZE,
+ PL_WINNT_FILENAME
+} pl_winNT_mainstate;
+
+typedef union {
+ enum {
+ PL_WINNT_TIME_PRESPACE = 0,
+ PL_WINNT_TIME_TIME
+ } time;
+ enum {
+ PL_WINNT_DIRORSIZE_PRESPACE = 0,
+ PL_WINNT_DIRORSIZE_CONTENT
+ } dirorsize;
+ enum {
+ PL_WINNT_FILENAME_PRESPACE = 0,
+ PL_WINNT_FILENAME_CONTENT,
+ PL_WINNT_FILENAME_WINEOL
+ } filename;
+} pl_winNT_substate;
+
+/* This struct is used in wildcard downloading - for parsing LIST response */
+struct ftp_parselist_data {
+ enum {
+ OS_TYPE_UNKNOWN = 0,
+ OS_TYPE_UNIX,
+ OS_TYPE_WIN_NT
+ } os_type;
+
+ union {
+ struct {
+ pl_unix_mainstate main;
+ pl_unix_substate sub;
+ } UNIX;
+
+ struct {
+ pl_winNT_mainstate main;
+ pl_winNT_substate sub;
+ } NT;
+ } state;
+
+ CURLcode error;
struct fileinfo *file_data;
- unsigned int item_length;
- size_t item_offset;
- struct {
- size_t filename;
- size_t user;
- size_t group;
- size_t time;
- size_t perm;
- size_t symlink_target;
- } offsets;
-};
-
-struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void)
-{
- return calloc(1, sizeof(struct ftp_parselist_data));
-}
-
-
+ unsigned int item_length;
+ size_t item_offset;
+ struct {
+ size_t filename;
+ size_t user;
+ size_t group;
+ size_t time;
+ size_t perm;
+ size_t symlink_target;
+ } offsets;
+};
+
+struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void)
+{
+ return calloc(1, sizeof(struct ftp_parselist_data));
+}
+
+
void Curl_ftp_parselist_data_free(struct ftp_parselist_data **parserp)
-{
+{
struct ftp_parselist_data *parser = *parserp;
if(parser)
Curl_fileinfo_cleanup(parser->file_data);
free(parser);
*parserp = NULL;
-}
-
-
-CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data)
-{
- return pl_data->error;
-}
-
-
-#define FTP_LP_MALFORMATED_PERM 0x01000000
-
-static int ftp_pl_get_permission(const char *str)
-{
- int permissions = 0;
- /* USER */
- if(str[0] == 'r')
- permissions |= 1 << 8;
- else if(str[0] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- if(str[1] == 'w')
- permissions |= 1 << 7;
- else if(str[1] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
-
- if(str[2] == 'x')
- permissions |= 1 << 6;
- else if(str[2] == 's') {
- permissions |= 1 << 6;
- permissions |= 1 << 11;
- }
- else if(str[2] == 'S')
- permissions |= 1 << 11;
- else if(str[2] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- /* GROUP */
- if(str[3] == 'r')
- permissions |= 1 << 5;
- else if(str[3] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- if(str[4] == 'w')
- permissions |= 1 << 4;
- else if(str[4] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- if(str[5] == 'x')
- permissions |= 1 << 3;
- else if(str[5] == 's') {
- permissions |= 1 << 3;
- permissions |= 1 << 10;
- }
- else if(str[5] == 'S')
- permissions |= 1 << 10;
- else if(str[5] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- /* others */
- if(str[6] == 'r')
- permissions |= 1 << 2;
- else if(str[6] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- if(str[7] == 'w')
- permissions |= 1 << 1;
- else if(str[7] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
- if(str[8] == 'x')
- permissions |= 1;
- else if(str[8] == 't') {
- permissions |= 1;
- permissions |= 1 << 9;
- }
- else if(str[8] == 'T')
- permissions |= 1 << 9;
- else if(str[8] != '-')
- permissions |= FTP_LP_MALFORMATED_PERM;
-
- return permissions;
-}
-
-static CURLcode ftp_pl_insert_finfo(struct connectdata *conn,
+}
+
+
+CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data)
+{
+ return pl_data->error;
+}
+
+
+#define FTP_LP_MALFORMATED_PERM 0x01000000
+
+static int ftp_pl_get_permission(const char *str)
+{
+ int permissions = 0;
+ /* USER */
+ if(str[0] == 'r')
+ permissions |= 1 << 8;
+ else if(str[0] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ if(str[1] == 'w')
+ permissions |= 1 << 7;
+ else if(str[1] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+
+ if(str[2] == 'x')
+ permissions |= 1 << 6;
+ else if(str[2] == 's') {
+ permissions |= 1 << 6;
+ permissions |= 1 << 11;
+ }
+ else if(str[2] == 'S')
+ permissions |= 1 << 11;
+ else if(str[2] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ /* GROUP */
+ if(str[3] == 'r')
+ permissions |= 1 << 5;
+ else if(str[3] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ if(str[4] == 'w')
+ permissions |= 1 << 4;
+ else if(str[4] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ if(str[5] == 'x')
+ permissions |= 1 << 3;
+ else if(str[5] == 's') {
+ permissions |= 1 << 3;
+ permissions |= 1 << 10;
+ }
+ else if(str[5] == 'S')
+ permissions |= 1 << 10;
+ else if(str[5] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ /* others */
+ if(str[6] == 'r')
+ permissions |= 1 << 2;
+ else if(str[6] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ if(str[7] == 'w')
+ permissions |= 1 << 1;
+ else if(str[7] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+ if(str[8] == 'x')
+ permissions |= 1;
+ else if(str[8] == 't') {
+ permissions |= 1;
+ permissions |= 1 << 9;
+ }
+ else if(str[8] == 'T')
+ permissions |= 1 << 9;
+ else if(str[8] != '-')
+ permissions |= FTP_LP_MALFORMATED_PERM;
+
+ return permissions;
+}
+
+static CURLcode ftp_pl_insert_finfo(struct connectdata *conn,
struct fileinfo *infop)
-{
- curl_fnmatch_callback compare;
- struct WildcardData *wc = &conn->data->wildcard;
+{
+ curl_fnmatch_callback compare;
+ struct WildcardData *wc = &conn->data->wildcard;
struct ftp_wc *ftpwc = wc->protdata;
struct Curl_llist *llist = &wc->filelist;
struct ftp_parselist_data *parser = ftpwc->parser;
- bool add = TRUE;
+ bool add = TRUE;
struct curl_fileinfo *finfo = &infop->info;
-
- /* move finfo pointers to b_data */
- char *str = finfo->b_data;
- finfo->filename = str + parser->offsets.filename;
- finfo->strings.group = parser->offsets.group ?
- str + parser->offsets.group : NULL;
- finfo->strings.perm = parser->offsets.perm ?
- str + parser->offsets.perm : NULL;
- finfo->strings.target = parser->offsets.symlink_target ?
- str + parser->offsets.symlink_target : NULL;
- finfo->strings.time = str + parser->offsets.time;
- finfo->strings.user = parser->offsets.user ?
- str + parser->offsets.user : NULL;
-
- /* get correct fnmatch callback */
- compare = conn->data->set.fnmatch;
- if(!compare)
- compare = Curl_fnmatch;
-
- /* filter pattern-corresponding filenames */
+
+ /* move finfo pointers to b_data */
+ char *str = finfo->b_data;
+ finfo->filename = str + parser->offsets.filename;
+ finfo->strings.group = parser->offsets.group ?
+ str + parser->offsets.group : NULL;
+ finfo->strings.perm = parser->offsets.perm ?
+ str + parser->offsets.perm : NULL;
+ finfo->strings.target = parser->offsets.symlink_target ?
+ str + parser->offsets.symlink_target : NULL;
+ finfo->strings.time = str + parser->offsets.time;
+ finfo->strings.user = parser->offsets.user ?
+ str + parser->offsets.user : NULL;
+
+ /* get correct fnmatch callback */
+ compare = conn->data->set.fnmatch;
+ if(!compare)
+ compare = Curl_fnmatch;
+
+ /* filter pattern-corresponding filenames */
Curl_set_in_callback(conn->data, true);
- if(compare(conn->data->set.fnmatch_data, wc->pattern,
- finfo->filename) == 0) {
- /* discard symlink which is containing multiple " -> " */
- if((finfo->filetype == CURLFILETYPE_SYMLINK) && finfo->strings.target &&
- (strstr(finfo->strings.target, " -> "))) {
- add = FALSE;
- }
- }
- else {
- add = FALSE;
- }
+ if(compare(conn->data->set.fnmatch_data, wc->pattern,
+ finfo->filename) == 0) {
+ /* discard symlink which is containing multiple " -> " */
+ if((finfo->filetype == CURLFILETYPE_SYMLINK) && finfo->strings.target &&
+ (strstr(finfo->strings.target, " -> "))) {
+ add = FALSE;
+ }
+ }
+ else {
+ add = FALSE;
+ }
Curl_set_in_callback(conn->data, false);
-
- if(add) {
+
+ if(add) {
Curl_llist_insert_next(llist, llist->tail, finfo, &infop->list);
- }
- else {
+ }
+ else {
Curl_fileinfo_cleanup(infop);
- }
-
+ }
+
ftpwc->parser->file_data = NULL;
- return CURLE_OK;
-}
-
-size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
- void *connptr)
-{
- size_t bufflen = size*nmemb;
- struct connectdata *conn = (struct connectdata *)connptr;
+ return CURLE_OK;
+}
+
+size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
+ void *connptr)
+{
+ size_t bufflen = size*nmemb;
+ struct connectdata *conn = (struct connectdata *)connptr;
struct ftp_wc *ftpwc = conn->data->wildcard.protdata;
struct ftp_parselist_data *parser = ftpwc->parser;
struct fileinfo *infop;
- struct curl_fileinfo *finfo;
- unsigned long i = 0;
+ struct curl_fileinfo *finfo;
+ unsigned long i = 0;
CURLcode result;
size_t retsize = bufflen;
-
- if(parser->error) { /* error in previous call */
- /* scenario:
- * 1. call => OK..
- * 2. call => OUT_OF_MEMORY (or other error)
- * 3. (last) call => is skipped RIGHT HERE and the error is hadled later
- * in wc_statemach()
- */
+
+ if(parser->error) { /* error in previous call */
+ /* scenario:
+ * 1. call => OK..
+ * 2. call => OUT_OF_MEMORY (or other error)
+ * 3. (last) call => is skipped RIGHT HERE and the error is hadled later
+ * in wc_statemach()
+ */
goto fail;
- }
-
- if(parser->os_type == OS_TYPE_UNKNOWN && bufflen > 0) {
- /* considering info about FILE response format */
- parser->os_type = (buffer[0] >= '0' && buffer[0] <= '9') ?
- OS_TYPE_WIN_NT : OS_TYPE_UNIX;
- }
-
- while(i < bufflen) { /* FSM */
-
- char c = buffer[i];
- if(!parser->file_data) { /* tmp file data is not allocated yet */
- parser->file_data = Curl_fileinfo_alloc();
- if(!parser->file_data) {
- parser->error = CURLE_OUT_OF_MEMORY;
+ }
+
+ if(parser->os_type == OS_TYPE_UNKNOWN && bufflen > 0) {
+ /* considering info about FILE response format */
+ parser->os_type = (buffer[0] >= '0' && buffer[0] <= '9') ?
+ OS_TYPE_WIN_NT : OS_TYPE_UNIX;
+ }
+
+ while(i < bufflen) { /* FSM */
+
+ char c = buffer[i];
+ if(!parser->file_data) { /* tmp file data is not allocated yet */
+ parser->file_data = Curl_fileinfo_alloc();
+ if(!parser->file_data) {
+ parser->error = CURLE_OUT_OF_MEMORY;
goto fail;
- }
+ }
parser->file_data->info.b_data = malloc(FTP_BUFFER_ALLOCSIZE);
if(!parser->file_data->info.b_data) {
parser->error = CURLE_OUT_OF_MEMORY;
goto fail;
- }
+ }
parser->file_data->info.b_size = FTP_BUFFER_ALLOCSIZE;
- parser->item_offset = 0;
- parser->item_length = 0;
- }
-
+ parser->item_offset = 0;
+ parser->item_length = 0;
+ }
+
infop = parser->file_data;
finfo = &infop->info;
- finfo->b_data[finfo->b_used++] = c;
-
- if(finfo->b_used >= finfo->b_size - 1) {
- /* if it is important, extend buffer space for file data */
- char *tmp = realloc(finfo->b_data,
- finfo->b_size + FTP_BUFFER_ALLOCSIZE);
- if(tmp) {
- finfo->b_size += FTP_BUFFER_ALLOCSIZE;
- finfo->b_data = tmp;
- }
- else {
+ finfo->b_data[finfo->b_used++] = c;
+
+ if(finfo->b_used >= finfo->b_size - 1) {
+ /* if it is important, extend buffer space for file data */
+ char *tmp = realloc(finfo->b_data,
+ finfo->b_size + FTP_BUFFER_ALLOCSIZE);
+ if(tmp) {
+ finfo->b_size += FTP_BUFFER_ALLOCSIZE;
+ finfo->b_data = tmp;
+ }
+ else {
Curl_fileinfo_cleanup(parser->file_data);
- parser->file_data = NULL;
- parser->error = CURLE_OUT_OF_MEMORY;
+ parser->file_data = NULL;
+ parser->error = CURLE_OUT_OF_MEMORY;
goto fail;
- }
- }
-
+ }
+ }
+
switch(parser->os_type) {
- case OS_TYPE_UNIX:
+ case OS_TYPE_UNIX:
switch(parser->state.UNIX.main) {
- case PL_UNIX_TOTALSIZE:
- switch(parser->state.UNIX.sub.total_dirsize) {
- case PL_UNIX_TOTALSIZE_INIT:
- if(c == 't') {
- parser->state.UNIX.sub.total_dirsize = PL_UNIX_TOTALSIZE_READING;
- parser->item_length++;
- }
- else {
- parser->state.UNIX.main = PL_UNIX_FILETYPE;
- /* start FSM again not considering size of directory */
- finfo->b_used = 0;
+ case PL_UNIX_TOTALSIZE:
+ switch(parser->state.UNIX.sub.total_dirsize) {
+ case PL_UNIX_TOTALSIZE_INIT:
+ if(c == 't') {
+ parser->state.UNIX.sub.total_dirsize = PL_UNIX_TOTALSIZE_READING;
+ parser->item_length++;
+ }
+ else {
+ parser->state.UNIX.main = PL_UNIX_FILETYPE;
+ /* start FSM again not considering size of directory */
+ finfo->b_used = 0;
continue;
- }
- break;
- case PL_UNIX_TOTALSIZE_READING:
- parser->item_length++;
- if(c == '\r') {
- parser->item_length--;
- finfo->b_used--;
- }
- else if(c == '\n') {
- finfo->b_data[parser->item_length - 1] = 0;
- if(strncmp("total ", finfo->b_data, 6) == 0) {
+ }
+ break;
+ case PL_UNIX_TOTALSIZE_READING:
+ parser->item_length++;
+ if(c == '\r') {
+ parser->item_length--;
+ finfo->b_used--;
+ }
+ else if(c == '\n') {
+ finfo->b_data[parser->item_length - 1] = 0;
+ if(strncmp("total ", finfo->b_data, 6) == 0) {
char *endptr = finfo->b_data + 6;
/* here we can deal with directory size, pass the leading
whitespace and then the digits */
- while(ISSPACE(*endptr))
- endptr++;
+ while(ISSPACE(*endptr))
+ endptr++;
while(ISDIGIT(*endptr))
endptr++;
- if(*endptr != 0) {
+ if(*endptr != 0) {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
+ }
parser->state.UNIX.main = PL_UNIX_FILETYPE;
finfo->b_used = 0;
- }
- else {
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- break;
- }
- break;
- case PL_UNIX_FILETYPE:
+ }
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_FILETYPE:
switch(c) {
- case '-':
- finfo->filetype = CURLFILETYPE_FILE;
- break;
- case 'd':
- finfo->filetype = CURLFILETYPE_DIRECTORY;
- break;
- case 'l':
- finfo->filetype = CURLFILETYPE_SYMLINK;
- break;
- case 'p':
- finfo->filetype = CURLFILETYPE_NAMEDPIPE;
- break;
- case 's':
- finfo->filetype = CURLFILETYPE_SOCKET;
- break;
- case 'c':
- finfo->filetype = CURLFILETYPE_DEVICE_CHAR;
- break;
- case 'b':
- finfo->filetype = CURLFILETYPE_DEVICE_BLOCK;
- break;
- case 'D':
- finfo->filetype = CURLFILETYPE_DOOR;
- break;
- default:
+ case '-':
+ finfo->filetype = CURLFILETYPE_FILE;
+ break;
+ case 'd':
+ finfo->filetype = CURLFILETYPE_DIRECTORY;
+ break;
+ case 'l':
+ finfo->filetype = CURLFILETYPE_SYMLINK;
+ break;
+ case 'p':
+ finfo->filetype = CURLFILETYPE_NAMEDPIPE;
+ break;
+ case 's':
+ finfo->filetype = CURLFILETYPE_SOCKET;
+ break;
+ case 'c':
+ finfo->filetype = CURLFILETYPE_DEVICE_CHAR;
+ break;
+ case 'b':
+ finfo->filetype = CURLFILETYPE_DEVICE_BLOCK;
+ break;
+ case 'D':
+ finfo->filetype = CURLFILETYPE_DOOR;
+ break;
+ default:
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- parser->state.UNIX.main = PL_UNIX_PERMISSION;
- parser->item_length = 0;
- parser->item_offset = 1;
- break;
- case PL_UNIX_PERMISSION:
- parser->item_length++;
- if(parser->item_length <= 9) {
- if(!strchr("rwx-tTsS", c)) {
+ }
+ parser->state.UNIX.main = PL_UNIX_PERMISSION;
+ parser->item_length = 0;
+ parser->item_offset = 1;
+ break;
+ case PL_UNIX_PERMISSION:
+ parser->item_length++;
+ if(parser->item_length <= 9) {
+ if(!strchr("rwx-tTsS", c)) {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- else if(parser->item_length == 10) {
- unsigned int perm;
- if(c != ' ') {
+ }
+ }
+ else if(parser->item_length == 10) {
+ unsigned int perm;
+ if(c != ' ') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- finfo->b_data[10] = 0; /* terminate permissions */
- perm = ftp_pl_get_permission(finfo->b_data + parser->item_offset);
- if(perm & FTP_LP_MALFORMATED_PERM) {
+ }
+ finfo->b_data[10] = 0; /* terminate permissions */
+ perm = ftp_pl_get_permission(finfo->b_data + parser->item_offset);
+ if(perm & FTP_LP_MALFORMATED_PERM) {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
+ }
parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_PERM;
parser->file_data->info.perm = perm;
- parser->offsets.perm = parser->item_offset;
-
- parser->item_length = 0;
- parser->state.UNIX.main = PL_UNIX_HLINKS;
- parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_PRESPACE;
- }
- break;
- case PL_UNIX_HLINKS:
- switch(parser->state.UNIX.sub.hlinks) {
- case PL_UNIX_HLINKS_PRESPACE:
- if(c != ' ') {
- if(c >= '0' && c <= '9') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_NUMBER;
- }
- else {
+ parser->offsets.perm = parser->item_offset;
+
+ parser->item_length = 0;
+ parser->state.UNIX.main = PL_UNIX_HLINKS;
+ parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_PRESPACE;
+ }
+ break;
+ case PL_UNIX_HLINKS:
+ switch(parser->state.UNIX.sub.hlinks) {
+ case PL_UNIX_HLINKS_PRESPACE:
+ if(c != ' ') {
+ if(c >= '0' && c <= '9') {
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_NUMBER;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- break;
- case PL_UNIX_HLINKS_NUMBER:
- parser->item_length ++;
- if(c == ' ') {
- char *p;
- long int hlinks;
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- hlinks = strtol(finfo->b_data + parser->item_offset, &p, 10);
- if(p[0] == '\0' && hlinks != LONG_MAX && hlinks != LONG_MIN) {
+ }
+ }
+ break;
+ case PL_UNIX_HLINKS_NUMBER:
+ parser->item_length ++;
+ if(c == ' ') {
+ char *p;
+ long int hlinks;
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ hlinks = strtol(finfo->b_data + parser->item_offset, &p, 10);
+ if(p[0] == '\0' && hlinks != LONG_MAX && hlinks != LONG_MIN) {
parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_HLINKCOUNT;
parser->file_data->info.hardlinks = hlinks;
- }
- parser->item_length = 0;
- parser->item_offset = 0;
- parser->state.UNIX.main = PL_UNIX_USER;
- parser->state.UNIX.sub.user = PL_UNIX_USER_PRESPACE;
- }
- else if(c < '0' || c > '9') {
+ }
+ parser->item_length = 0;
+ parser->item_offset = 0;
+ parser->state.UNIX.main = PL_UNIX_USER;
+ parser->state.UNIX.sub.user = PL_UNIX_USER_PRESPACE;
+ }
+ else if(c < '0' || c > '9') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- case PL_UNIX_USER:
- switch(parser->state.UNIX.sub.user) {
- case PL_UNIX_USER_PRESPACE:
- if(c != ' ') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.UNIX.sub.user = PL_UNIX_USER_PARSING;
- }
- break;
- case PL_UNIX_USER_PARSING:
- parser->item_length++;
- if(c == ' ') {
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- parser->offsets.user = parser->item_offset;
- parser->state.UNIX.main = PL_UNIX_GROUP;
- parser->state.UNIX.sub.group = PL_UNIX_GROUP_PRESPACE;
- parser->item_offset = 0;
- parser->item_length = 0;
- }
- break;
- }
- break;
- case PL_UNIX_GROUP:
- switch(parser->state.UNIX.sub.group) {
- case PL_UNIX_GROUP_PRESPACE:
- if(c != ' ') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.UNIX.sub.group = PL_UNIX_GROUP_NAME;
- }
- break;
- case PL_UNIX_GROUP_NAME:
- parser->item_length++;
- if(c == ' ') {
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- parser->offsets.group = parser->item_offset;
- parser->state.UNIX.main = PL_UNIX_SIZE;
- parser->state.UNIX.sub.size = PL_UNIX_SIZE_PRESPACE;
- parser->item_offset = 0;
- parser->item_length = 0;
- }
- break;
- }
- break;
- case PL_UNIX_SIZE:
- switch(parser->state.UNIX.sub.size) {
- case PL_UNIX_SIZE_PRESPACE:
- if(c != ' ') {
- if(c >= '0' && c <= '9') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.UNIX.sub.size = PL_UNIX_SIZE_NUMBER;
- }
- else {
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_USER:
+ switch(parser->state.UNIX.sub.user) {
+ case PL_UNIX_USER_PRESPACE:
+ if(c != ' ') {
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.user = PL_UNIX_USER_PARSING;
+ }
+ break;
+ case PL_UNIX_USER_PARSING:
+ parser->item_length++;
+ if(c == ' ') {
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ parser->offsets.user = parser->item_offset;
+ parser->state.UNIX.main = PL_UNIX_GROUP;
+ parser->state.UNIX.sub.group = PL_UNIX_GROUP_PRESPACE;
+ parser->item_offset = 0;
+ parser->item_length = 0;
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_GROUP:
+ switch(parser->state.UNIX.sub.group) {
+ case PL_UNIX_GROUP_PRESPACE:
+ if(c != ' ') {
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.group = PL_UNIX_GROUP_NAME;
+ }
+ break;
+ case PL_UNIX_GROUP_NAME:
+ parser->item_length++;
+ if(c == ' ') {
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ parser->offsets.group = parser->item_offset;
+ parser->state.UNIX.main = PL_UNIX_SIZE;
+ parser->state.UNIX.sub.size = PL_UNIX_SIZE_PRESPACE;
+ parser->item_offset = 0;
+ parser->item_length = 0;
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_SIZE:
+ switch(parser->state.UNIX.sub.size) {
+ case PL_UNIX_SIZE_PRESPACE:
+ if(c != ' ') {
+ if(c >= '0' && c <= '9') {
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.size = PL_UNIX_SIZE_NUMBER;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- break;
- case PL_UNIX_SIZE_NUMBER:
- parser->item_length++;
- if(c == ' ') {
- char *p;
- curl_off_t fsize;
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ }
+ }
+ break;
+ case PL_UNIX_SIZE_NUMBER:
+ parser->item_length++;
+ if(c == ' ') {
+ char *p;
+ curl_off_t fsize;
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
if(!curlx_strtoofft(finfo->b_data + parser->item_offset,
&p, 10, &fsize)) {
if(p[0] == '\0' && fsize != CURL_OFF_T_MAX &&
@@ -616,395 +616,395 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
parser->item_offset = 0;
parser->state.UNIX.main = PL_UNIX_TIME;
parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART1;
- }
- }
- else if(!ISDIGIT(c)) {
+ }
+ }
+ else if(!ISDIGIT(c)) {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- case PL_UNIX_TIME:
- switch(parser->state.UNIX.sub.time) {
- case PL_UNIX_TIME_PREPART1:
- if(c != ' ') {
- if(ISALNUM(c)) {
- parser->item_offset = finfo->b_used -1;
- parser->item_length = 1;
- parser->state.UNIX.sub.time = PL_UNIX_TIME_PART1;
- }
- else {
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_TIME:
+ switch(parser->state.UNIX.sub.time) {
+ case PL_UNIX_TIME_PREPART1:
+ if(c != ' ') {
+ if(ISALNUM(c)) {
+ parser->item_offset = finfo->b_used -1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.time = PL_UNIX_TIME_PART1;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- break;
- case PL_UNIX_TIME_PART1:
- parser->item_length++;
- if(c == ' ') {
- parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART2;
- }
- else if(!ISALNUM(c) && c != '.') {
+ }
+ }
+ break;
+ case PL_UNIX_TIME_PART1:
+ parser->item_length++;
+ if(c == ' ') {
+ parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART2;
+ }
+ else if(!ISALNUM(c) && c != '.') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- case PL_UNIX_TIME_PREPART2:
- parser->item_length++;
- if(c != ' ') {
- if(ISALNUM(c)) {
- parser->state.UNIX.sub.time = PL_UNIX_TIME_PART2;
- }
- else {
+ }
+ break;
+ case PL_UNIX_TIME_PREPART2:
+ parser->item_length++;
+ if(c != ' ') {
+ if(ISALNUM(c)) {
+ parser->state.UNIX.sub.time = PL_UNIX_TIME_PART2;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- break;
- case PL_UNIX_TIME_PART2:
- parser->item_length++;
- if(c == ' ') {
- parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART3;
- }
- else if(!ISALNUM(c) && c != '.') {
+ }
+ }
+ break;
+ case PL_UNIX_TIME_PART2:
+ parser->item_length++;
+ if(c == ' ') {
+ parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART3;
+ }
+ else if(!ISALNUM(c) && c != '.') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- case PL_UNIX_TIME_PREPART3:
- parser->item_length++;
- if(c != ' ') {
- if(ISALNUM(c)) {
- parser->state.UNIX.sub.time = PL_UNIX_TIME_PART3;
- }
- else {
+ }
+ break;
+ case PL_UNIX_TIME_PREPART3:
+ parser->item_length++;
+ if(c != ' ') {
+ if(ISALNUM(c)) {
+ parser->state.UNIX.sub.time = PL_UNIX_TIME_PART3;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- break;
- case PL_UNIX_TIME_PART3:
- parser->item_length++;
- if(c == ' ') {
- finfo->b_data[parser->item_offset + parser->item_length -1] = 0;
- parser->offsets.time = parser->item_offset;
+ }
+ }
+ break;
+ case PL_UNIX_TIME_PART3:
+ parser->item_length++;
+ if(c == ' ') {
+ finfo->b_data[parser->item_offset + parser->item_length -1] = 0;
+ parser->offsets.time = parser->item_offset;
/*
if(ftp_pl_gettime(parser, finfo->b_data + parser->item_offset)) {
parser->file_data->flags |= CURLFINFOFLAG_KNOWN_TIME;
}
*/
- if(finfo->filetype == CURLFILETYPE_SYMLINK) {
- parser->state.UNIX.main = PL_UNIX_SYMLINK;
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRESPACE;
- }
- else {
- parser->state.UNIX.main = PL_UNIX_FILENAME;
- parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_PRESPACE;
- }
- }
- else if(!ISALNUM(c) && c != '.' && c != ':') {
+ if(finfo->filetype == CURLFILETYPE_SYMLINK) {
+ parser->state.UNIX.main = PL_UNIX_SYMLINK;
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRESPACE;
+ }
+ else {
+ parser->state.UNIX.main = PL_UNIX_FILENAME;
+ parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_PRESPACE;
+ }
+ }
+ else if(!ISALNUM(c) && c != '.' && c != ':') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- case PL_UNIX_FILENAME:
- switch(parser->state.UNIX.sub.filename) {
- case PL_UNIX_FILENAME_PRESPACE:
- if(c != ' ') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_NAME;
- }
- break;
- case PL_UNIX_FILENAME_NAME:
- parser->item_length++;
- if(c == '\r') {
- parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_WINDOWSEOL;
- }
- else if(c == '\n') {
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- parser->offsets.filename = parser->item_offset;
- parser->state.UNIX.main = PL_UNIX_FILETYPE;
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_FILENAME:
+ switch(parser->state.UNIX.sub.filename) {
+ case PL_UNIX_FILENAME_PRESPACE:
+ if(c != ' ') {
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_NAME;
+ }
+ break;
+ case PL_UNIX_FILENAME_NAME:
+ parser->item_length++;
+ if(c == '\r') {
+ parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_WINDOWSEOL;
+ }
+ else if(c == '\n') {
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ parser->offsets.filename = parser->item_offset;
+ parser->state.UNIX.main = PL_UNIX_FILETYPE;
result = ftp_pl_insert_finfo(conn, infop);
if(result) {
parser->error = result;
goto fail;
- }
- }
- break;
- case PL_UNIX_FILENAME_WINDOWSEOL:
- if(c == '\n') {
+ }
+ }
+ break;
+ case PL_UNIX_FILENAME_WINDOWSEOL:
+ if(c == '\n') {
finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- parser->offsets.filename = parser->item_offset;
- parser->state.UNIX.main = PL_UNIX_FILETYPE;
+ parser->offsets.filename = parser->item_offset;
+ parser->state.UNIX.main = PL_UNIX_FILETYPE;
result = ftp_pl_insert_finfo(conn, infop);
if(result) {
parser->error = result;
goto fail;
- }
- }
- else {
+ }
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- case PL_UNIX_SYMLINK:
- switch(parser->state.UNIX.sub.symlink) {
- case PL_UNIX_SYMLINK_PRESPACE:
- if(c != ' ') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
- }
- break;
- case PL_UNIX_SYMLINK_NAME:
- parser->item_length++;
- if(c == ' ') {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET1;
- }
- else if(c == '\r' || c == '\n') {
+ }
+ break;
+ }
+ break;
+ case PL_UNIX_SYMLINK:
+ switch(parser->state.UNIX.sub.symlink) {
+ case PL_UNIX_SYMLINK_PRESPACE:
+ if(c != ' ') {
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
+ }
+ break;
+ case PL_UNIX_SYMLINK_NAME:
+ parser->item_length++;
+ if(c == ' ') {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET1;
+ }
+ else if(c == '\r' || c == '\n') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- case PL_UNIX_SYMLINK_PRETARGET1:
- parser->item_length++;
- if(c == '-') {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET2;
- }
- else if(c == '\r' || c == '\n') {
+ }
+ break;
+ case PL_UNIX_SYMLINK_PRETARGET1:
+ parser->item_length++;
+ if(c == '-') {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET2;
+ }
+ else if(c == '\r' || c == '\n') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- else {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
- }
- break;
- case PL_UNIX_SYMLINK_PRETARGET2:
- parser->item_length++;
- if(c == '>') {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET3;
- }
- else if(c == '\r' || c == '\n') {
+ }
+ else {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
+ }
+ break;
+ case PL_UNIX_SYMLINK_PRETARGET2:
+ parser->item_length++;
+ if(c == '>') {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET3;
+ }
+ else if(c == '\r' || c == '\n') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- else {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
- }
- break;
- case PL_UNIX_SYMLINK_PRETARGET3:
- parser->item_length++;
- if(c == ' ') {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET4;
- /* now place where is symlink following */
- finfo->b_data[parser->item_offset + parser->item_length - 4] = 0;
- parser->offsets.filename = parser->item_offset;
- parser->item_length = 0;
- parser->item_offset = 0;
- }
- else if(c == '\r' || c == '\n') {
+ }
+ else {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
+ }
+ break;
+ case PL_UNIX_SYMLINK_PRETARGET3:
+ parser->item_length++;
+ if(c == ' ') {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET4;
+ /* now place where is symlink following */
+ finfo->b_data[parser->item_offset + parser->item_length - 4] = 0;
+ parser->offsets.filename = parser->item_offset;
+ parser->item_length = 0;
+ parser->item_offset = 0;
+ }
+ else if(c == '\r' || c == '\n') {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- else {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
- }
- break;
- case PL_UNIX_SYMLINK_PRETARGET4:
- if(c != '\r' && c != '\n') {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_TARGET;
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- }
- else {
+ }
+ else {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME;
+ }
+ break;
+ case PL_UNIX_SYMLINK_PRETARGET4:
+ if(c != '\r' && c != '\n') {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_TARGET;
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- case PL_UNIX_SYMLINK_TARGET:
+ }
+ break;
+ case PL_UNIX_SYMLINK_TARGET:
parser->item_length++;
- if(c == '\r') {
- parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_WINDOWSEOL;
- }
- else if(c == '\n') {
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- parser->offsets.symlink_target = parser->item_offset;
+ if(c == '\r') {
+ parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_WINDOWSEOL;
+ }
+ else if(c == '\n') {
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ parser->offsets.symlink_target = parser->item_offset;
result = ftp_pl_insert_finfo(conn, infop);
if(result) {
parser->error = result;
goto fail;
- }
- parser->state.UNIX.main = PL_UNIX_FILETYPE;
- }
- break;
- case PL_UNIX_SYMLINK_WINDOWSEOL:
- if(c == '\n') {
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- parser->offsets.symlink_target = parser->item_offset;
+ }
+ parser->state.UNIX.main = PL_UNIX_FILETYPE;
+ }
+ break;
+ case PL_UNIX_SYMLINK_WINDOWSEOL:
+ if(c == '\n') {
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ parser->offsets.symlink_target = parser->item_offset;
result = ftp_pl_insert_finfo(conn, infop);
if(result) {
parser->error = result;
goto fail;
- }
- parser->state.UNIX.main = PL_UNIX_FILETYPE;
- }
- else {
+ }
+ parser->state.UNIX.main = PL_UNIX_FILETYPE;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- }
- break;
- case OS_TYPE_WIN_NT:
- switch(parser->state.NT.main) {
- case PL_WINNT_DATE:
- parser->item_length++;
- if(parser->item_length < 9) {
- if(!strchr("0123456789-", c)) { /* only simple control */
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ case OS_TYPE_WIN_NT:
+ switch(parser->state.NT.main) {
+ case PL_WINNT_DATE:
+ parser->item_length++;
+ if(parser->item_length < 9) {
+ if(!strchr("0123456789-", c)) { /* only simple control */
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- else if(parser->item_length == 9) {
- if(c == ' ') {
- parser->state.NT.main = PL_WINNT_TIME;
- parser->state.NT.sub.time = PL_WINNT_TIME_PRESPACE;
- }
- else {
+ }
+ }
+ else if(parser->item_length == 9) {
+ if(c == ' ') {
+ parser->state.NT.main = PL_WINNT_TIME;
+ parser->state.NT.sub.time = PL_WINNT_TIME_PRESPACE;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- }
- else {
+ }
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- case PL_WINNT_TIME:
- parser->item_length++;
- switch(parser->state.NT.sub.time) {
- case PL_WINNT_TIME_PRESPACE:
- if(!ISSPACE(c)) {
- parser->state.NT.sub.time = PL_WINNT_TIME_TIME;
- }
- break;
- case PL_WINNT_TIME_TIME:
- if(c == ' ') {
- parser->offsets.time = parser->item_offset;
- finfo->b_data[parser->item_offset + parser->item_length -1] = 0;
- parser->state.NT.main = PL_WINNT_DIRORSIZE;
- parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_PRESPACE;
- parser->item_length = 0;
- }
- else if(!strchr("APM0123456789:", c)) {
+ }
+ break;
+ case PL_WINNT_TIME:
+ parser->item_length++;
+ switch(parser->state.NT.sub.time) {
+ case PL_WINNT_TIME_PRESPACE:
+ if(!ISSPACE(c)) {
+ parser->state.NT.sub.time = PL_WINNT_TIME_TIME;
+ }
+ break;
+ case PL_WINNT_TIME_TIME:
+ if(c == ' ') {
+ parser->offsets.time = parser->item_offset;
+ finfo->b_data[parser->item_offset + parser->item_length -1] = 0;
+ parser->state.NT.main = PL_WINNT_DIRORSIZE;
+ parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_PRESPACE;
+ parser->item_length = 0;
+ }
+ else if(!strchr("APM0123456789:", c)) {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- case PL_WINNT_DIRORSIZE:
- switch(parser->state.NT.sub.dirorsize) {
- case PL_WINNT_DIRORSIZE_PRESPACE:
+ }
+ break;
+ }
+ break;
+ case PL_WINNT_DIRORSIZE:
+ switch(parser->state.NT.sub.dirorsize) {
+ case PL_WINNT_DIRORSIZE_PRESPACE:
if(c != ' ') {
- parser->item_offset = finfo->b_used - 1;
- parser->item_length = 1;
- parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_CONTENT;
- }
- break;
- case PL_WINNT_DIRORSIZE_CONTENT:
- parser->item_length ++;
- if(c == ' ') {
- finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- if(strcmp("<DIR>", finfo->b_data + parser->item_offset) == 0) {
- finfo->filetype = CURLFILETYPE_DIRECTORY;
- finfo->size = 0;
- }
- else {
- char *endptr;
+ parser->item_offset = finfo->b_used - 1;
+ parser->item_length = 1;
+ parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_CONTENT;
+ }
+ break;
+ case PL_WINNT_DIRORSIZE_CONTENT:
+ parser->item_length ++;
+ if(c == ' ') {
+ finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
+ if(strcmp("<DIR>", finfo->b_data + parser->item_offset) == 0) {
+ finfo->filetype = CURLFILETYPE_DIRECTORY;
+ finfo->size = 0;
+ }
+ else {
+ char *endptr;
if(curlx_strtoofft(finfo->b_data +
parser->item_offset,
&endptr, 10, &finfo->size)) {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- /* correct file type */
+ }
+ /* correct file type */
parser->file_data->info.filetype = CURLFILETYPE_FILE;
- }
-
+ }
+
parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE;
- parser->item_length = 0;
- parser->state.NT.main = PL_WINNT_FILENAME;
- parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE;
- }
- break;
- }
- break;
- case PL_WINNT_FILENAME:
+ parser->item_length = 0;
+ parser->state.NT.main = PL_WINNT_FILENAME;
+ parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE;
+ }
+ break;
+ }
+ break;
+ case PL_WINNT_FILENAME:
switch(parser->state.NT.sub.filename) {
- case PL_WINNT_FILENAME_PRESPACE:
- if(c != ' ') {
- parser->item_offset = finfo->b_used -1;
- parser->item_length = 1;
- parser->state.NT.sub.filename = PL_WINNT_FILENAME_CONTENT;
- }
- break;
- case PL_WINNT_FILENAME_CONTENT:
- parser->item_length++;
- if(c == '\r') {
- parser->state.NT.sub.filename = PL_WINNT_FILENAME_WINEOL;
- finfo->b_data[finfo->b_used - 1] = 0;
- }
- else if(c == '\n') {
- parser->offsets.filename = parser->item_offset;
- finfo->b_data[finfo->b_used - 1] = 0;
- parser->offsets.filename = parser->item_offset;
+ case PL_WINNT_FILENAME_PRESPACE:
+ if(c != ' ') {
+ parser->item_offset = finfo->b_used -1;
+ parser->item_length = 1;
+ parser->state.NT.sub.filename = PL_WINNT_FILENAME_CONTENT;
+ }
+ break;
+ case PL_WINNT_FILENAME_CONTENT:
+ parser->item_length++;
+ if(c == '\r') {
+ parser->state.NT.sub.filename = PL_WINNT_FILENAME_WINEOL;
+ finfo->b_data[finfo->b_used - 1] = 0;
+ }
+ else if(c == '\n') {
+ parser->offsets.filename = parser->item_offset;
+ finfo->b_data[finfo->b_used - 1] = 0;
+ parser->offsets.filename = parser->item_offset;
result = ftp_pl_insert_finfo(conn, infop);
if(result) {
parser->error = result;
goto fail;
- }
- parser->state.NT.main = PL_WINNT_DATE;
- parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE;
- }
- break;
- case PL_WINNT_FILENAME_WINEOL:
- if(c == '\n') {
- parser->offsets.filename = parser->item_offset;
+ }
+ parser->state.NT.main = PL_WINNT_DATE;
+ parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE;
+ }
+ break;
+ case PL_WINNT_FILENAME_WINEOL:
+ if(c == '\n') {
+ parser->offsets.filename = parser->item_offset;
result = ftp_pl_insert_finfo(conn, infop);
if(result) {
parser->error = result;
goto fail;
- }
- parser->state.NT.main = PL_WINNT_DATE;
- parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE;
- }
- else {
+ }
+ parser->state.NT.main = PL_WINNT_DATE;
+ parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE;
+ }
+ else {
parser->error = CURLE_FTP_BAD_FILE_LIST;
goto fail;
- }
- break;
- }
- break;
- }
- break;
- default:
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ default:
retsize = bufflen + 1;
goto fail;
- }
-
- i++;
- }
+ }
+
+ i++;
+ }
return retsize;
-
+
fail:
/* Clean up any allocated memory. */
@@ -1014,6 +1014,6 @@ fail:
}
return retsize;
-}
-
-#endif /* CURL_DISABLE_FTP */
+}
+
+#endif /* CURL_DISABLE_FTP */
diff --git a/contrib/libs/curl/lib/ftplistparser.h b/contrib/libs/curl/lib/ftplistparser.h
index a655dc2b8b..e4cd8201d9 100644
--- a/contrib/libs/curl/lib/ftplistparser.h
+++ b/contrib/libs/curl/lib/ftplistparser.h
@@ -1,41 +1,41 @@
-#ifndef HEADER_CURL_FTPLISTPARSER_H
-#define HEADER_CURL_FTPLISTPARSER_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_FTPLISTPARSER_H
+#define HEADER_CURL_FTPLISTPARSER_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_FTP
-
-/* WRITEFUNCTION callback for parsing LIST responses */
-size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
- void *connptr);
-
-struct ftp_parselist_data; /* defined inside ftplibparser.c */
-
-CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data);
-
-struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void);
-
-void Curl_ftp_parselist_data_free(struct ftp_parselist_data **pl_data);
-
-#endif /* CURL_DISABLE_FTP */
-#endif /* HEADER_CURL_FTPLISTPARSER_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_FTP
+
+/* WRITEFUNCTION callback for parsing LIST responses */
+size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
+ void *connptr);
+
+struct ftp_parselist_data; /* defined inside ftplibparser.c */
+
+CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data);
+
+struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void);
+
+void Curl_ftp_parselist_data_free(struct ftp_parselist_data **pl_data);
+
+#endif /* CURL_DISABLE_FTP */
+#endif /* HEADER_CURL_FTPLISTPARSER_H */
diff --git a/contrib/libs/curl/lib/getenv.c b/contrib/libs/curl/lib/getenv.c
index aece40de8b..92c53505c6 100644
--- a/contrib/libs/curl/lib/getenv.c
+++ b/contrib/libs/curl/lib/getenv.c
@@ -1,37 +1,37 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-#include "curl_memory.h"
-
-#include "memdebug.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+#include "curl_memory.h"
+
+#include "memdebug.h"
+
static char *GetEnv(const char *variable)
-{
+{
#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_APP)
(void)variable;
- return NULL;
+ return NULL;
#elif defined(WIN32)
/* This uses Windows API instead of C runtime getenv() to get the environment
variable since some changes aren't always visible to the latter. #4774 */
@@ -65,13 +65,13 @@ static char *GetEnv(const char *variable)
/* else rc is bytes needed, try again */
}
-#else
- char *env = getenv(variable);
- return (env && env[0])?strdup(env):NULL;
-#endif
-}
-
-char *curl_getenv(const char *v)
-{
- return GetEnv(v);
-}
+#else
+ char *env = getenv(variable);
+ return (env && env[0])?strdup(env):NULL;
+#endif
+}
+
+char *curl_getenv(const char *v)
+{
+ return GetEnv(v);
+}
diff --git a/contrib/libs/curl/lib/getinfo.c b/contrib/libs/curl/lib/getinfo.c
index 4965df83db..fd8f4e8430 100644
--- a/contrib/libs/curl/lib/getinfo.c
+++ b/contrib/libs/curl/lib/getinfo.c
@@ -1,101 +1,101 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "getinfo.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "getinfo.h"
+
#include "vtls/vtls.h"
-#include "connect.h" /* Curl_getconnectinfo() */
-#include "progress.h"
-
+#include "connect.h" /* Curl_getconnectinfo() */
+#include "progress.h"
+
/* The last #include files should be: */
#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
+#include "memdebug.h"
+
+/*
* Initialize statistical and informational data.
*
* This function is called in curl_easy_reset, curl_easy_duphandle and at the
* beginning of a perform session. It must reset the session-info variables,
* in particular all variables in struct PureInfo.
- */
+ */
CURLcode Curl_initinfo(struct Curl_easy *data)
-{
- struct Progress *pro = &data->progress;
+{
+ struct Progress *pro = &data->progress;
struct PureInfo *info = &data->info;
-
- pro->t_nslookup = 0;
- pro->t_connect = 0;
- pro->t_appconnect = 0;
- pro->t_pretransfer = 0;
- pro->t_starttransfer = 0;
- pro->timespent = 0;
- pro->t_redirect = 0;
+
+ pro->t_nslookup = 0;
+ pro->t_connect = 0;
+ pro->t_appconnect = 0;
+ pro->t_pretransfer = 0;
+ pro->t_starttransfer = 0;
+ pro->timespent = 0;
+ pro->t_redirect = 0;
pro->is_t_startransfer_set = false;
-
- info->httpcode = 0;
+
+ info->httpcode = 0;
info->httpproxycode = 0;
- info->httpversion = 0;
- info->filetime = -1; /* -1 is an illegal time and thus means unknown */
- info->timecond = FALSE;
-
- info->header_size = 0;
- info->request_size = 0;
+ info->httpversion = 0;
+ info->filetime = -1; /* -1 is an illegal time and thus means unknown */
+ info->timecond = FALSE;
+
+ info->header_size = 0;
+ info->request_size = 0;
info->proxyauthavail = 0;
info->httpauthavail = 0;
- info->numconnects = 0;
-
+ info->numconnects = 0;
+
free(info->contenttype);
info->contenttype = NULL;
free(info->wouldredirect);
info->wouldredirect = NULL;
- info->conn_primary_ip[0] = '\0';
- info->conn_local_ip[0] = '\0';
- info->conn_primary_port = 0;
- info->conn_local_port = 0;
+ info->conn_primary_ip[0] = '\0';
+ info->conn_local_ip[0] = '\0';
+ info->conn_primary_port = 0;
+ info->conn_local_port = 0;
info->retry_after = 0;
-
+
info->conn_scheme = 0;
info->conn_protocol = 0;
#ifdef USE_SSL
Curl_ssl_free_certinfo(data);
#endif
- return CURLE_OK;
-}
-
+ return CURLE_OK;
+}
+
static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info,
const char **param_charp)
-{
- switch(info) {
- case CURLINFO_EFFECTIVE_URL:
- *param_charp = data->change.url?data->change.url:(char *)"";
- break;
+{
+ switch(info) {
+ case CURLINFO_EFFECTIVE_URL:
+ *param_charp = data->change.url?data->change.url:(char *)"";
+ break;
case CURLINFO_EFFECTIVE_METHOD: {
const char *m = data->set.str[STRING_CUSTOMREQUEST];
if(!m) {
@@ -124,58 +124,58 @@ static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info,
*param_charp = m;
}
break;
- case CURLINFO_CONTENT_TYPE:
- *param_charp = data->info.contenttype;
- break;
- case CURLINFO_PRIVATE:
- *param_charp = (char *) data->set.private_data;
- break;
- case CURLINFO_FTP_ENTRY_PATH:
- /* Return the entrypath string from the most recent connection.
- This pointer was copied from the connectdata structure by FTP.
- The actual string may be free()ed by subsequent libcurl calls so
- it must be copied to a safer area before the next libcurl call.
- Callers must never free it themselves. */
- *param_charp = data->state.most_recent_ftp_entrypath;
- break;
- case CURLINFO_REDIRECT_URL:
- /* Return the URL this request would have been redirected to if that
- option had been enabled! */
- *param_charp = data->info.wouldredirect;
- break;
- case CURLINFO_PRIMARY_IP:
- /* Return the ip address of the most recent (primary) connection */
- *param_charp = data->info.conn_primary_ip;
- break;
- case CURLINFO_LOCAL_IP:
- /* Return the source/local ip address of the most recent (primary)
- connection */
- *param_charp = data->info.conn_local_ip;
- break;
- case CURLINFO_RTSP_SESSION_ID:
- *param_charp = data->set.str[STRING_RTSP_SESSION_ID];
- break;
+ case CURLINFO_CONTENT_TYPE:
+ *param_charp = data->info.contenttype;
+ break;
+ case CURLINFO_PRIVATE:
+ *param_charp = (char *) data->set.private_data;
+ break;
+ case CURLINFO_FTP_ENTRY_PATH:
+ /* Return the entrypath string from the most recent connection.
+ This pointer was copied from the connectdata structure by FTP.
+ The actual string may be free()ed by subsequent libcurl calls so
+ it must be copied to a safer area before the next libcurl call.
+ Callers must never free it themselves. */
+ *param_charp = data->state.most_recent_ftp_entrypath;
+ break;
+ case CURLINFO_REDIRECT_URL:
+ /* Return the URL this request would have been redirected to if that
+ option had been enabled! */
+ *param_charp = data->info.wouldredirect;
+ break;
+ case CURLINFO_PRIMARY_IP:
+ /* Return the ip address of the most recent (primary) connection */
+ *param_charp = data->info.conn_primary_ip;
+ break;
+ case CURLINFO_LOCAL_IP:
+ /* Return the source/local ip address of the most recent (primary)
+ connection */
+ *param_charp = data->info.conn_local_ip;
+ break;
+ case CURLINFO_RTSP_SESSION_ID:
+ *param_charp = data->set.str[STRING_RTSP_SESSION_ID];
+ break;
case CURLINFO_SCHEME:
*param_charp = data->info.conn_scheme;
break;
-
- default:
+
+ default:
return CURLE_UNKNOWN_OPTION;
- }
+ }
+
+ return CURLE_OK;
+}
- return CURLE_OK;
-}
-
static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info,
- long *param_longp)
-{
- curl_socket_t sockfd;
-
- union {
- unsigned long *to_ulong;
- long *to_long;
- } lptr;
-
+ long *param_longp)
+{
+ curl_socket_t sockfd;
+
+ union {
+ unsigned long *to_ulong;
+ long *to_long;
+ } lptr;
+
#ifdef DEBUGBUILD
char *timestr = getenv("CURL_TIME");
if(timestr) {
@@ -203,91 +203,91 @@ static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info,
}
#endif
- switch(info) {
- case CURLINFO_RESPONSE_CODE:
- *param_longp = data->info.httpcode;
- break;
- case CURLINFO_HTTP_CONNECTCODE:
- *param_longp = data->info.httpproxycode;
- break;
- case CURLINFO_FILETIME:
+ switch(info) {
+ case CURLINFO_RESPONSE_CODE:
+ *param_longp = data->info.httpcode;
+ break;
+ case CURLINFO_HTTP_CONNECTCODE:
+ *param_longp = data->info.httpproxycode;
+ break;
+ case CURLINFO_FILETIME:
if(data->info.filetime > LONG_MAX)
*param_longp = LONG_MAX;
else if(data->info.filetime < LONG_MIN)
*param_longp = LONG_MIN;
else
*param_longp = (long)data->info.filetime;
- break;
- case CURLINFO_HEADER_SIZE:
+ break;
+ case CURLINFO_HEADER_SIZE:
*param_longp = (long)data->info.header_size;
- break;
- case CURLINFO_REQUEST_SIZE:
+ break;
+ case CURLINFO_REQUEST_SIZE:
*param_longp = (long)data->info.request_size;
- break;
- case CURLINFO_SSL_VERIFYRESULT:
- *param_longp = data->set.ssl.certverifyresult;
- break;
+ break;
+ case CURLINFO_SSL_VERIFYRESULT:
+ *param_longp = data->set.ssl.certverifyresult;
+ break;
#ifndef CURL_DISABLE_PROXY
case CURLINFO_PROXY_SSL_VERIFYRESULT:
*param_longp = data->set.proxy_ssl.certverifyresult;
break;
#endif
- case CURLINFO_REDIRECT_COUNT:
- *param_longp = data->set.followlocation;
- break;
- case CURLINFO_HTTPAUTH_AVAIL:
- lptr.to_long = param_longp;
- *lptr.to_ulong = data->info.httpauthavail;
- break;
- case CURLINFO_PROXYAUTH_AVAIL:
- lptr.to_long = param_longp;
- *lptr.to_ulong = data->info.proxyauthavail;
- break;
- case CURLINFO_OS_ERRNO:
- *param_longp = data->state.os_errno;
- break;
- case CURLINFO_NUM_CONNECTS:
- *param_longp = data->info.numconnects;
- break;
- case CURLINFO_LASTSOCKET:
- sockfd = Curl_getconnectinfo(data, NULL);
-
- /* note: this is not a good conversion for systems with 64 bit sockets and
- 32 bit longs */
- if(sockfd != CURL_SOCKET_BAD)
- *param_longp = (long)sockfd;
- else
- /* this interface is documented to return -1 in case of badness, which
- may not be the same as the CURL_SOCKET_BAD value */
- *param_longp = -1;
- break;
- case CURLINFO_PRIMARY_PORT:
- /* Return the (remote) port of the most recent (primary) connection */
- *param_longp = data->info.conn_primary_port;
- break;
- case CURLINFO_LOCAL_PORT:
- /* Return the local port of the most recent (primary) connection */
- *param_longp = data->info.conn_local_port;
- break;
+ case CURLINFO_REDIRECT_COUNT:
+ *param_longp = data->set.followlocation;
+ break;
+ case CURLINFO_HTTPAUTH_AVAIL:
+ lptr.to_long = param_longp;
+ *lptr.to_ulong = data->info.httpauthavail;
+ break;
+ case CURLINFO_PROXYAUTH_AVAIL:
+ lptr.to_long = param_longp;
+ *lptr.to_ulong = data->info.proxyauthavail;
+ break;
+ case CURLINFO_OS_ERRNO:
+ *param_longp = data->state.os_errno;
+ break;
+ case CURLINFO_NUM_CONNECTS:
+ *param_longp = data->info.numconnects;
+ break;
+ case CURLINFO_LASTSOCKET:
+ sockfd = Curl_getconnectinfo(data, NULL);
+
+ /* note: this is not a good conversion for systems with 64 bit sockets and
+ 32 bit longs */
+ if(sockfd != CURL_SOCKET_BAD)
+ *param_longp = (long)sockfd;
+ else
+ /* this interface is documented to return -1 in case of badness, which
+ may not be the same as the CURL_SOCKET_BAD value */
+ *param_longp = -1;
+ break;
+ case CURLINFO_PRIMARY_PORT:
+ /* Return the (remote) port of the most recent (primary) connection */
+ *param_longp = data->info.conn_primary_port;
+ break;
+ case CURLINFO_LOCAL_PORT:
+ /* Return the local port of the most recent (primary) connection */
+ *param_longp = data->info.conn_local_port;
+ break;
case CURLINFO_PROXY_ERROR:
*param_longp = (long)data->info.pxcode;
break;
- case CURLINFO_CONDITION_UNMET:
+ case CURLINFO_CONDITION_UNMET:
if(data->info.httpcode == 304)
*param_longp = 1L;
else
/* return if the condition prevented the document to get transferred */
*param_longp = data->info.timecond ? 1L : 0L;
- break;
- case CURLINFO_RTSP_CLIENT_CSEQ:
- *param_longp = data->state.rtsp_next_client_CSeq;
- break;
- case CURLINFO_RTSP_SERVER_CSEQ:
- *param_longp = data->state.rtsp_next_server_CSeq;
- break;
- case CURLINFO_RTSP_CSEQ_RECV:
- *param_longp = data->state.rtsp_CSeq_recv;
- break;
+ break;
+ case CURLINFO_RTSP_CLIENT_CSEQ:
+ *param_longp = data->state.rtsp_next_client_CSeq;
+ break;
+ case CURLINFO_RTSP_SERVER_CSEQ:
+ *param_longp = data->state.rtsp_next_server_CSeq;
+ break;
+ case CURLINFO_RTSP_CSEQ_RECV:
+ *param_longp = data->state.rtsp_CSeq_recv;
+ break;
case CURLINFO_HTTP_VERSION:
switch(data->info.httpversion) {
case 10:
@@ -310,13 +310,13 @@ static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info,
case CURLINFO_PROTOCOL:
*param_longp = data->info.conn_protocol;
break;
- default:
+ default:
return CURLE_UNKNOWN_OPTION;
- }
+ }
+
+ return CURLE_OK;
+}
- return CURLE_OK;
-}
-
#define DOUBLE_SECS(x) (double)(x)/1000000
static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info,
@@ -399,8 +399,8 @@ static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info,
}
static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info,
- double *param_doublep)
-{
+ double *param_doublep)
+{
#ifdef DEBUGBUILD
char *timestr = getenv("CURL_TIME");
if(timestr) {
@@ -422,77 +422,77 @@ static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info,
}
}
#endif
- switch(info) {
- case CURLINFO_TOTAL_TIME:
+ switch(info) {
+ case CURLINFO_TOTAL_TIME:
*param_doublep = DOUBLE_SECS(data->progress.timespent);
- break;
- case CURLINFO_NAMELOOKUP_TIME:
+ break;
+ case CURLINFO_NAMELOOKUP_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_nslookup);
- break;
- case CURLINFO_CONNECT_TIME:
+ break;
+ case CURLINFO_CONNECT_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_connect);
- break;
- case CURLINFO_APPCONNECT_TIME:
+ break;
+ case CURLINFO_APPCONNECT_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_appconnect);
- break;
- case CURLINFO_PRETRANSFER_TIME:
+ break;
+ case CURLINFO_PRETRANSFER_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_pretransfer);
- break;
- case CURLINFO_STARTTRANSFER_TIME:
+ break;
+ case CURLINFO_STARTTRANSFER_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_starttransfer);
- break;
- case CURLINFO_SIZE_UPLOAD:
+ break;
+ case CURLINFO_SIZE_UPLOAD:
*param_doublep = (double)data->progress.uploaded;
- break;
- case CURLINFO_SIZE_DOWNLOAD:
- *param_doublep = (double)data->progress.downloaded;
- break;
- case CURLINFO_SPEED_DOWNLOAD:
+ break;
+ case CURLINFO_SIZE_DOWNLOAD:
+ *param_doublep = (double)data->progress.downloaded;
+ break;
+ case CURLINFO_SPEED_DOWNLOAD:
*param_doublep = (double)data->progress.dlspeed;
- break;
- case CURLINFO_SPEED_UPLOAD:
- *param_doublep = (double)data->progress.ulspeed;
- break;
- case CURLINFO_CONTENT_LENGTH_DOWNLOAD:
- *param_doublep = (data->progress.flags & PGRS_DL_SIZE_KNOWN)?
- (double)data->progress.size_dl:-1;
- break;
- case CURLINFO_CONTENT_LENGTH_UPLOAD:
- *param_doublep = (data->progress.flags & PGRS_UL_SIZE_KNOWN)?
- (double)data->progress.size_ul:-1;
- break;
- case CURLINFO_REDIRECT_TIME:
+ break;
+ case CURLINFO_SPEED_UPLOAD:
+ *param_doublep = (double)data->progress.ulspeed;
+ break;
+ case CURLINFO_CONTENT_LENGTH_DOWNLOAD:
+ *param_doublep = (data->progress.flags & PGRS_DL_SIZE_KNOWN)?
+ (double)data->progress.size_dl:-1;
+ break;
+ case CURLINFO_CONTENT_LENGTH_UPLOAD:
+ *param_doublep = (data->progress.flags & PGRS_UL_SIZE_KNOWN)?
+ (double)data->progress.size_ul:-1;
+ break;
+ case CURLINFO_REDIRECT_TIME:
*param_doublep = DOUBLE_SECS(data->progress.t_redirect);
- break;
-
- default:
+ break;
+
+ default:
return CURLE_UNKNOWN_OPTION;
- }
+ }
+
+ return CURLE_OK;
+}
- return CURLE_OK;
-}
-
static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info,
- struct curl_slist **param_slistp)
-{
- union {
+ struct curl_slist **param_slistp)
+{
+ union {
struct curl_certinfo *to_certinfo;
struct curl_slist *to_slist;
- } ptr;
-
- switch(info) {
- case CURLINFO_SSL_ENGINES:
- *param_slistp = Curl_ssl_engines_list(data);
- break;
- case CURLINFO_COOKIELIST:
- *param_slistp = Curl_cookie_list(data);
- break;
- case CURLINFO_CERTINFO:
- /* Return the a pointer to the certinfo struct. Not really an slist
- pointer but we can pretend it is here */
- ptr.to_certinfo = &data->info.certs;
- *param_slistp = ptr.to_slist;
- break;
+ } ptr;
+
+ switch(info) {
+ case CURLINFO_SSL_ENGINES:
+ *param_slistp = Curl_ssl_engines_list(data);
+ break;
+ case CURLINFO_COOKIELIST:
+ *param_slistp = Curl_cookie_list(data);
+ break;
+ case CURLINFO_CERTINFO:
+ /* Return the a pointer to the certinfo struct. Not really an slist
+ pointer but we can pretend it is here */
+ ptr.to_certinfo = &data->info.certs;
+ *param_slistp = ptr.to_slist;
+ break;
case CURLINFO_TLS_SESSION:
case CURLINFO_TLS_SSL_PTR:
{
@@ -502,7 +502,7 @@ static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info,
#ifdef USE_SSL
struct connectdata *conn = data->conn;
#endif
-
+
*tsip = tsi;
tsi->backend = Curl_ssl_backend();
tsi->internals = NULL;
@@ -520,16 +520,16 @@ static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info,
#endif
}
break;
- default:
+ default:
return CURLE_UNKNOWN_OPTION;
- }
+ }
+
+ return CURLE_OK;
+}
- return CURLE_OK;
-}
-
static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info,
curl_socket_t *param_socketp)
-{
+{
switch(info) {
case CURLINFO_ACTIVESOCKET:
*param_socketp = Curl_getconnectinfo(data, NULL);
@@ -543,58 +543,58 @@ static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info,
CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...)
{
- va_list arg;
+ va_list arg;
long *param_longp = NULL;
double *param_doublep = NULL;
curl_off_t *param_offt = NULL;
const char **param_charp = NULL;
struct curl_slist **param_slistp = NULL;
curl_socket_t *param_socketp = NULL;
- int type;
+ int type;
CURLcode result = CURLE_UNKNOWN_OPTION;
-
- if(!data)
+
+ if(!data)
return result;
-
- va_start(arg, info);
-
- type = CURLINFO_TYPEMASK & (int)info;
- switch(type) {
- case CURLINFO_STRING:
+
+ va_start(arg, info);
+
+ type = CURLINFO_TYPEMASK & (int)info;
+ switch(type) {
+ case CURLINFO_STRING:
param_charp = va_arg(arg, const char **);
if(param_charp)
result = getinfo_char(data, info, param_charp);
- break;
- case CURLINFO_LONG:
- param_longp = va_arg(arg, long *);
+ break;
+ case CURLINFO_LONG:
+ param_longp = va_arg(arg, long *);
if(param_longp)
result = getinfo_long(data, info, param_longp);
- break;
- case CURLINFO_DOUBLE:
- param_doublep = va_arg(arg, double *);
+ break;
+ case CURLINFO_DOUBLE:
+ param_doublep = va_arg(arg, double *);
if(param_doublep)
result = getinfo_double(data, info, param_doublep);
- break;
+ break;
case CURLINFO_OFF_T:
param_offt = va_arg(arg, curl_off_t *);
if(param_offt)
result = getinfo_offt(data, info, param_offt);
break;
- case CURLINFO_SLIST:
- param_slistp = va_arg(arg, struct curl_slist **);
+ case CURLINFO_SLIST:
+ param_slistp = va_arg(arg, struct curl_slist **);
if(param_slistp)
result = getinfo_slist(data, info, param_slistp);
- break;
+ break;
case CURLINFO_SOCKET:
param_socketp = va_arg(arg, curl_socket_t *);
if(param_socketp)
result = getinfo_socket(data, info, param_socketp);
break;
- default:
- break;
- }
-
- va_end(arg);
+ default:
+ break;
+ }
+
+ va_end(arg);
return result;
-}
+}
diff --git a/contrib/libs/curl/lib/getinfo.h b/contrib/libs/curl/lib/getinfo.h
index 35f30d08ec..f35d1b4b34 100644
--- a/contrib/libs/curl/lib/getinfo.h
+++ b/contrib/libs/curl/lib/getinfo.h
@@ -1,27 +1,27 @@
-#ifndef HEADER_CURL_GETINFO_H
-#define HEADER_CURL_GETINFO_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_GETINFO_H
+#define HEADER_CURL_GETINFO_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...);
CURLcode Curl_initinfo(struct Curl_easy *data);
-
-#endif /* HEADER_CURL_GETINFO_H */
+
+#endif /* HEADER_CURL_GETINFO_H */
diff --git a/contrib/libs/curl/lib/gopher.c b/contrib/libs/curl/lib/gopher.c
index 3f02af341d..b101c0ab68 100644
--- a/contrib/libs/curl/lib/gopher.c
+++ b/contrib/libs/curl/lib/gopher.c
@@ -1,97 +1,97 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_GOPHER
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
-#include "sendf.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_GOPHER
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
+#include "sendf.h"
#include "connect.h"
-#include "progress.h"
-#include "gopher.h"
-#include "select.h"
+#include "progress.h"
+#include "gopher.h"
+#include "select.h"
#include "strdup.h"
-#include "url.h"
+#include "url.h"
#include "escape.h"
-#include "warnless.h"
+#include "warnless.h"
#include "curl_printf.h"
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * Forward declarations.
- */
-
-static CURLcode gopher_do(struct connectdata *conn, bool *done);
-
-/*
- * Gopher protocol handler.
- * This is also a nice simple template to build off for simple
- * connect-command-download protocols.
- */
-
-const struct Curl_handler Curl_handler_gopher = {
- "GOPHER", /* scheme */
- ZERO_NULL, /* setup_connection */
- gopher_do, /* do_it */
- ZERO_NULL, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * Forward declarations.
+ */
+
+static CURLcode gopher_do(struct connectdata *conn, bool *done);
+
+/*
+ * Gopher protocol handler.
+ * This is also a nice simple template to build off for simple
+ * connect-command-download protocols.
+ */
+
+const struct Curl_handler Curl_handler_gopher = {
+ "GOPHER", /* scheme */
+ ZERO_NULL, /* setup_connection */
+ gopher_do, /* do_it */
+ ZERO_NULL, /* done */
+ ZERO_NULL, /* do_more */
+ ZERO_NULL, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_GOPHER, /* defport */
- CURLPROTO_GOPHER, /* protocol */
+ PORT_GOPHER, /* defport */
+ CURLPROTO_GOPHER, /* protocol */
CURLPROTO_GOPHER, /* family */
- PROTOPT_NONE /* flags */
-};
-
-static CURLcode gopher_do(struct connectdata *conn, bool *done)
-{
+ PROTOPT_NONE /* flags */
+};
+
+static CURLcode gopher_do(struct connectdata *conn, bool *done)
+{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
+ curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
char *gopherpath;
char *path = data->state.up.path;
char *query = data->state.up.query;
char *sel = NULL;
- char *sel_org = NULL;
+ char *sel_org = NULL;
timediff_t timeout_ms;
- ssize_t amount, k;
+ ssize_t amount, k;
size_t len;
int what;
-
- *done = TRUE; /* unconditionally */
-
+
+ *done = TRUE; /* unconditionally */
+
/* path is guaranteed non-NULL */
DEBUGASSERT(path);
@@ -103,41 +103,41 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
if(!gopherpath)
return CURLE_OUT_OF_MEMORY;
- /* Create selector. Degenerate cases: / and /1 => convert to "" */
+ /* Create selector. Degenerate cases: / and /1 => convert to "" */
if(strlen(gopherpath) <= 2) {
- sel = (char *)"";
+ sel = (char *)"";
len = strlen(sel);
free(gopherpath);
}
- else {
- char *newp;
-
- /* Otherwise, drop / and the first character (i.e., item type) ... */
+ else {
+ char *newp;
+
+ /* Otherwise, drop / and the first character (i.e., item type) ... */
newp = gopherpath;
newp += 2;
-
- /* ... and finally unescape */
+
+ /* ... and finally unescape */
result = Curl_urldecode(data, newp, 0, &sel, &len, REJECT_ZERO);
free(gopherpath);
if(result)
return result;
- sel_org = sel;
- }
-
+ sel_org = sel;
+ }
+
k = curlx_uztosz(len);
-
- for(;;) {
- result = Curl_write(conn, sockfd, sel, k, &amount);
+
+ for(;;) {
+ result = Curl_write(conn, sockfd, sel, k, &amount);
if(!result) { /* Which may not have written it all! */
- result = Curl_client_write(conn, CLIENTWRITE_HEADER, sel, amount);
+ result = Curl_client_write(conn, CLIENTWRITE_HEADER, sel, amount);
if(result)
break;
- k -= amount;
- sel += amount;
- if(k < 1)
- break; /* but it did write it all */
- }
+ k -= amount;
+ sel += amount;
+ if(k < 1)
+ break; /* but it did write it all */
+ }
else
break;
@@ -149,12 +149,12 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
if(!timeout_ms)
timeout_ms = TIMEDIFF_T_MAX;
- /* Don't busyloop. The entire loop thing is a work-around as it causes a
- BLOCKING behavior which is a NO-NO. This function should rather be
- split up in a do and a doing piece where the pieces that aren't
- possible to send now will be sent in the doing function repeatedly
- until the entire request is sent.
- */
+ /* Don't busyloop. The entire loop thing is a work-around as it causes a
+ BLOCKING behavior which is a NO-NO. This function should rather be
+ split up in a do and a doing piece where the pieces that aren't
+ possible to send now will be sent in the doing function repeatedly
+ until the entire request is sent.
+ */
what = SOCKET_WRITABLE(sockfd, timeout_ms);
if(what < 0) {
result = CURLE_SEND_ERROR;
@@ -164,21 +164,21 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
result = CURLE_OPERATION_TIMEDOUT;
break;
}
- }
-
+ }
+
free(sel_org);
-
+
if(!result)
result = Curl_write(conn, sockfd, "\r\n", 2, &amount);
if(result) {
- failf(data, "Failed sending Gopher request");
- return result;
- }
- result = Curl_client_write(conn, CLIENTWRITE_HEADER, (char *)"\r\n", 2);
- if(result)
- return result;
-
+ failf(data, "Failed sending Gopher request");
+ return result;
+ }
+ result = Curl_client_write(conn, CLIENTWRITE_HEADER, (char *)"\r\n", 2);
+ if(result)
+ return result;
+
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
- return CURLE_OK;
-}
-#endif /*CURL_DISABLE_GOPHER*/
+ return CURLE_OK;
+}
+#endif /*CURL_DISABLE_GOPHER*/
diff --git a/contrib/libs/curl/lib/gopher.h b/contrib/libs/curl/lib/gopher.h
index 0b89163c9a..b35fa45096 100644
--- a/contrib/libs/curl/lib/gopher.h
+++ b/contrib/libs/curl/lib/gopher.h
@@ -1,29 +1,29 @@
-#ifndef HEADER_CURL_GOPHER_H
-#define HEADER_CURL_GOPHER_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_GOPHER_H
+#define HEADER_CURL_GOPHER_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#ifndef CURL_DISABLE_GOPHER
-extern const struct Curl_handler Curl_handler_gopher;
-#endif
-
-#endif /* HEADER_CURL_GOPHER_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#ifndef CURL_DISABLE_GOPHER
+extern const struct Curl_handler Curl_handler_gopher;
+#endif
+
+#endif /* HEADER_CURL_GOPHER_H */
diff --git a/contrib/libs/curl/lib/hash.c b/contrib/libs/curl/lib/hash.c
index 57f76a16fe..051c176269 100644
--- a/contrib/libs/curl/lib/hash.c
+++ b/contrib/libs/curl/lib/hash.c
@@ -1,199 +1,199 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <curl/curl.h>
-#include "hash.h"
-#include "llist.h"
+#include "hash.h"
+#include "llist.h"
#include "curl_memory.h"
-
-/* The last #include file should be: */
-#include "memdebug.h"
-
-static void
-hash_element_dtor(void *user, void *element)
-{
+
+/* The last #include file should be: */
+#include "memdebug.h"
+
+static void
+hash_element_dtor(void *user, void *element)
+{
struct Curl_hash *h = (struct Curl_hash *) user;
struct Curl_hash_element *e = (struct Curl_hash_element *) element;
-
- if(e->ptr) {
- h->dtor(e->ptr);
- e->ptr = NULL;
- }
-
- e->key_len = 0;
-
- free(e);
-}
-
+
+ if(e->ptr) {
+ h->dtor(e->ptr);
+ e->ptr = NULL;
+ }
+
+ e->key_len = 0;
+
+ free(e);
+}
+
/* Initializes a hash structure.
* Return 1 on error, 0 is fine.
*
* @unittest: 1602
* @unittest: 1603
*/
-int
+int
Curl_hash_init(struct Curl_hash *h,
- int slots,
- hash_function hfunc,
- comp_function comparator,
+ int slots,
+ hash_function hfunc,
+ comp_function comparator,
Curl_hash_dtor dtor)
-{
- if(!slots || !hfunc || !comparator ||!dtor) {
- return 1; /* failure */
- }
-
- h->hash_func = hfunc;
- h->comp_func = comparator;
- h->dtor = dtor;
- h->size = 0;
- h->slots = slots;
-
+{
+ if(!slots || !hfunc || !comparator ||!dtor) {
+ return 1; /* failure */
+ }
+
+ h->hash_func = hfunc;
+ h->comp_func = comparator;
+ h->dtor = dtor;
+ h->size = 0;
+ h->slots = slots;
+
h->table = malloc(slots * sizeof(struct Curl_llist));
- if(h->table) {
+ if(h->table) {
int i;
for(i = 0; i < slots; ++i)
Curl_llist_init(&h->table[i], (Curl_llist_dtor) hash_element_dtor);
- return 0; /* fine */
- }
+ return 0; /* fine */
+ }
h->slots = 0;
return 1; /* failure */
-}
-
+}
+
static struct Curl_hash_element *
-mk_hash_element(const void *key, size_t key_len, const void *p)
-{
+mk_hash_element(const void *key, size_t key_len, const void *p)
+{
/* allocate the struct plus memory after it to store the key */
struct Curl_hash_element *he = malloc(sizeof(struct Curl_hash_element) +
key_len);
- if(he) {
+ if(he) {
/* copy the key */
memcpy(he->key, key, key_len);
he->key_len = key_len;
he->ptr = (void *) p;
- }
- return he;
-}
-
+ }
+ return he;
+}
+
#define FETCH_LIST(x,y,z) &x->table[x->hash_func(y, z, x->slots)]
-
-/* Insert the data in the hash. If there already was a match in the hash,
- * that data is replaced.
- *
- * @unittest: 1305
+
+/* Insert the data in the hash. If there already was a match in the hash,
+ * that data is replaced.
+ *
+ * @unittest: 1305
* @unittest: 1602
* @unittest: 1603
- */
-void *
+ */
+void *
Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p)
-{
+{
struct Curl_hash_element *he;
struct Curl_llist_element *le;
struct Curl_llist *l = FETCH_LIST(h, key, key_len);
-
- for(le = l->head; le; le = le->next) {
+
+ for(le = l->head; le; le = le->next) {
he = (struct Curl_hash_element *) le->ptr;
- if(h->comp_func(he->key, he->key_len, key, key_len)) {
- Curl_llist_remove(l, le, (void *)h);
- --h->size;
- break;
- }
- }
-
- he = mk_hash_element(key, key_len, p);
- if(he) {
+ if(h->comp_func(he->key, he->key_len, key, key_len)) {
+ Curl_llist_remove(l, le, (void *)h);
+ --h->size;
+ break;
+ }
+ }
+
+ he = mk_hash_element(key, key_len, p);
+ if(he) {
Curl_llist_insert_next(l, l->tail, he, &he->list);
++h->size;
return p; /* return the new entry */
- }
-
- return NULL; /* failure */
-}
-
+ }
+
+ return NULL; /* failure */
+}
+
/* Remove the identified hash entry.
* Returns non-zero on failure.
*
* @unittest: 1603
*/
int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len)
-{
+{
struct Curl_llist_element *le;
struct Curl_llist *l = FETCH_LIST(h, key, key_len);
-
- for(le = l->head; le; le = le->next) {
+
+ for(le = l->head; le; le = le->next) {
struct Curl_hash_element *he = le->ptr;
- if(h->comp_func(he->key, he->key_len, key, key_len)) {
- Curl_llist_remove(l, le, (void *) h);
- --h->size;
- return 0;
- }
- }
- return 1;
-}
-
+ if(h->comp_func(he->key, he->key_len, key, key_len)) {
+ Curl_llist_remove(l, le, (void *) h);
+ --h->size;
+ return 0;
+ }
+ }
+ return 1;
+}
+
/* Retrieves a hash element.
*
* @unittest: 1603
*/
-void *
+void *
Curl_hash_pick(struct Curl_hash *h, void *key, size_t key_len)
-{
+{
struct Curl_llist_element *le;
struct Curl_llist *l;
-
- if(h) {
- l = FETCH_LIST(h, key, key_len);
- for(le = l->head; le; le = le->next) {
+
+ if(h) {
+ l = FETCH_LIST(h, key, key_len);
+ for(le = l->head; le; le = le->next) {
struct Curl_hash_element *he = le->ptr;
- if(h->comp_func(he->key, he->key_len, key, key_len)) {
- return he->ptr;
- }
- }
- }
-
- return NULL;
-}
-
-#if defined(DEBUGBUILD) && defined(AGGRESIVE_TEST)
-void
+ if(h->comp_func(he->key, he->key_len, key, key_len)) {
+ return he->ptr;
+ }
+ }
+ }
+
+ return NULL;
+}
+
+#if defined(DEBUGBUILD) && defined(AGGRESIVE_TEST)
+void
Curl_hash_apply(Curl_hash *h, void *user,
- void (*cb)(void *user, void *ptr))
-{
+ void (*cb)(void *user, void *ptr))
+{
struct Curl_llist_element *le;
- int i;
-
- for(i = 0; i < h->slots; ++i) {
- for(le = (h->table[i])->head;
- le;
- le = le->next) {
+ int i;
+
+ for(i = 0; i < h->slots; ++i) {
+ for(le = (h->table[i])->head;
+ le;
+ le = le->next) {
Curl_hash_element *el = le->ptr;
- cb(user, el->ptr);
- }
- }
-}
-#endif
-
+ cb(user, el->ptr);
+ }
+ }
+}
+#endif
+
/* Destroys all the entries in the given hash and resets its attributes,
* prepping the given hash for [static|dynamic] deallocation.
*
@@ -201,25 +201,25 @@ Curl_hash_apply(Curl_hash *h, void *user,
* @unittest: 1602
* @unittest: 1603
*/
-void
+void
Curl_hash_destroy(struct Curl_hash *h)
-{
- int i;
-
- for(i = 0; i < h->slots; ++i) {
+{
+ int i;
+
+ for(i = 0; i < h->slots; ++i) {
Curl_llist_destroy(&h->table[i], (void *) h);
- }
-
- Curl_safefree(h->table);
- h->size = 0;
- h->slots = 0;
-}
-
+ }
+
+ Curl_safefree(h->table);
+ h->size = 0;
+ h->slots = 0;
+}
+
/* Removes all the entries in the given hash.
*
* @unittest: 1602
*/
-void
+void
Curl_hash_clean(struct Curl_hash *h)
{
Curl_hash_clean_with_criterium(h, NULL, NULL);
@@ -228,124 +228,124 @@ Curl_hash_clean(struct Curl_hash *h)
/* Cleans all entries that pass the comp function criteria. */
void
Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user,
- int (*comp)(void *, void *))
-{
+ int (*comp)(void *, void *))
+{
struct Curl_llist_element *le;
struct Curl_llist_element *lnext;
struct Curl_llist *list;
- int i;
-
- if(!h)
- return;
-
- for(i = 0; i < h->slots; ++i) {
+ int i;
+
+ if(!h)
+ return;
+
+ for(i = 0; i < h->slots; ++i) {
list = &h->table[i];
- le = list->head; /* get first list entry */
- while(le) {
+ le = list->head; /* get first list entry */
+ while(le) {
struct Curl_hash_element *he = le->ptr;
- lnext = le->next;
- /* ask the callback function if we shall remove this entry or not */
+ lnext = le->next;
+ /* ask the callback function if we shall remove this entry or not */
if(comp == NULL || comp(user, he->ptr)) {
- Curl_llist_remove(list, le, (void *) h);
- --h->size; /* one less entry in the hash now */
- }
- le = lnext;
- }
- }
-}
-
+ Curl_llist_remove(list, le, (void *) h);
+ --h->size; /* one less entry in the hash now */
+ }
+ le = lnext;
+ }
+ }
+}
+
size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num)
-{
+{
const char *key_str = (const char *) key;
- const char *end = key_str + key_length;
+ const char *end = key_str + key_length;
size_t h = 5381;
-
- while(key_str < end) {
- h += h << 5;
+
+ while(key_str < end) {
+ h += h << 5;
h ^= *key_str++;
- }
-
- return (h % slots_num);
-}
-
+ }
+
+ return (h % slots_num);
+}
+
size_t Curl_str_key_compare(void *k1, size_t key1_len,
void *k2, size_t key2_len)
-{
+{
if((key1_len == key2_len) && !memcmp(k1, k2, key1_len))
- return 1;
-
- return 0;
-}
-
+ return 1;
+
+ return 0;
+}
+
void Curl_hash_start_iterate(struct Curl_hash *hash,
struct Curl_hash_iterator *iter)
-{
- iter->hash = hash;
- iter->slot_index = 0;
- iter->current_element = NULL;
-}
-
+{
+ iter->hash = hash;
+ iter->slot_index = 0;
+ iter->current_element = NULL;
+}
+
struct Curl_hash_element *
Curl_hash_next_element(struct Curl_hash_iterator *iter)
-{
+{
struct Curl_hash *h = iter->hash;
-
- /* Get the next element in the current list, if any */
- if(iter->current_element)
- iter->current_element = iter->current_element->next;
-
- /* If we have reached the end of the list, find the next one */
- if(!iter->current_element) {
+
+ /* Get the next element in the current list, if any */
+ if(iter->current_element)
+ iter->current_element = iter->current_element->next;
+
+ /* If we have reached the end of the list, find the next one */
+ if(!iter->current_element) {
int i;
for(i = iter->slot_index; i < h->slots; i++) {
if(h->table[i].head) {
iter->current_element = h->table[i].head;
iter->slot_index = i + 1;
- break;
- }
- }
- }
-
- if(iter->current_element) {
+ break;
+ }
+ }
+ }
+
+ if(iter->current_element) {
struct Curl_hash_element *he = iter->current_element->ptr;
- return he;
- }
+ return he;
+ }
iter->current_element = NULL;
return NULL;
-}
-
-#if 0 /* useful function for debugging hashes and their contents */
+}
+
+#if 0 /* useful function for debugging hashes and their contents */
void Curl_hash_print(struct Curl_hash *h,
- void (*func)(void *))
-{
+ void (*func)(void *))
+{
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
- int last_index = -1;
-
- if(!h)
- return;
-
- fprintf(stderr, "=Hash dump=\n");
-
- Curl_hash_start_iterate(h, &iter);
-
- he = Curl_hash_next_element(&iter);
- while(he) {
- if(iter.slot_index != last_index) {
- fprintf(stderr, "index %d:", iter.slot_index);
- if(last_index >= 0) {
- fprintf(stderr, "\n");
- }
- last_index = iter.slot_index;
- }
-
- if(func)
- func(he->ptr);
- else
- fprintf(stderr, " [%p]", (void *)he->ptr);
-
- he = Curl_hash_next_element(&iter);
- }
- fprintf(stderr, "\n");
-}
-#endif
+ int last_index = -1;
+
+ if(!h)
+ return;
+
+ fprintf(stderr, "=Hash dump=\n");
+
+ Curl_hash_start_iterate(h, &iter);
+
+ he = Curl_hash_next_element(&iter);
+ while(he) {
+ if(iter.slot_index != last_index) {
+ fprintf(stderr, "index %d:", iter.slot_index);
+ if(last_index >= 0) {
+ fprintf(stderr, "\n");
+ }
+ last_index = iter.slot_index;
+ }
+
+ if(func)
+ func(he->ptr);
+ else
+ fprintf(stderr, " [%p]", (void *)he->ptr);
+
+ he = Curl_hash_next_element(&iter);
+ }
+ fprintf(stderr, "\n");
+}
+#endif
diff --git a/contrib/libs/curl/lib/hash.h b/contrib/libs/curl/lib/hash.h
index 784433546d..b7f828e071 100644
--- a/contrib/libs/curl/lib/hash.h
+++ b/contrib/libs/curl/lib/hash.h
@@ -1,100 +1,100 @@
-#ifndef HEADER_CURL_HASH_H
-#define HEADER_CURL_HASH_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HASH_H
+#define HEADER_CURL_HASH_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <stddef.h>
-
-#include "llist.h"
-
-/* Hash function prototype */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <stddef.h>
+
+#include "llist.h"
+
+/* Hash function prototype */
typedef size_t (*hash_function) (void *key,
- size_t key_length,
- size_t slots_num);
-
-/*
- Comparator function prototype. Compares two keys.
-*/
+ size_t key_length,
+ size_t slots_num);
+
+/*
+ Comparator function prototype. Compares two keys.
+*/
typedef size_t (*comp_function) (void *key1,
- size_t key1_len,
+ size_t key1_len,
void *key2,
- size_t key2_len);
-
+ size_t key2_len);
+
typedef void (*Curl_hash_dtor)(void *);
-
+
struct Curl_hash {
struct Curl_llist *table;
-
- /* Hash function to be used for this hash table */
- hash_function hash_func;
-
- /* Comparator function to compare keys */
- comp_function comp_func;
+
+ /* Hash function to be used for this hash table */
+ hash_function hash_func;
+
+ /* Comparator function to compare keys */
+ comp_function comp_func;
Curl_hash_dtor dtor;
- int slots;
- size_t size;
-};
-
+ int slots;
+ size_t size;
+};
+
struct Curl_hash_element {
struct Curl_llist_element list;
- void *ptr;
- size_t key_len;
+ void *ptr;
+ size_t key_len;
char key[1]; /* allocated memory following the struct */
-};
-
+};
+
struct Curl_hash_iterator {
struct Curl_hash *hash;
- int slot_index;
+ int slot_index;
struct Curl_llist_element *current_element;
-};
-
+};
+
int Curl_hash_init(struct Curl_hash *h,
- int slots,
- hash_function hfunc,
- comp_function comparator,
+ int slots,
+ hash_function hfunc,
+ comp_function comparator,
Curl_hash_dtor dtor);
-
+
void *Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p);
int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len);
void *Curl_hash_pick(struct Curl_hash *, void *key, size_t key_len);
void Curl_hash_apply(struct Curl_hash *h, void *user,
- void (*cb)(void *user, void *ptr));
+ void (*cb)(void *user, void *ptr));
#define Curl_hash_count(h) ((h)->size)
void Curl_hash_destroy(struct Curl_hash *h);
void Curl_hash_clean(struct Curl_hash *h);
void Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user,
- int (*comp)(void *, void *));
+ int (*comp)(void *, void *));
size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num);
size_t Curl_str_key_compare(void *k1, size_t key1_len, void *k2,
- size_t key2_len);
+ size_t key2_len);
void Curl_hash_start_iterate(struct Curl_hash *hash,
struct Curl_hash_iterator *iter);
struct Curl_hash_element *
Curl_hash_next_element(struct Curl_hash_iterator *iter);
-
+
void Curl_hash_print(struct Curl_hash *h,
- void (*func)(void *));
-
-
-#endif /* HEADER_CURL_HASH_H */
+ void (*func)(void *));
+
+
+#endif /* HEADER_CURL_HASH_H */
diff --git a/contrib/libs/curl/lib/hmac.c b/contrib/libs/curl/lib/hmac.c
index eade80d034..590abe6d2e 100644
--- a/contrib/libs/curl/lib/hmac.c
+++ b/contrib/libs/curl/lib/hmac.c
@@ -1,135 +1,135 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * RFC2104 Keyed-Hashing for Message Authentication
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * RFC2104 Keyed-Hashing for Message Authentication
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+
#include <curl/curl.h>
-#include "curl_hmac.h"
+#include "curl_hmac.h"
#include "curl_memory.h"
#include "warnless.h"
-
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * Generic HMAC algorithm.
- *
- * This module computes HMAC digests based on any hash function. Parameters
- * and computing procedures are set-up dynamically at HMAC computation
- * context initialisation.
- */
-
-static const unsigned char hmac_ipad = 0x36;
-static const unsigned char hmac_opad = 0x5C;
-
-
-
+
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * Generic HMAC algorithm.
+ *
+ * This module computes HMAC digests based on any hash function. Parameters
+ * and computing procedures are set-up dynamically at HMAC computation
+ * context initialisation.
+ */
+
+static const unsigned char hmac_ipad = 0x36;
+static const unsigned char hmac_opad = 0x5C;
+
+
+
struct HMAC_context *
Curl_HMAC_init(const struct HMAC_params *hashparams,
const unsigned char *key,
- unsigned int keylen)
-{
- size_t i;
+ unsigned int keylen)
+{
+ size_t i;
struct HMAC_context *ctxt;
unsigned char *hkey;
- unsigned char b;
-
- /* Create HMAC context. */
+ unsigned char b;
+
+ /* Create HMAC context. */
i = sizeof(*ctxt) + 2 * hashparams->hmac_ctxtsize +
- hashparams->hmac_resultlen;
- ctxt = malloc(i);
-
- if(!ctxt)
- return ctxt;
-
- ctxt->hmac_hash = hashparams;
- ctxt->hmac_hashctxt1 = (void *) (ctxt + 1);
- ctxt->hmac_hashctxt2 = (void *) ((char *) ctxt->hmac_hashctxt1 +
- hashparams->hmac_ctxtsize);
-
- /* If the key is too long, replace it by its hash digest. */
- if(keylen > hashparams->hmac_maxkeylen) {
- (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1);
- (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, key, keylen);
- hkey = (unsigned char *) ctxt->hmac_hashctxt2 + hashparams->hmac_ctxtsize;
- (*hashparams->hmac_hfinal)(hkey, ctxt->hmac_hashctxt1);
- key = hkey;
- keylen = hashparams->hmac_resultlen;
- }
-
- /* Prime the two hash contexts with the modified key. */
- (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1);
- (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt2);
-
- for(i = 0; i < keylen; i++) {
- b = (unsigned char)(*key ^ hmac_ipad);
- (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &b, 1);
- b = (unsigned char)(*key++ ^ hmac_opad);
- (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &b, 1);
- }
-
- for(; i < hashparams->hmac_maxkeylen; i++) {
- (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &hmac_ipad, 1);
- (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &hmac_opad, 1);
- }
-
- /* Done, return pointer to HMAC context. */
- return ctxt;
-}
-
+ hashparams->hmac_resultlen;
+ ctxt = malloc(i);
+
+ if(!ctxt)
+ return ctxt;
+
+ ctxt->hmac_hash = hashparams;
+ ctxt->hmac_hashctxt1 = (void *) (ctxt + 1);
+ ctxt->hmac_hashctxt2 = (void *) ((char *) ctxt->hmac_hashctxt1 +
+ hashparams->hmac_ctxtsize);
+
+ /* If the key is too long, replace it by its hash digest. */
+ if(keylen > hashparams->hmac_maxkeylen) {
+ (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1);
+ (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, key, keylen);
+ hkey = (unsigned char *) ctxt->hmac_hashctxt2 + hashparams->hmac_ctxtsize;
+ (*hashparams->hmac_hfinal)(hkey, ctxt->hmac_hashctxt1);
+ key = hkey;
+ keylen = hashparams->hmac_resultlen;
+ }
+
+ /* Prime the two hash contexts with the modified key. */
+ (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1);
+ (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt2);
+
+ for(i = 0; i < keylen; i++) {
+ b = (unsigned char)(*key ^ hmac_ipad);
+ (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &b, 1);
+ b = (unsigned char)(*key++ ^ hmac_opad);
+ (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &b, 1);
+ }
+
+ for(; i < hashparams->hmac_maxkeylen; i++) {
+ (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &hmac_ipad, 1);
+ (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &hmac_opad, 1);
+ }
+
+ /* Done, return pointer to HMAC context. */
+ return ctxt;
+}
+
int Curl_HMAC_update(struct HMAC_context *ctxt,
const unsigned char *data,
- unsigned int len)
-{
- /* Update first hash calculation. */
- (*ctxt->hmac_hash->hmac_hupdate)(ctxt->hmac_hashctxt1, data, len);
- return 0;
-}
-
-
+ unsigned int len)
+{
+ /* Update first hash calculation. */
+ (*ctxt->hmac_hash->hmac_hupdate)(ctxt->hmac_hashctxt1, data, len);
+ return 0;
+}
+
+
int Curl_HMAC_final(struct HMAC_context *ctxt, unsigned char *result)
-{
+{
const struct HMAC_params *hashparams = ctxt->hmac_hash;
-
- /* Do not get result if called with a null parameter: only release
- storage. */
-
- if(!result)
- result = (unsigned char *) ctxt->hmac_hashctxt2 +
- ctxt->hmac_hash->hmac_ctxtsize;
-
- (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt1);
- (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2,
- result, hashparams->hmac_resultlen);
- (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt2);
- free((char *) ctxt);
- return 0;
-}
-
+
+ /* Do not get result if called with a null parameter: only release
+ storage. */
+
+ if(!result)
+ result = (unsigned char *) ctxt->hmac_hashctxt2 +
+ ctxt->hmac_hash->hmac_ctxtsize;
+
+ (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt1);
+ (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2,
+ result, hashparams->hmac_resultlen);
+ (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt2);
+ free((char *) ctxt);
+ return 0;
+}
+
/*
* Curl_hmacit()
*
@@ -167,4 +167,4 @@ CURLcode Curl_hmacit(const struct HMAC_params *hashparams,
return CURLE_OK;
}
-#endif /* CURL_DISABLE_CRYPTO_AUTH */
+#endif /* CURL_DISABLE_CRYPTO_AUTH */
diff --git a/contrib/libs/curl/lib/hostasyn.c b/contrib/libs/curl/lib/hostasyn.c
index 318ddc1fb8..56a6fc2b72 100644
--- a/contrib/libs/curl/lib/hostasyn.c
+++ b/contrib/libs/curl/lib/hostasyn.c
@@ -1,128 +1,128 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
/***********************************************************************
* Only for builds using asynchronous name resolves
**********************************************************************/
#ifdef CURLRES_ASYNCH
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * Curl_addrinfo_callback() gets called by ares, gethostbyname_thread()
- * or getaddrinfo_thread() when we got the name resolved (or not!).
- *
- * If the status argument is CURL_ASYNC_SUCCESS, this function takes
- * ownership of the Curl_addrinfo passed, storing the resolved data
- * in the DNS cache.
- *
- * The storage operation locks and unlocks the DNS cache.
- */
-CURLcode Curl_addrinfo_callback(struct connectdata *conn,
- int status,
- struct Curl_addrinfo *ai)
-{
- struct Curl_dns_entry *dns = NULL;
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#ifdef HAVE_PROCESS_H
+#include <process.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * Curl_addrinfo_callback() gets called by ares, gethostbyname_thread()
+ * or getaddrinfo_thread() when we got the name resolved (or not!).
+ *
+ * If the status argument is CURL_ASYNC_SUCCESS, this function takes
+ * ownership of the Curl_addrinfo passed, storing the resolved data
+ * in the DNS cache.
+ *
+ * The storage operation locks and unlocks the DNS cache.
+ */
+CURLcode Curl_addrinfo_callback(struct connectdata *conn,
+ int status,
+ struct Curl_addrinfo *ai)
+{
+ struct Curl_dns_entry *dns = NULL;
CURLcode result = CURLE_OK;
-
- conn->async.status = status;
-
- if(CURL_ASYNC_SUCCESS == status) {
- if(ai) {
+
+ conn->async.status = status;
+
+ if(CURL_ASYNC_SUCCESS == status) {
+ if(ai) {
struct Curl_easy *data = conn->data;
-
- if(data->share)
- Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
- dns = Curl_cache_addr(data, ai,
- conn->async.hostname,
- conn->async.port);
+
+ if(data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
+ dns = Curl_cache_addr(data, ai,
+ conn->async.hostname,
+ conn->async.port);
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
- if(!dns) {
- /* failed to store, cleanup and return error */
- Curl_freeaddrinfo(ai);
+ if(!dns) {
+ /* failed to store, cleanup and return error */
+ Curl_freeaddrinfo(ai);
result = CURLE_OUT_OF_MEMORY;
- }
- }
- else {
+ }
+ }
+ else {
result = CURLE_OUT_OF_MEMORY;
- }
- }
-
- conn->async.dns = dns;
-
- /* Set async.done TRUE last in this function since it may be used multi-
- threaded and once this is TRUE the other thread may read fields from the
- async struct */
- conn->async.done = TRUE;
-
+ }
+ }
+
+ conn->async.dns = dns;
+
+ /* Set async.done TRUE last in this function since it may be used multi-
+ threaded and once this is TRUE the other thread may read fields from the
+ async struct */
+ conn->async.done = TRUE;
+
/* IPv4: The input hostent struct will be freed by ares when we return from
- this function */
+ this function */
return result;
-}
-
-/*
- * Curl_getaddrinfo() is the generic low-level name resolve API within this
- * source file. There are several versions of this function - for different
- * name resolve layers (selected at build-time). They all take this same set
- * of arguments
- */
+}
+
+/*
+ * Curl_getaddrinfo() is the generic low-level name resolve API within this
+ * source file. There are several versions of this function - for different
+ * name resolve layers (selected at build-time). They all take this same set
+ * of arguments
+ */
struct Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp)
-{
- return Curl_resolver_getaddrinfo(conn, hostname, port, waitp);
-}
-
-#endif /* CURLRES_ASYNCH */
+{
+ return Curl_resolver_getaddrinfo(conn, hostname, port, waitp);
+}
+
+#endif /* CURLRES_ASYNCH */
diff --git a/contrib/libs/curl/lib/hostcheck.c b/contrib/libs/curl/lib/hostcheck.c
index 43b1ed7dae..4d0614aeab 100644
--- a/contrib/libs/curl/lib/hostcheck.c
+++ b/contrib/libs/curl/lib/hostcheck.c
@@ -1,32 +1,32 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if defined(USE_OPENSSL) \
|| defined(USE_GSKIT) \
|| defined(USE_SCHANNEL)
-/* these backends use functions from this file */
-
+/* these backends use functions from this file */
+
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
@@ -34,20 +34,20 @@
#error #include <netinet/in6.h>
#endif
-#include "hostcheck.h"
+#include "hostcheck.h"
#include "strcase.h"
#include "inet_pton.h"
-
+
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
-/*
- * Match a hostname against a wildcard pattern.
- * E.g.
- * "foo.host.com" matches "*.host.com".
- *
- * We use the matching rule described in RFC6125, section 6.4.3.
+/*
+ * Match a hostname against a wildcard pattern.
+ * E.g.
+ * "foo.host.com" matches "*.host.com".
+ *
+ * We use the matching rule described in RFC6125, section 6.4.3.
* https://tools.ietf.org/html/rfc6125#section-6.4.3
*
* In addition: ignore trailing dots in the host names and wildcards, so that
@@ -60,13 +60,13 @@
*
* NOTE: hostmatch() gets called with copied buffers so that it can modify the
* contents at will.
- */
-
+ */
+
static int hostmatch(char *hostname, char *pattern)
-{
- const char *pattern_label_end, *pattern_wildcard, *hostname_label_end;
- int wildcard_enabled;
- size_t prefixlen, suffixlen;
+{
+ const char *pattern_label_end, *pattern_wildcard, *hostname_label_end;
+ int wildcard_enabled;
+ size_t prefixlen, suffixlen;
struct in_addr ignored;
#ifdef ENABLE_IPV6
struct sockaddr_in6 si6;
@@ -80,11 +80,11 @@ static int hostmatch(char *hostname, char *pattern)
if(pattern[len-1]=='.')
pattern[len-1] = 0;
- pattern_wildcard = strchr(pattern, '*');
- if(pattern_wildcard == NULL)
+ pattern_wildcard = strchr(pattern, '*');
+ if(pattern_wildcard == NULL)
return strcasecompare(pattern, hostname) ?
- CURL_HOST_MATCH : CURL_HOST_NOMATCH;
-
+ CURL_HOST_MATCH : CURL_HOST_NOMATCH;
+
/* detect IP address as hostname and fail the match if so */
if(Curl_inet_pton(AF_INET, hostname, &ignored) > 0)
return CURL_HOST_NOMATCH;
@@ -93,43 +93,43 @@ static int hostmatch(char *hostname, char *pattern)
return CURL_HOST_NOMATCH;
#endif
- /* We require at least 2 dots in pattern to avoid too wide wildcard
- match. */
- wildcard_enabled = 1;
- pattern_label_end = strchr(pattern, '.');
+ /* We require at least 2 dots in pattern to avoid too wide wildcard
+ match. */
+ wildcard_enabled = 1;
+ pattern_label_end = strchr(pattern, '.');
if(pattern_label_end == NULL || strchr(pattern_label_end + 1, '.') == NULL ||
- pattern_wildcard > pattern_label_end ||
+ pattern_wildcard > pattern_label_end ||
strncasecompare(pattern, "xn--", 4)) {
- wildcard_enabled = 0;
- }
- if(!wildcard_enabled)
+ wildcard_enabled = 0;
+ }
+ if(!wildcard_enabled)
return strcasecompare(pattern, hostname) ?
- CURL_HOST_MATCH : CURL_HOST_NOMATCH;
-
- hostname_label_end = strchr(hostname, '.');
- if(hostname_label_end == NULL ||
+ CURL_HOST_MATCH : CURL_HOST_NOMATCH;
+
+ hostname_label_end = strchr(hostname, '.');
+ if(hostname_label_end == NULL ||
!strcasecompare(pattern_label_end, hostname_label_end))
- return CURL_HOST_NOMATCH;
-
- /* The wildcard must match at least one character, so the left-most
- label of the hostname is at least as large as the left-most label
- of the pattern. */
- if(hostname_label_end - hostname < pattern_label_end - pattern)
- return CURL_HOST_NOMATCH;
-
- prefixlen = pattern_wildcard - pattern;
+ return CURL_HOST_NOMATCH;
+
+ /* The wildcard must match at least one character, so the left-most
+ label of the hostname is at least as large as the left-most label
+ of the pattern. */
+ if(hostname_label_end - hostname < pattern_label_end - pattern)
+ return CURL_HOST_NOMATCH;
+
+ prefixlen = pattern_wildcard - pattern;
suffixlen = pattern_label_end - (pattern_wildcard + 1);
return strncasecompare(pattern, hostname, prefixlen) &&
strncasecompare(pattern_wildcard + 1, hostname_label_end - suffixlen,
- suffixlen) ?
- CURL_HOST_MATCH : CURL_HOST_NOMATCH;
-}
-
-int Curl_cert_hostcheck(const char *match_pattern, const char *hostname)
-{
+ suffixlen) ?
+ CURL_HOST_MATCH : CURL_HOST_NOMATCH;
+}
+
+int Curl_cert_hostcheck(const char *match_pattern, const char *hostname)
+{
int res = 0;
- if(!match_pattern || !*match_pattern ||
- !hostname || !*hostname) /* sanity check */
+ if(!match_pattern || !*match_pattern ||
+ !hostname || !*hostname) /* sanity check */
;
else {
char *matchp = strdup(match_pattern);
@@ -143,8 +143,8 @@ int Curl_cert_hostcheck(const char *match_pattern, const char *hostname)
free(matchp);
}
}
-
+
return res;
-}
-
+}
+
#endif /* OPENSSL, GSKIT or schannel+wince */
diff --git a/contrib/libs/curl/lib/hostcheck.h b/contrib/libs/curl/lib/hostcheck.h
index f2b726f163..52155f43b4 100644
--- a/contrib/libs/curl/lib/hostcheck.h
+++ b/contrib/libs/curl/lib/hostcheck.h
@@ -1,31 +1,31 @@
-#ifndef HEADER_CURL_HOSTCHECK_H
-#define HEADER_CURL_HOSTCHECK_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HOSTCHECK_H
+#define HEADER_CURL_HOSTCHECK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <curl/curl.h>
-
-#define CURL_HOST_NOMATCH 0
-#define CURL_HOST_MATCH 1
-int Curl_cert_hostcheck(const char *match_pattern, const char *hostname);
-
-#endif /* HEADER_CURL_HOSTCHECK_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <curl/curl.h>
+
+#define CURL_HOST_NOMATCH 0
+#define CURL_HOST_MATCH 1
+int Curl_cert_hostcheck(const char *match_pattern, const char *hostname);
+
+#endif /* HEADER_CURL_HOSTCHECK_H */
diff --git a/contrib/libs/curl/lib/hostip.c b/contrib/libs/curl/lib/hostip.c
index 7d820c8166..c6435f1f97 100644
--- a/contrib/libs/curl/lib/hostip.c
+++ b/contrib/libs/curl/lib/hostip.c
@@ -1,148 +1,148 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
#ifdef HAVE_NETINET_IN6_H
#error #include <netinet/in6.h>
#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#ifdef HAVE_SETJMP_H
-#include <setjmp.h>
-#endif
-#ifdef HAVE_SIGNAL_H
-#include <signal.h>
-#endif
-
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#ifdef HAVE_SETJMP_H
+#include <setjmp.h>
+#endif
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif
+
+#ifdef HAVE_PROCESS_H
+#include <process.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
#include "rand.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
-#include "inet_ntop.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
+#include "inet_ntop.h"
#include "inet_pton.h"
#include "multiif.h"
#include "doh.h"
-#include "warnless.h"
+#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-#if defined(CURLRES_SYNCH) && \
- defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
-/* alarm-based timeouts can only be used with all the dependencies satisfied */
-#define USE_ALARM_TIMEOUT
-#endif
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#if defined(CURLRES_SYNCH) && \
+ defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
+/* alarm-based timeouts can only be used with all the dependencies satisfied */
+#define USE_ALARM_TIMEOUT
+#endif
+
#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */
-/*
- * hostip.c explained
- * ==================
- *
- * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
- * source file are these:
- *
- * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
- * that. The host may not be able to resolve IPv6, but we don't really have to
- * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
- * defined.
- *
- * CURLRES_ARES - is defined if libcurl is built to use c-ares for
- * asynchronous name resolves. This can be Windows or *nix.
- *
- * CURLRES_THREADED - is defined if libcurl is built to run under (native)
- * Windows, and then the name resolve will be done in a new thread, and the
- * supported API will be the same as for ares-builds.
- *
- * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
- * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
- * defined.
- *
- * The host*.c sources files are split up like this:
- *
- * hostip.c - method-independent resolver functions and utility functions
- * hostasyn.c - functions for asynchronous name resolves
- * hostsyn.c - functions for synchronous name resolves
+/*
+ * hostip.c explained
+ * ==================
+ *
+ * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
+ * source file are these:
+ *
+ * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
+ * that. The host may not be able to resolve IPv6, but we don't really have to
+ * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
+ * defined.
+ *
+ * CURLRES_ARES - is defined if libcurl is built to use c-ares for
+ * asynchronous name resolves. This can be Windows or *nix.
+ *
+ * CURLRES_THREADED - is defined if libcurl is built to run under (native)
+ * Windows, and then the name resolve will be done in a new thread, and the
+ * supported API will be the same as for ares-builds.
+ *
+ * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
+ * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
+ * defined.
+ *
+ * The host*.c sources files are split up like this:
+ *
+ * hostip.c - method-independent resolver functions and utility functions
+ * hostasyn.c - functions for asynchronous name resolves
+ * hostsyn.c - functions for synchronous name resolves
* hostip4.c - IPv4 specific functions
* hostip6.c - IPv6 specific functions
- *
- * The two asynchronous name resolver backends are implemented in:
- * asyn-ares.c - functions for ares-using name resolves
- * asyn-thread.c - functions for threaded name resolves
-
- * The hostip.h is the united header file for all this. It defines the
- * CURLRES_* defines based on the config*.h and curl_setup.h defines.
- */
-
-static void freednsentry(void *freethis);
-
-/*
+ *
+ * The two asynchronous name resolver backends are implemented in:
+ * asyn-ares.c - functions for ares-using name resolves
+ * asyn-thread.c - functions for threaded name resolves
+
+ * The hostip.h is the united header file for all this. It defines the
+ * CURLRES_* defines based on the config*.h and curl_setup.h defines.
+ */
+
+static void freednsentry(void *freethis);
+
+/*
* Return # of addresses in a Curl_addrinfo struct
- */
+ */
int Curl_num_addresses(const struct Curl_addrinfo *addr)
-{
- int i = 0;
- while(addr) {
- addr = addr->ai_next;
- i++;
- }
- return i;
-}
-
-/*
+{
+ int i = 0;
+ while(addr) {
+ addr = addr->ai_next;
+ i++;
+ }
+ return i;
+}
+
+/*
* Curl_printable_address() stores a printable version of the 1st address
- * given in the 'ai' argument. The result will be stored in the buf that is
- * bufsize bytes big.
- *
+ * given in the 'ai' argument. The result will be stored in the buf that is
+ * bufsize bytes big.
+ *
* If the conversion fails, the target buffer is empty.
- */
+ */
void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf,
size_t bufsize)
-{
+{
DEBUGASSERT(bufsize);
buf[0] = 0;
-
+
switch(ai->ai_family) {
case AF_INET: {
const struct sockaddr_in *sa4 = (const void *)ai->ai_addr;
@@ -150,26 +150,26 @@ void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf,
(void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize);
break;
}
-#ifdef ENABLE_IPV6
+#ifdef ENABLE_IPV6
case AF_INET6: {
const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr;
const struct in6_addr *ipaddr6 = &sa6->sin6_addr;
(void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize);
break;
}
-#endif
+#endif
default:
break;
- }
-}
-
-/*
+ }
+}
+
+/*
* Create a hostcache id string for the provided host + port, to be used by
* the DNS caching. Without alloc.
- */
+ */
static void
create_hostcache_id(const char *name, int port, char *ptr, size_t buflen)
-{
+{
size_t len = strlen(name);
if(len > (buflen - 7))
len = buflen - 7;
@@ -177,74 +177,74 @@ create_hostcache_id(const char *name, int port, char *ptr, size_t buflen)
while(len--)
*ptr++ = (char)TOLOWER(*name++);
msnprintf(ptr, 7, ":%u", port);
-}
-
-struct hostcache_prune_data {
- long cache_timeout;
- time_t now;
-};
-
-/*
- * This function is set as a callback to be called for every entry in the DNS
- * cache when we want to prune old unused entries.
- *
- * Returning non-zero means remove the entry, return 0 to keep it in the
- * cache.
- */
-static int
-hostcache_timestamp_remove(void *datap, void *hc)
-{
- struct hostcache_prune_data *data =
- (struct hostcache_prune_data *) datap;
- struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
-
+}
+
+struct hostcache_prune_data {
+ long cache_timeout;
+ time_t now;
+};
+
+/*
+ * This function is set as a callback to be called for every entry in the DNS
+ * cache when we want to prune old unused entries.
+ *
+ * Returning non-zero means remove the entry, return 0 to keep it in the
+ * cache.
+ */
+static int
+hostcache_timestamp_remove(void *datap, void *hc)
+{
+ struct hostcache_prune_data *data =
+ (struct hostcache_prune_data *) datap;
+ struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
+
return (0 != c->timestamp)
&& (data->now - c->timestamp >= data->cache_timeout);
-}
-
-/*
- * Prune the DNS cache. This assumes that a lock has already been taken.
- */
-static void
+}
+
+/*
+ * Prune the DNS cache. This assumes that a lock has already been taken.
+ */
+static void
hostcache_prune(struct Curl_hash *hostcache, long cache_timeout, time_t now)
-{
- struct hostcache_prune_data user;
-
- user.cache_timeout = cache_timeout;
- user.now = now;
-
- Curl_hash_clean_with_criterium(hostcache,
- (void *) &user,
- hostcache_timestamp_remove);
-}
-
-/*
- * Library-wide function for pruning the DNS cache. This function takes and
- * returns the appropriate locks.
- */
+{
+ struct hostcache_prune_data user;
+
+ user.cache_timeout = cache_timeout;
+ user.now = now;
+
+ Curl_hash_clean_with_criterium(hostcache,
+ (void *) &user,
+ hostcache_timestamp_remove);
+}
+
+/*
+ * Library-wide function for pruning the DNS cache. This function takes and
+ * returns the appropriate locks.
+ */
void Curl_hostcache_prune(struct Curl_easy *data)
-{
- time_t now;
-
- if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
- /* cache forever means never prune, and NULL hostcache means
- we can't do it */
- return;
-
- if(data->share)
- Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
- time(&now);
-
- /* Remove outdated and unused entries from the hostcache */
- hostcache_prune(data->dns.hostcache,
- data->set.dns_cache_timeout,
- now);
-
- if(data->share)
- Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-}
-
+{
+ time_t now;
+
+ if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
+ /* cache forever means never prune, and NULL hostcache means
+ we can't do it */
+ return;
+
+ if(data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
+ time(&now);
+
+ /* Remove outdated and unused entries from the hostcache */
+ hostcache_prune(data->dns.hostcache,
+ data->set.dns_cache_timeout,
+ now);
+
+ if(data->share)
+ Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
+}
+
#ifdef HAVE_SIGSETJMP
/* Beware this is a global and unique instance. This is used to store the
return address that we can jump back to from inside a signal handler. This
@@ -296,7 +296,7 @@ fetch_addr(struct connectdata *conn,
return dns;
}
-/*
+/*
* Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
*
* Curl_resolv() checks initially and multi_runsingle() checks each time
@@ -309,29 +309,29 @@ fetch_addr(struct connectdata *conn,
*
* The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
* use, or we'll leak memory!
- */
+ */
struct Curl_dns_entry *
Curl_fetch_addr(struct connectdata *conn,
const char *hostname,
int port)
-{
+{
struct Curl_easy *data = conn->data;
struct Curl_dns_entry *dns = NULL;
-
+
if(data->share)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
+
dns = fetch_addr(conn, hostname, port);
-
+
if(dns)
dns->inuse++; /* we use it! */
-
+
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-
+
return dns;
-}
-
+}
+
#ifndef CURL_DISABLE_SHUFFLE_DNS
UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
struct Curl_addrinfo **addr);
@@ -352,17 +352,17 @@ UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
{
CURLcode result = CURLE_OK;
const int num_addrs = Curl_num_addresses(*addr);
-
+
if(num_addrs > 1) {
struct Curl_addrinfo **nodes;
infof(data, "Shuffling %i addresses", num_addrs);
-
+
nodes = malloc(num_addrs*sizeof(*nodes));
if(nodes) {
int i;
unsigned int *rnd;
const size_t rnd_size = num_addrs * sizeof(*rnd);
-
+
/* build a plain array of Curl_addrinfo pointers */
nodes[0] = *addr;
for(i = 1; i < num_addrs; i++) {
@@ -401,26 +401,26 @@ UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
}
#endif
-/*
- * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
- *
- * When calling Curl_resolv() has resulted in a response with a returned
- * address, we call this function to store the information in the dns
- * cache etc
- *
- * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
- */
-struct Curl_dns_entry *
+/*
+ * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
+ *
+ * When calling Curl_resolv() has resulted in a response with a returned
+ * address, we call this function to store the information in the dns
+ * cache etc
+ *
+ * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
+ */
+struct Curl_dns_entry *
Curl_cache_addr(struct Curl_easy *data,
struct Curl_addrinfo *addr,
- const char *hostname,
- int port)
-{
+ const char *hostname,
+ int port)
+{
char entry_id[MAX_HOSTCACHE_LEN];
- size_t entry_len;
- struct Curl_dns_entry *dns;
- struct Curl_dns_entry *dns2;
-
+ size_t entry_len;
+ struct Curl_dns_entry *dns;
+ struct Curl_dns_entry *dns2;
+
#ifndef CURL_DISABLE_SHUFFLE_DNS
/* shuffle addresses if requested */
if(data->set.dns_shuffle_addresses) {
@@ -430,87 +430,87 @@ Curl_cache_addr(struct Curl_easy *data,
}
#endif
- /* Create a new cache entry */
- dns = calloc(1, sizeof(struct Curl_dns_entry));
- if(!dns) {
- return NULL;
- }
-
+ /* Create a new cache entry */
+ dns = calloc(1, sizeof(struct Curl_dns_entry));
+ if(!dns) {
+ return NULL;
+ }
+
/* Create an entry id, based upon the hostname and port */
create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
entry_len = strlen(entry_id);
dns->inuse = 1; /* the cache has the first reference */
- dns->addr = addr; /* this is the address(es) */
- time(&dns->timestamp);
- if(dns->timestamp == 0)
+ dns->addr = addr; /* this is the address(es) */
+ time(&dns->timestamp);
+ if(dns->timestamp == 0)
dns->timestamp = 1; /* zero indicates CURLOPT_RESOLVE entry */
-
- /* Store the resolved data in our DNS cache. */
+
+ /* Store the resolved data in our DNS cache. */
dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
- (void *)dns);
- if(!dns2) {
- free(dns);
- return NULL;
- }
-
- dns = dns2;
- dns->inuse++; /* mark entry as in-use */
- return dns;
-}
-
-/*
- * Curl_resolv() is the main name resolve function within libcurl. It resolves
- * a name and returns a pointer to the entry in the 'entry' argument (if one
- * is provided). This function might return immediately if we're using asynch
- * resolves. See the return codes.
- *
- * The cache entry we return will get its 'inuse' counter increased when this
- * function is used. You MUST call Curl_resolv_unlock() later (when you're
- * done using this struct) to decrease the counter again.
- *
- * In debug mode, we specifically test for an interface name "LocalHost"
- * and resolve "localhost" instead as a means to permit test cases
- * to connect to a local test server with any host name.
- *
- * Return codes:
- *
- * CURLRESOLV_ERROR (-1) = error, no pointer
- * CURLRESOLV_RESOLVED (0) = OK, pointer provided
- * CURLRESOLV_PENDING (1) = waiting for response, no pointer
- */
-
+ (void *)dns);
+ if(!dns2) {
+ free(dns);
+ return NULL;
+ }
+
+ dns = dns2;
+ dns->inuse++; /* mark entry as in-use */
+ return dns;
+}
+
+/*
+ * Curl_resolv() is the main name resolve function within libcurl. It resolves
+ * a name and returns a pointer to the entry in the 'entry' argument (if one
+ * is provided). This function might return immediately if we're using asynch
+ * resolves. See the return codes.
+ *
+ * The cache entry we return will get its 'inuse' counter increased when this
+ * function is used. You MUST call Curl_resolv_unlock() later (when you're
+ * done using this struct) to decrease the counter again.
+ *
+ * In debug mode, we specifically test for an interface name "LocalHost"
+ * and resolve "localhost" instead as a means to permit test cases
+ * to connect to a local test server with any host name.
+ *
+ * Return codes:
+ *
+ * CURLRESOLV_ERROR (-1) = error, no pointer
+ * CURLRESOLV_RESOLVED (0) = OK, pointer provided
+ * CURLRESOLV_PENDING (1) = waiting for response, no pointer
+ */
+
enum resolve_t Curl_resolv(struct connectdata *conn,
const char *hostname,
int port,
bool allowDOH,
struct Curl_dns_entry **entry)
-{
- struct Curl_dns_entry *dns = NULL;
+{
+ struct Curl_dns_entry *dns = NULL;
struct Curl_easy *data = conn->data;
- CURLcode result;
+ CURLcode result;
enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */
-
- *entry = NULL;
+
+ *entry = NULL;
conn->bits.doh = FALSE; /* default is not */
-
- if(data->share)
- Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
+
+ if(data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
dns = fetch_addr(conn, hostname, port);
-
- if(dns) {
+
+ if(dns) {
infof(data, "Hostname %s was found in DNS cache\n", hostname);
- dns->inuse++; /* we use it! */
- rc = CURLRESOLV_RESOLVED;
- }
-
- if(data->share)
- Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-
- if(!dns) {
- /* The entry was not in the cache. Resolve it to IP address */
-
+ dns->inuse++; /* we use it! */
+ rc = CURLRESOLV_RESOLVED;
+ }
+
+ if(data->share)
+ Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
+
+ if(!dns) {
+ /* The entry was not in the cache. Resolve it to IP address */
+
struct Curl_addrinfo *addr = NULL;
int respwait = 0;
struct in_addr in;
@@ -518,7 +518,7 @@ enum resolve_t Curl_resolv(struct connectdata *conn,
const
#endif
bool ipnum = FALSE;
-
+
/* notify the resolver start callback */
if(data->set.resolver_start) {
int st;
@@ -576,147 +576,147 @@ enum resolve_t Curl_resolv(struct connectdata *conn,
non-zero value indicating that we need to wait for the response to
the resolve call */
addr = Curl_getaddrinfo(conn,
-#ifdef DEBUGBUILD
+#ifdef DEBUGBUILD
(data->set.str[STRING_DEVICE]
&& !strcmp(data->set.str[STRING_DEVICE],
"LocalHost"))?"localhost":
-#endif
+#endif
hostname, port, &respwait);
}
}
- if(!addr) {
- if(respwait) {
- /* the response to our resolve call will come asynchronously at
- a later time, good or bad */
- /* First, check that we haven't received the info by now */
+ if(!addr) {
+ if(respwait) {
+ /* the response to our resolve call will come asynchronously at
+ a later time, good or bad */
+ /* First, check that we haven't received the info by now */
result = Curl_resolv_check(conn, &dns);
- if(result) /* error detected */
- return CURLRESOLV_ERROR;
- if(dns)
- rc = CURLRESOLV_RESOLVED; /* pointer provided */
- else
- rc = CURLRESOLV_PENDING; /* no info yet */
- }
- }
- else {
- if(data->share)
- Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
- /* we got a response, store it in the cache */
- dns = Curl_cache_addr(data, addr, hostname, port);
-
- if(data->share)
- Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-
- if(!dns)
- /* returned failure, bail out nicely */
- Curl_freeaddrinfo(addr);
- else
- rc = CURLRESOLV_RESOLVED;
- }
- }
-
- *entry = dns;
-
- return rc;
-}
-
-#ifdef USE_ALARM_TIMEOUT
-/*
- * This signal handler jumps back into the main libcurl code and continues
- * execution. This effectively causes the remainder of the application to run
- * within a signal handler which is nonportable and could lead to problems.
- */
-static
-RETSIGTYPE alarmfunc(int sig)
-{
- /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
- (void)sig;
- siglongjmp(curl_jmpenv, 1);
-}
-#endif /* USE_ALARM_TIMEOUT */
-
-/*
- * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
- * timeout. This function might return immediately if we're using asynch
- * resolves. See the return codes.
- *
- * The cache entry we return will get its 'inuse' counter increased when this
- * function is used. You MUST call Curl_resolv_unlock() later (when you're
- * done using this struct) to decrease the counter again.
- *
- * If built with a synchronous resolver and use of signals is not
- * disabled by the application, then a nonzero timeout will cause a
- * timeout after the specified number of milliseconds. Otherwise, timeout
- * is ignored.
- *
- * Return codes:
- *
- * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
- * CURLRESOLV_ERROR (-1) = error, no pointer
- * CURLRESOLV_RESOLVED (0) = OK, pointer provided
- * CURLRESOLV_PENDING (1) = waiting for response, no pointer
- */
-
+ if(result) /* error detected */
+ return CURLRESOLV_ERROR;
+ if(dns)
+ rc = CURLRESOLV_RESOLVED; /* pointer provided */
+ else
+ rc = CURLRESOLV_PENDING; /* no info yet */
+ }
+ }
+ else {
+ if(data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
+ /* we got a response, store it in the cache */
+ dns = Curl_cache_addr(data, addr, hostname, port);
+
+ if(data->share)
+ Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
+
+ if(!dns)
+ /* returned failure, bail out nicely */
+ Curl_freeaddrinfo(addr);
+ else
+ rc = CURLRESOLV_RESOLVED;
+ }
+ }
+
+ *entry = dns;
+
+ return rc;
+}
+
+#ifdef USE_ALARM_TIMEOUT
+/*
+ * This signal handler jumps back into the main libcurl code and continues
+ * execution. This effectively causes the remainder of the application to run
+ * within a signal handler which is nonportable and could lead to problems.
+ */
+static
+RETSIGTYPE alarmfunc(int sig)
+{
+ /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
+ (void)sig;
+ siglongjmp(curl_jmpenv, 1);
+}
+#endif /* USE_ALARM_TIMEOUT */
+
+/*
+ * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
+ * timeout. This function might return immediately if we're using asynch
+ * resolves. See the return codes.
+ *
+ * The cache entry we return will get its 'inuse' counter increased when this
+ * function is used. You MUST call Curl_resolv_unlock() later (when you're
+ * done using this struct) to decrease the counter again.
+ *
+ * If built with a synchronous resolver and use of signals is not
+ * disabled by the application, then a nonzero timeout will cause a
+ * timeout after the specified number of milliseconds. Otherwise, timeout
+ * is ignored.
+ *
+ * Return codes:
+ *
+ * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
+ * CURLRESOLV_ERROR (-1) = error, no pointer
+ * CURLRESOLV_RESOLVED (0) = OK, pointer provided
+ * CURLRESOLV_PENDING (1) = waiting for response, no pointer
+ */
+
enum resolve_t Curl_resolv_timeout(struct connectdata *conn,
const char *hostname,
int port,
struct Curl_dns_entry **entry,
timediff_t timeoutms)
-{
-#ifdef USE_ALARM_TIMEOUT
-#ifdef HAVE_SIGACTION
- struct sigaction keep_sigact; /* store the old struct here */
+{
+#ifdef USE_ALARM_TIMEOUT
+#ifdef HAVE_SIGACTION
+ struct sigaction keep_sigact; /* store the old struct here */
volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
- struct sigaction sigact;
-#else
-#ifdef HAVE_SIGNAL
- void (*keep_sigact)(int); /* store the old handler here */
-#endif /* HAVE_SIGNAL */
-#endif /* HAVE_SIGACTION */
- volatile long timeout;
- volatile unsigned int prev_alarm = 0;
+ struct sigaction sigact;
+#else
+#ifdef HAVE_SIGNAL
+ void (*keep_sigact)(int); /* store the old handler here */
+#endif /* HAVE_SIGNAL */
+#endif /* HAVE_SIGACTION */
+ volatile long timeout;
+ volatile unsigned int prev_alarm = 0;
struct Curl_easy *data = conn->data;
-#endif /* USE_ALARM_TIMEOUT */
+#endif /* USE_ALARM_TIMEOUT */
enum resolve_t rc;
-
- *entry = NULL;
-
- if(timeoutms < 0)
- /* got an already expired timeout */
- return CURLRESOLV_TIMEDOUT;
-
-#ifdef USE_ALARM_TIMEOUT
- if(data->set.no_signal)
- /* Ignore the timeout when signals are disabled */
- timeout = 0;
- else
+
+ *entry = NULL;
+
+ if(timeoutms < 0)
+ /* got an already expired timeout */
+ return CURLRESOLV_TIMEDOUT;
+
+#ifdef USE_ALARM_TIMEOUT
+ if(data->set.no_signal)
+ /* Ignore the timeout when signals are disabled */
+ timeout = 0;
+ else
timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
-
- if(!timeout)
- /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
+
+ if(!timeout)
+ /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
return Curl_resolv(conn, hostname, port, TRUE, entry);
-
+
if(timeout < 1000) {
- /* The alarm() function only provides integer second resolution, so if
- we want to wait less than one second we must bail out already now. */
+ /* The alarm() function only provides integer second resolution, so if
+ we want to wait less than one second we must bail out already now. */
failf(data,
"remaining timeout of %ld too small to resolve via SIGALRM method",
timeout);
- return CURLRESOLV_TIMEDOUT;
+ return CURLRESOLV_TIMEDOUT;
+ }
+ /* This allows us to time-out from the name resolver, as the timeout
+ will generate a signal and we will siglongjmp() from that here.
+ This technique has problems (see alarmfunc).
+ This should be the last thing we do before calling Curl_resolv(),
+ as otherwise we'd have to worry about variables that get modified
+ before we invoke Curl_resolv() (and thus use "volatile"). */
+ if(sigsetjmp(curl_jmpenv, 1)) {
+ /* this is coming from a siglongjmp() after an alarm signal */
+ failf(data, "name lookup timed out");
+ rc = CURLRESOLV_ERROR;
+ goto clean_up;
}
- /* This allows us to time-out from the name resolver, as the timeout
- will generate a signal and we will siglongjmp() from that here.
- This technique has problems (see alarmfunc).
- This should be the last thing we do before calling Curl_resolv(),
- as otherwise we'd have to worry about variables that get modified
- before we invoke Curl_resolv() (and thus use "volatile"). */
- if(sigsetjmp(curl_jmpenv, 1)) {
- /* this is coming from a siglongjmp() after an alarm signal */
- failf(data, "name lookup timed out");
- rc = CURLRESOLV_ERROR;
- goto clean_up;
- }
else {
/*************************************************************
* Set signal handler to catch SIGALRM
@@ -739,126 +739,126 @@ enum resolve_t Curl_resolv_timeout(struct connectdata *conn,
keep_sigact = signal(SIGALRM, alarmfunc);
#endif
#endif /* HAVE_SIGACTION */
-
+
/* alarm() makes a signal get sent when the timeout fires off, and that
will abort system calls */
prev_alarm = alarm(curlx_sltoui(timeout/1000L));
}
-#else
-#ifndef CURLRES_ASYNCH
- if(timeoutms)
- infof(conn->data, "timeout on name lookup is not supported\n");
-#else
- (void)timeoutms; /* timeoutms not used with an async resolver */
-#endif
-#endif /* USE_ALARM_TIMEOUT */
-
- /* Perform the actual name resolution. This might be interrupted by an
- * alarm if it takes too long.
- */
+#else
+#ifndef CURLRES_ASYNCH
+ if(timeoutms)
+ infof(conn->data, "timeout on name lookup is not supported\n");
+#else
+ (void)timeoutms; /* timeoutms not used with an async resolver */
+#endif
+#endif /* USE_ALARM_TIMEOUT */
+
+ /* Perform the actual name resolution. This might be interrupted by an
+ * alarm if it takes too long.
+ */
rc = Curl_resolv(conn, hostname, port, TRUE, entry);
-
-#ifdef USE_ALARM_TIMEOUT
-clean_up:
-
- if(!prev_alarm)
- /* deactivate a possibly active alarm before uninstalling the handler */
- alarm(0);
-
-#ifdef HAVE_SIGACTION
- if(keep_copysig) {
- /* we got a struct as it looked before, now put that one back nice
- and clean */
- sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
- }
-#else
-#ifdef HAVE_SIGNAL
- /* restore the previous SIGALRM handler */
- signal(SIGALRM, keep_sigact);
-#endif
-#endif /* HAVE_SIGACTION */
-
- /* switch back the alarm() to either zero or to what it was before minus
- the time we spent until now! */
- if(prev_alarm) {
- /* there was an alarm() set before us, now put it back */
+
+#ifdef USE_ALARM_TIMEOUT
+clean_up:
+
+ if(!prev_alarm)
+ /* deactivate a possibly active alarm before uninstalling the handler */
+ alarm(0);
+
+#ifdef HAVE_SIGACTION
+ if(keep_copysig) {
+ /* we got a struct as it looked before, now put that one back nice
+ and clean */
+ sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
+ }
+#else
+#ifdef HAVE_SIGNAL
+ /* restore the previous SIGALRM handler */
+ signal(SIGALRM, keep_sigact);
+#endif
+#endif /* HAVE_SIGACTION */
+
+ /* switch back the alarm() to either zero or to what it was before minus
+ the time we spent until now! */
+ if(prev_alarm) {
+ /* there was an alarm() set before us, now put it back */
timediff_t elapsed_secs = Curl_timediff(Curl_now(),
conn->created) / 1000;
-
- /* the alarm period is counted in even number of seconds */
+
+ /* the alarm period is counted in even number of seconds */
unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
-
- if(!alarm_set ||
- ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
- /* if the alarm time-left reached zero or turned "negative" (counted
- with unsigned values), we should fire off a SIGALRM here, but we
- won't, and zero would be to switch it off so we never set it to
- less than 1! */
- alarm(1);
- rc = CURLRESOLV_TIMEDOUT;
- failf(data, "Previous alarm fired off!");
- }
- else
- alarm((unsigned int)alarm_set);
- }
-#endif /* USE_ALARM_TIMEOUT */
-
- return rc;
-}
-
-/*
- * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
- * made, the struct may be destroyed due to pruning. It is important that only
- * one unlock is made for each Curl_resolv() call.
- *
- * May be called with 'data' == NULL for global cache.
- */
+
+ if(!alarm_set ||
+ ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
+ /* if the alarm time-left reached zero or turned "negative" (counted
+ with unsigned values), we should fire off a SIGALRM here, but we
+ won't, and zero would be to switch it off so we never set it to
+ less than 1! */
+ alarm(1);
+ rc = CURLRESOLV_TIMEDOUT;
+ failf(data, "Previous alarm fired off!");
+ }
+ else
+ alarm((unsigned int)alarm_set);
+ }
+#endif /* USE_ALARM_TIMEOUT */
+
+ return rc;
+}
+
+/*
+ * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
+ * made, the struct may be destroyed due to pruning. It is important that only
+ * one unlock is made for each Curl_resolv() call.
+ *
+ * May be called with 'data' == NULL for global cache.
+ */
void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns)
-{
- if(data && data->share)
- Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
+{
+ if(data && data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
freednsentry(dns);
-
- if(data && data->share)
- Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-}
-
-/*
+
+ if(data && data->share)
+ Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
+}
+
+/*
* File-internal: release cache dns entry reference, free if inuse drops to 0
- */
-static void freednsentry(void *freethis)
-{
+ */
+static void freednsentry(void *freethis)
+{
struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis;
DEBUGASSERT(dns && (dns->inuse>0));
-
+
dns->inuse--;
if(dns->inuse == 0) {
Curl_freeaddrinfo(dns->addr);
free(dns);
- }
-}
-
-/*
+ }
+}
+
+/*
* Curl_mk_dnscache() inits a new DNS cache and returns success/failure.
- */
+ */
int Curl_mk_dnscache(struct Curl_hash *hash)
-{
+{
return Curl_hash_init(hash, 7, Curl_hash_str, Curl_str_key_compare,
freednsentry);
-}
-
-/*
- * Curl_hostcache_clean()
- *
- * This _can_ be called with 'data' == NULL but then of course no locking
- * can be done!
- */
-
+}
+
+/*
+ * Curl_hostcache_clean()
+ *
+ * This _can_ be called with 'data' == NULL but then of course no locking
+ * can be done!
+ */
+
void Curl_hostcache_clean(struct Curl_easy *data,
struct Curl_hash *hash)
-{
+{
if(data && data->share)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
@@ -866,23 +866,23 @@ void Curl_hostcache_clean(struct Curl_easy *data,
if(data && data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-}
-
-
+}
+
+
CURLcode Curl_loadhostpairs(struct Curl_easy *data)
-{
- struct curl_slist *hostp;
- char hostname[256];
+{
+ struct curl_slist *hostp;
+ char hostname[256];
int port = 0;
-
+
/* Default is no wildcard found */
data->change.wildcard_resolve = false;
for(hostp = data->change.resolve; hostp; hostp = hostp->next) {
char entry_id[MAX_HOSTCACHE_LEN];
- if(!hostp->data)
- continue;
- if(hostp->data[0] == '-') {
+ if(!hostp->data)
+ continue;
+ if(hostp->data[0] == '-') {
size_t entry_len;
if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) {
@@ -903,11 +903,11 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
- }
+ }
else {
- struct Curl_dns_entry *dns;
+ struct Curl_dns_entry *dns;
struct Curl_addrinfo *head = NULL, *tail = NULL;
- size_t entry_len;
+ size_t entry_len;
char address[64];
#if !defined(CURL_DISABLE_VERBOSE_STRINGS)
char *addresses = NULL;
@@ -919,7 +919,7 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
char *host_end;
unsigned long tmp_port;
bool error = true;
-
+
host_end = strchr(hostp->data, ':');
if(!host_end ||
((host_end - hostp->data) >= (ptrdiff_t)sizeof(hostname)))
@@ -998,19 +998,19 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
infof(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'!\n",
hostp->data);
Curl_freeaddrinfo(head);
- continue;
- }
-
- /* Create an entry id, based upon the hostname and port */
+ continue;
+ }
+
+ /* Create an entry id, based upon the hostname and port */
create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
- entry_len = strlen(entry_id);
-
- if(data->share)
- Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
-
- /* See if its already in our dns cache */
+ entry_len = strlen(entry_id);
+
+ if(data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
+ /* See if its already in our dns cache */
dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
-
+
if(dns) {
infof(data, "RESOLVE %s:%d is - old addresses discarded!\n",
hostname, port);
@@ -1023,7 +1023,7 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
}
-
+
/* put this new host in the cache */
dns = Curl_cache_addr(data, head, hostname, port);
if(dns) {
@@ -1032,15 +1032,15 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
* entry alive: */
dns->inuse--;
}
-
- if(data->share)
- Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
-
- if(!dns) {
+
+ if(data->share)
+ Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
+
+ if(!dns) {
Curl_freeaddrinfo(head);
- return CURLE_OUT_OF_MEMORY;
- }
- infof(data, "Added %s:%d:%s to DNS cache\n",
+ return CURLE_OUT_OF_MEMORY;
+ }
+ infof(data, "Added %s:%d:%s to DNS cache\n",
hostname, port, addresses);
/* Wildcard hostname */
@@ -1049,12 +1049,12 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
hostname, port);
data->change.wildcard_resolve = true;
}
- }
- }
- data->change.resolve = NULL; /* dealt with now */
-
- return CURLE_OK;
-}
+ }
+ }
+ data->change.resolve = NULL; /* dealt with now */
+
+ return CURLE_OK;
+}
CURLcode Curl_resolv_check(struct connectdata *conn,
struct Curl_dns_entry **dns)
diff --git a/contrib/libs/curl/lib/hostip.h b/contrib/libs/curl/lib/hostip.h
index 77bc821cfa..724a03d7fb 100644
--- a/contrib/libs/curl/lib/hostip.h
+++ b/contrib/libs/curl/lib/hostip.h
@@ -1,84 +1,84 @@
-#ifndef HEADER_CURL_HOSTIP_H
-#define HEADER_CURL_HOSTIP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HOSTIP_H
+#define HEADER_CURL_HOSTIP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-#include "hash.h"
-#include "curl_addrinfo.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+#include "hash.h"
+#include "curl_addrinfo.h"
#include "timeval.h" /* for timediff_t */
-#include "asyn.h"
-
-#ifdef HAVE_SETJMP_H
-#include <setjmp.h>
-#endif
-
-#ifdef NETWARE
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-/* Allocate enough memory to hold the full name information structs and
- * everything. OSF1 is known to require at least 8872 bytes. The buffer
- * required for storing all possible aliases and IP numbers is according to
- * Stevens' Unix Network Programming 2nd edition, p. 304: 8192 bytes!
- */
-#define CURL_HOSTENT_SIZE 9000
-
-#define CURL_TIMEOUT_RESOLVE 300 /* when using asynch methods, we allow this
- many seconds for a name resolve */
-
-#define CURL_ASYNC_SUCCESS CURLE_OK
-
-struct addrinfo;
-struct hostent;
+#include "asyn.h"
+
+#ifdef HAVE_SETJMP_H
+#include <setjmp.h>
+#endif
+
+#ifdef NETWARE
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+/* Allocate enough memory to hold the full name information structs and
+ * everything. OSF1 is known to require at least 8872 bytes. The buffer
+ * required for storing all possible aliases and IP numbers is according to
+ * Stevens' Unix Network Programming 2nd edition, p. 304: 8192 bytes!
+ */
+#define CURL_HOSTENT_SIZE 9000
+
+#define CURL_TIMEOUT_RESOLVE 300 /* when using asynch methods, we allow this
+ many seconds for a name resolve */
+
+#define CURL_ASYNC_SUCCESS CURLE_OK
+
+struct addrinfo;
+struct hostent;
struct Curl_easy;
-struct connectdata;
-
-/*
- * Curl_global_host_cache_init() initializes and sets up a global DNS cache.
- * Global DNS cache is general badness. Do not use. This will be removed in
- * a future version. Use the share interface instead!
- *
+struct connectdata;
+
+/*
+ * Curl_global_host_cache_init() initializes and sets up a global DNS cache.
+ * Global DNS cache is general badness. Do not use. This will be removed in
+ * a future version. Use the share interface instead!
+ *
* Returns a struct Curl_hash pointer on success, NULL on failure.
- */
+ */
struct Curl_hash *Curl_global_host_cache_init(void);
-
-struct Curl_dns_entry {
+
+struct Curl_dns_entry {
struct Curl_addrinfo *addr;
/* timestamp == 0 -- CURLOPT_RESOLVE entry, doesn't timeout */
- time_t timestamp;
+ time_t timestamp;
/* use-counter, use Curl_resolv_unlock to release reference */
long inuse;
-};
-
-/*
- * Curl_resolv() returns an entry with the info for the specified host
- * and port.
- *
- * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
- * use, or we'll leak memory!
- */
-/* return codes */
+};
+
+/*
+ * Curl_resolv() returns an entry with the info for the specified host
+ * and port.
+ *
+ * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
+ * use, or we'll leak memory!
+ */
+/* return codes */
enum resolve_t {
CURLRESOLV_TIMEDOUT = -2,
CURLRESOLV_ERROR = -1,
@@ -94,81 +94,81 @@ enum resolve_t Curl_resolv_timeout(struct connectdata *conn,
const char *hostname, int port,
struct Curl_dns_entry **dnsentry,
timediff_t timeoutms);
-
-#ifdef CURLRES_IPV6
-/*
+
+#ifdef CURLRES_IPV6
+/*
* Curl_ipv6works() returns TRUE if IPv6 seems to work.
- */
+ */
bool Curl_ipv6works(struct connectdata *conn);
-#else
+#else
#define Curl_ipv6works(x) FALSE
-#endif
-
-/*
- * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
- * been set and returns TRUE if they are OK.
- */
-bool Curl_ipvalid(struct connectdata *conn);
-
-
-/*
- * Curl_getaddrinfo() is the generic low-level name resolve API within this
- * source file. There are several versions of this function - for different
- * name resolve layers (selected at build-time). They all take this same set
- * of arguments
- */
+#endif
+
+/*
+ * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
+ * been set and returns TRUE if they are OK.
+ */
+bool Curl_ipvalid(struct connectdata *conn);
+
+
+/*
+ * Curl_getaddrinfo() is the generic low-level name resolve API within this
+ * source file. There are several versions of this function - for different
+ * name resolve layers (selected at build-time). They all take this same set
+ * of arguments
+ */
struct Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp);
-
-
-/* unlock a previously resolved dns entry */
+
+
+/* unlock a previously resolved dns entry */
void Curl_resolv_unlock(struct Curl_easy *data,
- struct Curl_dns_entry *dns);
-
+ struct Curl_dns_entry *dns);
+
/* init a new dns cache and return success */
int Curl_mk_dnscache(struct Curl_hash *hash);
-
-/* prune old entries from the DNS cache */
+
+/* prune old entries from the DNS cache */
void Curl_hostcache_prune(struct Curl_easy *data);
-
+
/* Return # of addresses in a Curl_addrinfo struct */
int Curl_num_addresses(const struct Curl_addrinfo *addr);
-
-#if defined(CURLDEBUG) && defined(HAVE_GETNAMEINFO)
-int curl_dogetnameinfo(GETNAMEINFO_QUAL_ARG1 GETNAMEINFO_TYPE_ARG1 sa,
- GETNAMEINFO_TYPE_ARG2 salen,
- char *host, GETNAMEINFO_TYPE_ARG46 hostlen,
- char *serv, GETNAMEINFO_TYPE_ARG46 servlen,
- GETNAMEINFO_TYPE_ARG7 flags,
- int line, const char *source);
-#endif
-
-/* IPv4 threadsafe resolve function used for synch and asynch builds */
+
+#if defined(CURLDEBUG) && defined(HAVE_GETNAMEINFO)
+int curl_dogetnameinfo(GETNAMEINFO_QUAL_ARG1 GETNAMEINFO_TYPE_ARG1 sa,
+ GETNAMEINFO_TYPE_ARG2 salen,
+ char *host, GETNAMEINFO_TYPE_ARG46 hostlen,
+ char *serv, GETNAMEINFO_TYPE_ARG46 servlen,
+ GETNAMEINFO_TYPE_ARG7 flags,
+ int line, const char *source);
+#endif
+
+/* IPv4 threadsafe resolve function used for synch and asynch builds */
struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, int port);
-
+
CURLcode Curl_once_resolved(struct connectdata *conn, bool *protocol_connect);
-
-/*
- * Curl_addrinfo_callback() is used when we build with any asynch specialty.
- * Handles end of async request processing. Inserts ai into hostcache when
- * status is CURL_ASYNC_SUCCESS. Twiddles fields in conn to indicate async
- * request completed whether successful or failed.
- */
-CURLcode Curl_addrinfo_callback(struct connectdata *conn,
- int status,
+
+/*
+ * Curl_addrinfo_callback() is used when we build with any asynch specialty.
+ * Handles end of async request processing. Inserts ai into hostcache when
+ * status is CURL_ASYNC_SUCCESS. Twiddles fields in conn to indicate async
+ * request completed whether successful or failed.
+ */
+CURLcode Curl_addrinfo_callback(struct connectdata *conn,
+ int status,
struct Curl_addrinfo *ai);
-
-/*
- * Curl_printable_address() returns a printable version of the 1st address
- * given in the 'ip' argument. The result will be stored in the buf that is
- * bufsize bytes big.
- */
+
+/*
+ * Curl_printable_address() returns a printable version of the 1st address
+ * given in the 'ip' argument. The result will be stored in the buf that is
+ * bufsize bytes big.
+ */
void Curl_printable_address(const struct Curl_addrinfo *ip,
char *buf, size_t bufsize);
-
-/*
+
+/*
* Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
*
* Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
@@ -182,68 +182,68 @@ Curl_fetch_addr(struct connectdata *conn,
int port);
/*
- * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
- *
- * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
- */
-struct Curl_dns_entry *
+ * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
+ *
+ * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
+ */
+struct Curl_dns_entry *
Curl_cache_addr(struct Curl_easy *data, struct Curl_addrinfo *addr,
- const char *hostname, int port);
-
-#ifndef INADDR_NONE
-#define CURL_INADDR_NONE (in_addr_t) ~0
-#else
-#define CURL_INADDR_NONE INADDR_NONE
-#endif
-
-#ifdef HAVE_SIGSETJMP
-/* Forward-declaration of variable defined in hostip.c. Beware this
- * is a global and unique instance. This is used to store the return
- * address that we can jump back to from inside a signal handler.
- * This is not thread-safe stuff.
- */
-extern sigjmp_buf curl_jmpenv;
-#endif
-
-/*
- * Function provided by the resolver backend to set DNS servers to use.
- */
+ const char *hostname, int port);
+
+#ifndef INADDR_NONE
+#define CURL_INADDR_NONE (in_addr_t) ~0
+#else
+#define CURL_INADDR_NONE INADDR_NONE
+#endif
+
+#ifdef HAVE_SIGSETJMP
+/* Forward-declaration of variable defined in hostip.c. Beware this
+ * is a global and unique instance. This is used to store the return
+ * address that we can jump back to from inside a signal handler.
+ * This is not thread-safe stuff.
+ */
+extern sigjmp_buf curl_jmpenv;
+#endif
+
+/*
+ * Function provided by the resolver backend to set DNS servers to use.
+ */
CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers);
-
-/*
- * Function provided by the resolver backend to set
- * outgoing interface to use for DNS requests
- */
+
+/*
+ * Function provided by the resolver backend to set
+ * outgoing interface to use for DNS requests
+ */
CURLcode Curl_set_dns_interface(struct Curl_easy *data,
- const char *interf);
-
-/*
- * Function provided by the resolver backend to set
- * local IPv4 address to use as source address for DNS requests
- */
+ const char *interf);
+
+/*
+ * Function provided by the resolver backend to set
+ * local IPv4 address to use as source address for DNS requests
+ */
CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data,
- const char *local_ip4);
-
-/*
- * Function provided by the resolver backend to set
- * local IPv6 address to use as source address for DNS requests
- */
+ const char *local_ip4);
+
+/*
+ * Function provided by the resolver backend to set
+ * local IPv6 address to use as source address for DNS requests
+ */
CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data,
- const char *local_ip6);
-
-/*
- * Clean off entries from the cache
- */
+ const char *local_ip6);
+
+/*
+ * Clean off entries from the cache
+ */
void Curl_hostcache_clean(struct Curl_easy *data, struct Curl_hash *hash);
-
-/*
- * Populate the cache with specified entries from CURLOPT_RESOLVE.
- */
+
+/*
+ * Populate the cache with specified entries from CURLOPT_RESOLVE.
+ */
CURLcode Curl_loadhostpairs(struct Curl_easy *data);
-
+
CURLcode Curl_resolv_check(struct connectdata *conn,
struct Curl_dns_entry **dns);
int Curl_resolv_getsock(struct connectdata *conn,
curl_socket_t *socks);
-#endif /* HEADER_CURL_HOSTIP_H */
+#endif /* HEADER_CURL_HOSTIP_H */
diff --git a/contrib/libs/curl/lib/hostip4.c b/contrib/libs/curl/lib/hostip4.c
index 9a6e6b9443..df83a2f12b 100644
--- a/contrib/libs/curl/lib/hostip4.c
+++ b/contrib/libs/curl/lib/hostip4.c
@@ -1,139 +1,139 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
/***********************************************************************
* Only for plain IPv4 builds
**********************************************************************/
#ifdef CURLRES_IPV4 /* plain IPv4 code coming up */
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#ifdef HAVE_PROCESS_H
+#include <process.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
- * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
- * been set and returns TRUE if they are OK.
- */
-bool Curl_ipvalid(struct connectdata *conn)
-{
- if(conn->ip_version == CURL_IPRESOLVE_V6)
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/*
+ * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
+ * been set and returns TRUE if they are OK.
+ */
+bool Curl_ipvalid(struct connectdata *conn)
+{
+ if(conn->ip_version == CURL_IPRESOLVE_V6)
/* An IPv6 address was requested and we can't get/use one */
- return FALSE;
-
- return TRUE; /* OK, proceed */
-}
-
-#ifdef CURLRES_SYNCH
-
-/*
+ return FALSE;
+
+ return TRUE; /* OK, proceed */
+}
+
+#ifdef CURLRES_SYNCH
+
+/*
* Curl_getaddrinfo() - the IPv4 synchronous version.
- *
- * The original code to this function was from the Dancer source code, written
- * by Bjorn Reese, it has since been patched and modified considerably.
- *
- * gethostbyname_r() is the thread-safe version of the gethostbyname()
- * function. When we build for plain IPv4, we attempt to use this
- * function. There are _three_ different gethostbyname_r() versions, and we
- * detect which one this platform supports in the configure script and set up
- * the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or
- * HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME
- * has the corresponding rules. This is primarily on *nix. Note that some unix
- * flavours have thread-safe versions of the plain gethostbyname() etc.
- *
- */
+ *
+ * The original code to this function was from the Dancer source code, written
+ * by Bjorn Reese, it has since been patched and modified considerably.
+ *
+ * gethostbyname_r() is the thread-safe version of the gethostbyname()
+ * function. When we build for plain IPv4, we attempt to use this
+ * function. There are _three_ different gethostbyname_r() versions, and we
+ * detect which one this platform supports in the configure script and set up
+ * the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or
+ * HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME
+ * has the corresponding rules. This is primarily on *nix. Note that some unix
+ * flavours have thread-safe versions of the plain gethostbyname() etc.
+ *
+ */
struct Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp)
-{
+{
struct Curl_addrinfo *ai = NULL;
-
-#ifdef CURL_DISABLE_VERBOSE_STRINGS
- (void)conn;
-#endif
-
- *waitp = 0; /* synchronous response only */
-
- ai = Curl_ipv4_resolve_r(hostname, port);
- if(!ai)
- infof(conn->data, "Curl_ipv4_resolve_r failed for %s\n", hostname);
-
- return ai;
-}
-#endif /* CURLRES_SYNCH */
-#endif /* CURLRES_IPV4 */
-
-#if defined(CURLRES_IPV4) && !defined(CURLRES_ARES)
-
-/*
- * Curl_ipv4_resolve_r() - ipv4 threadsafe resolver function.
- *
- * This is used for both synchronous and asynchronous resolver builds,
- * implying that only threadsafe code and function calls may be used.
- *
- */
+
+#ifdef CURL_DISABLE_VERBOSE_STRINGS
+ (void)conn;
+#endif
+
+ *waitp = 0; /* synchronous response only */
+
+ ai = Curl_ipv4_resolve_r(hostname, port);
+ if(!ai)
+ infof(conn->data, "Curl_ipv4_resolve_r failed for %s\n", hostname);
+
+ return ai;
+}
+#endif /* CURLRES_SYNCH */
+#endif /* CURLRES_IPV4 */
+
+#if defined(CURLRES_IPV4) && !defined(CURLRES_ARES)
+
+/*
+ * Curl_ipv4_resolve_r() - ipv4 threadsafe resolver function.
+ *
+ * This is used for both synchronous and asynchronous resolver builds,
+ * implying that only threadsafe code and function calls may be used.
+ *
+ */
struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
int port)
-{
-#if !defined(HAVE_GETADDRINFO_THREADSAFE) && defined(HAVE_GETHOSTBYNAME_R_3)
- int res;
-#endif
+{
+#if !defined(HAVE_GETADDRINFO_THREADSAFE) && defined(HAVE_GETHOSTBYNAME_R_3)
+ int res;
+#endif
struct Curl_addrinfo *ai = NULL;
- struct hostent *h = NULL;
- struct hostent *buf = NULL;
-
-#if defined(HAVE_GETADDRINFO_THREADSAFE)
+ struct hostent *h = NULL;
+ struct hostent *buf = NULL;
+
+#if defined(HAVE_GETADDRINFO_THREADSAFE)
struct addrinfo hints;
char sbuf[12];
char *sbufptr = NULL;
-
+
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
@@ -141,17 +141,17 @@ struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
msnprintf(sbuf, sizeof(sbuf), "%d", port);
sbufptr = sbuf;
}
-
+
(void)Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &ai);
-
-#elif defined(HAVE_GETHOSTBYNAME_R)
- /*
- * gethostbyname_r() is the preferred resolve function for many platforms.
- * Since there are three different versions of it, the following code is
- * somewhat #ifdef-ridden.
- */
+
+#elif defined(HAVE_GETHOSTBYNAME_R)
+ /*
+ * gethostbyname_r() is the preferred resolve function for many platforms.
+ * Since there are three different versions of it, the following code is
+ * somewhat #ifdef-ridden.
+ */
int h_errnop;
-
+
buf = calloc(1, CURL_HOSTENT_SIZE);
if(!buf)
return NULL; /* major failure */
@@ -160,28 +160,28 @@ struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
* qnx nto and it is also _required_ for some of these functions on some
* platforms.
*/
-
-#if defined(HAVE_GETHOSTBYNAME_R_5)
+
+#if defined(HAVE_GETHOSTBYNAME_R_5)
/* Solaris, IRIX and more */
h = gethostbyname_r(hostname,
(struct hostent *)buf,
(char *)buf + sizeof(struct hostent),
CURL_HOSTENT_SIZE - sizeof(struct hostent),
&h_errnop);
-
+
/* If the buffer is too small, it returns NULL and sets errno to
* ERANGE. The errno is thread safe if this is compiled with
* -D_REENTRANT as then the 'errno' variable is a macro defined to get
* used properly for threads.
*/
-
+
if(h) {
;
}
else
-#elif defined(HAVE_GETHOSTBYNAME_R_6)
+#elif defined(HAVE_GETHOSTBYNAME_R_6)
/* Linux */
-
+
(void)gethostbyname_r(hostname,
(struct hostent *)buf,
(char *)buf + sizeof(struct hostent),
@@ -218,11 +218,11 @@ struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
* is set to the ERANGE or EAGAIN code. Note that 'errno' is not a
* thread-safe variable.
*/
-
+
if(!h) /* failure */
-#elif defined(HAVE_GETHOSTBYNAME_R_3)
+#elif defined(HAVE_GETHOSTBYNAME_R_3)
/* AIX, Digital Unix/Tru64, HPUX 10, more? */
-
+
/* For AIX 4.3 or later, we don't use gethostbyname_r() at all, because of
* the plain fact that it does not return unique full buffers on each
* call, but instead several of the pointers in the hostent structs will
@@ -240,15 +240,15 @@ struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
* [*] = much later we've found out that it isn't at all "completely
* thread-safe", but at least the gethostbyname() function is.
*/
-
+
if(CURL_HOSTENT_SIZE >=
(sizeof(struct hostent) + sizeof(struct hostent_data))) {
-
+
/* August 22nd, 2000: Albert Chin-A-Young brought an updated version
* that should work! September 20: Richard Prescott worked on the buffer
* size dilemma.
*/
-
+
res = gethostbyname_r(hostname,
(struct hostent *)buf,
(struct hostent_data *)((char *)buf +
@@ -257,11 +257,11 @@ struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
}
else
res = -1; /* failure, too smallish buffer size */
-
+
if(!res) { /* success */
-
+
h = buf; /* result expected in h */
-
+
/* This is the worst kind of the different gethostbyname_r() interfaces.
* Since we don't know how big buffer this particular lookup required,
* we can't realloc down the huge alloc without doing closer analysis of
@@ -272,27 +272,27 @@ struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
*/
}
else
-#endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */
+#endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */
{
h = NULL; /* set return code to NULL */
free(buf);
}
-#else /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */
+#else /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */
/*
* Here is code for platforms that don't have a thread safe
* getaddrinfo() nor gethostbyname_r() function or for which
* gethostbyname() is the preferred one.
*/
h = gethostbyname((void *)hostname);
-#endif /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */
-
- if(h) {
- ai = Curl_he2ai(h, port);
-
- if(buf) /* used a *_r() function */
- free(buf);
- }
-
- return ai;
-}
-#endif /* defined(CURLRES_IPV4) && !defined(CURLRES_ARES) */
+#endif /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */
+
+ if(h) {
+ ai = Curl_he2ai(h, port);
+
+ if(buf) /* used a *_r() function */
+ free(buf);
+ }
+
+ return ai;
+}
+#endif /* defined(CURLRES_IPV4) && !defined(CURLRES_ARES) */
diff --git a/contrib/libs/curl/lib/hostip6.c b/contrib/libs/curl/lib/hostip6.c
index 30fd094380..02b0ca298b 100644
--- a/contrib/libs/curl/lib/hostip6.c
+++ b/contrib/libs/curl/lib/hostip6.c
@@ -1,69 +1,69 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
/***********************************************************************
* Only for IPv6-enabled builds
**********************************************************************/
#ifdef CURLRES_IPV6
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
-#include "inet_pton.h"
-#include "connect.h"
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#ifdef HAVE_PROCESS_H
+#include <process.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
+#include "inet_pton.h"
+#include "connect.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/*
* Curl_ipv6works() returns TRUE if IPv6 seems to work.
- */
+ */
bool Curl_ipv6works(struct connectdata *conn)
-{
+{
if(conn) {
/* the nature of most system is that IPv6 status doesn't come and go
during a program's lifetime so we only probe the first time and then we
@@ -75,132 +75,132 @@ bool Curl_ipv6works(struct connectdata *conn)
}
else {
int ipv6_works = -1;
- /* probe to see if we have a working IPv6 stack */
- curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0);
- if(s == CURL_SOCKET_BAD)
+ /* probe to see if we have a working IPv6 stack */
+ curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0);
+ if(s == CURL_SOCKET_BAD)
/* an IPv6 address was requested but we can't get/use one */
- ipv6_works = 0;
- else {
- ipv6_works = 1;
- Curl_closesocket(NULL, s);
- }
+ ipv6_works = 0;
+ else {
+ ipv6_works = 1;
+ Curl_closesocket(NULL, s);
+ }
return (ipv6_works>0)?TRUE:FALSE;
- }
-}
-
-/*
- * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
- * been set and returns TRUE if they are OK.
- */
-bool Curl_ipvalid(struct connectdata *conn)
-{
- if(conn->ip_version == CURL_IPRESOLVE_V6)
+ }
+}
+
+/*
+ * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
+ * been set and returns TRUE if they are OK.
+ */
+bool Curl_ipvalid(struct connectdata *conn)
+{
+ if(conn->ip_version == CURL_IPRESOLVE_V6)
return Curl_ipv6works(conn);
- return TRUE;
-}
-
-#if defined(CURLRES_SYNCH)
-
-#ifdef DEBUG_ADDRINFO
+ return TRUE;
+}
+
+#if defined(CURLRES_SYNCH)
+
+#ifdef DEBUG_ADDRINFO
static void dump_addrinfo(struct connectdata *conn,
const struct Curl_addrinfo *ai)
-{
- printf("dump_addrinfo:\n");
- for(; ai; ai = ai->ai_next) {
+{
+ printf("dump_addrinfo:\n");
+ for(; ai; ai = ai->ai_next) {
char buf[INET6_ADDRSTRLEN];
- printf(" fam %2d, CNAME %s, ",
- ai->ai_family, ai->ai_canonname ? ai->ai_canonname : "<none>");
+ printf(" fam %2d, CNAME %s, ",
+ ai->ai_family, ai->ai_canonname ? ai->ai_canonname : "<none>");
Curl_printable_address(ai, buf, sizeof(buf));
printf("%s\n", buf);
- }
-}
-#else
-#define dump_addrinfo(x,y) Curl_nop_stmt
-#endif
-
-/*
+ }
+}
+#else
+#define dump_addrinfo(x,y) Curl_nop_stmt
+#endif
+
+/*
* Curl_getaddrinfo() when built IPv6-enabled (non-threading and
- * non-ares version).
- *
- * Returns name information about the given hostname and port number. If
- * successful, the 'addrinfo' is returned and the forth argument will point to
- * memory we need to free after use. That memory *MUST* be freed with
- * Curl_freeaddrinfo(), nothing else.
- */
+ * non-ares version).
+ *
+ * Returns name information about the given hostname and port number. If
+ * successful, the 'addrinfo' is returned and the forth argument will point to
+ * memory we need to free after use. That memory *MUST* be freed with
+ * Curl_freeaddrinfo(), nothing else.
+ */
struct Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
const char *hostname,
int port,
int *waitp)
-{
- struct addrinfo hints;
+{
+ struct addrinfo hints;
struct Curl_addrinfo *res;
- int error;
- char sbuf[12];
- char *sbufptr = NULL;
+ int error;
+ char sbuf[12];
+ char *sbufptr = NULL;
#ifndef USE_RESOLVE_ON_IPS
- char addrbuf[128];
+ char addrbuf[128];
#endif
- int pf;
+ int pf;
#if !defined(CURL_DISABLE_VERBOSE_STRINGS)
struct Curl_easy *data = conn->data;
#endif
-
- *waitp = 0; /* synchronous response only */
-
+
+ *waitp = 0; /* synchronous response only */
+
/* Check if a limited name resolve has been requested */
- switch(conn->ip_version) {
- case CURL_IPRESOLVE_V4:
- pf = PF_INET;
- break;
- case CURL_IPRESOLVE_V6:
- pf = PF_INET6;
- break;
- default:
- pf = PF_UNSPEC;
- break;
- }
-
+ switch(conn->ip_version) {
+ case CURL_IPRESOLVE_V4:
+ pf = PF_INET;
+ break;
+ case CURL_IPRESOLVE_V6:
+ pf = PF_INET6;
+ break;
+ default:
+ pf = PF_UNSPEC;
+ break;
+ }
+
if((pf != PF_INET) && !Curl_ipv6works(conn))
/* The stack seems to be a non-IPv6 one */
- pf = PF_INET;
-
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = pf;
+ pf = PF_INET;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = pf;
hints.ai_socktype = (conn->transport == TRNSPRT_TCP) ?
SOCK_STREAM : SOCK_DGRAM;
-
+
#ifndef USE_RESOLVE_ON_IPS
/*
* The AI_NUMERICHOST must not be set to get synthesized IPv6 address from
* an IPv4 address on iOS and Mac OS X.
*/
- if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) ||
- (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) {
- /* the given address is numerical only, prevent a reverse lookup */
- hints.ai_flags = AI_NUMERICHOST;
- }
+ if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) ||
+ (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) {
+ /* the given address is numerical only, prevent a reverse lookup */
+ hints.ai_flags = AI_NUMERICHOST;
+ }
#endif
-
- if(port) {
+
+ if(port) {
msnprintf(sbuf, sizeof(sbuf), "%d", port);
sbufptr = sbuf;
- }
-
- error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res);
- if(error) {
- infof(data, "getaddrinfo(3) failed for %s:%d\n", hostname, port);
- return NULL;
- }
-
+ }
+
+ error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res);
+ if(error) {
+ infof(data, "getaddrinfo(3) failed for %s:%d\n", hostname, port);
+ return NULL;
+ }
+
if(port) {
Curl_addrinfo_set_port(res, port);
}
- dump_addrinfo(conn, res);
-
- return res;
-}
-#endif /* CURLRES_SYNCH */
+ dump_addrinfo(conn, res);
+
+ return res;
+}
+#endif /* CURLRES_SYNCH */
-#endif /* CURLRES_IPV6 */
+#endif /* CURLRES_IPV6 */
diff --git a/contrib/libs/curl/lib/hostsyn.c b/contrib/libs/curl/lib/hostsyn.c
index d6305a6acd..550b43a085 100644
--- a/contrib/libs/curl/lib/hostsyn.c
+++ b/contrib/libs/curl/lib/hostsyn.c
@@ -1,107 +1,107 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
/***********************************************************************
* Only for builds using synchronous name resolves
**********************************************************************/
#ifdef CURLRES_SYNCH
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#ifdef HAVE_PROCESS_H
-#include <process.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "hash.h"
-#include "share.h"
-#include "strerror.h"
-#include "url.h"
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * Function provided by the resolver backend to set DNS servers to use.
- */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#ifdef HAVE_PROCESS_H
+#include <process.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "hash.h"
+#include "share.h"
+#include "strerror.h"
+#include "url.h"
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * Function provided by the resolver backend to set DNS servers to use.
+ */
CURLcode Curl_set_dns_servers(struct Curl_easy *data,
- char *servers)
-{
- (void)data;
- (void)servers;
- return CURLE_NOT_BUILT_IN;
-
-}
-
-/*
- * Function provided by the resolver backend to set
- * outgoing interface to use for DNS requests
- */
+ char *servers)
+{
+ (void)data;
+ (void)servers;
+ return CURLE_NOT_BUILT_IN;
+
+}
+
+/*
+ * Function provided by the resolver backend to set
+ * outgoing interface to use for DNS requests
+ */
CURLcode Curl_set_dns_interface(struct Curl_easy *data,
- const char *interf)
-{
- (void)data;
- (void)interf;
- return CURLE_NOT_BUILT_IN;
-}
-
-/*
- * Function provided by the resolver backend to set
- * local IPv4 address to use as source address for DNS requests
- */
+ const char *interf)
+{
+ (void)data;
+ (void)interf;
+ return CURLE_NOT_BUILT_IN;
+}
+
+/*
+ * Function provided by the resolver backend to set
+ * local IPv4 address to use as source address for DNS requests
+ */
CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data,
- const char *local_ip4)
-{
- (void)data;
- (void)local_ip4;
- return CURLE_NOT_BUILT_IN;
-}
-
-/*
- * Function provided by the resolver backend to set
- * local IPv6 address to use as source address for DNS requests
- */
+ const char *local_ip4)
+{
+ (void)data;
+ (void)local_ip4;
+ return CURLE_NOT_BUILT_IN;
+}
+
+/*
+ * Function provided by the resolver backend to set
+ * local IPv6 address to use as source address for DNS requests
+ */
CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data,
- const char *local_ip6)
-{
- (void)data;
- (void)local_ip6;
- return CURLE_NOT_BUILT_IN;
-}
-
-#endif /* truly sync */
+ const char *local_ip6)
+{
+ (void)data;
+ (void)local_ip6;
+ return CURLE_NOT_BUILT_IN;
+}
+
+#endif /* truly sync */
diff --git a/contrib/libs/curl/lib/http.c b/contrib/libs/curl/lib/http.c
index cb9ec46b19..c232ed4134 100644
--- a/contrib/libs/curl/lib/http.c
+++ b/contrib/libs/curl/lib/http.c
@@ -1,176 +1,176 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_HTTP
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
-#include "sendf.h"
-#include "formdata.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_HTTP
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
+#include "sendf.h"
+#include "formdata.h"
#include "mime.h"
-#include "progress.h"
-#include "curl_base64.h"
-#include "cookie.h"
+#include "progress.h"
+#include "curl_base64.h"
+#include "cookie.h"
#include "vauth/vauth.h"
#include "vtls/vtls.h"
-#include "http_digest.h"
+#include "http_digest.h"
#include "http_ntlm.h"
-#include "curl_ntlm_wb.h"
-#include "http_negotiate.h"
-#include "url.h"
-#include "share.h"
-#include "hostip.h"
-#include "http.h"
-#include "select.h"
-#include "parsedate.h" /* for the week day and month names */
-#include "strtoofft.h"
-#include "multiif.h"
+#include "curl_ntlm_wb.h"
+#include "http_negotiate.h"
+#include "url.h"
+#include "share.h"
+#include "hostip.h"
+#include "http.h"
+#include "select.h"
+#include "parsedate.h" /* for the week day and month names */
+#include "strtoofft.h"
+#include "multiif.h"
#include "strcase.h"
-#include "content_encoding.h"
-#include "http_proxy.h"
-#include "warnless.h"
-#include "non-ascii.h"
-#include "http2.h"
+#include "content_encoding.h"
+#include "http_proxy.h"
+#include "warnless.h"
+#include "non-ascii.h"
+#include "http2.h"
#include "connect.h"
#include "strdup.h"
#include "altsvc.h"
#include "hsts.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
- * Forward declarations.
- */
-
-static int http_getsock_do(struct connectdata *conn,
+#include "memdebug.h"
+
+/*
+ * Forward declarations.
+ */
+
+static int http_getsock_do(struct connectdata *conn,
curl_socket_t *socks);
-static int http_should_fail(struct connectdata *conn);
-
+static int http_should_fail(struct connectdata *conn);
+
#ifndef CURL_DISABLE_PROXY
static CURLcode add_haproxy_protocol_header(struct connectdata *conn);
#endif
-#ifdef USE_SSL
-static CURLcode https_connecting(struct connectdata *conn, bool *done);
-static int https_getsock(struct connectdata *conn,
+#ifdef USE_SSL
+static CURLcode https_connecting(struct connectdata *conn, bool *done);
+static int https_getsock(struct connectdata *conn,
curl_socket_t *socks);
-#else
-#define https_connecting(x,y) CURLE_COULDNT_CONNECT
-#endif
+#else
+#define https_connecting(x,y) CURLE_COULDNT_CONNECT
+#endif
static CURLcode http_setup_conn(struct connectdata *conn);
-
-/*
- * HTTP handler interface.
- */
-const struct Curl_handler Curl_handler_http = {
- "HTTP", /* scheme */
+
+/*
+ * HTTP handler interface.
+ */
+const struct Curl_handler Curl_handler_http = {
+ "HTTP", /* scheme */
http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- Curl_http_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- http_getsock_do, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+ Curl_http, /* do_it */
+ Curl_http_done, /* done */
+ ZERO_NULL, /* do_more */
+ Curl_http_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ http_getsock_do, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_HTTP, /* defport */
- CURLPROTO_HTTP, /* protocol */
+ PORT_HTTP, /* defport */
+ CURLPROTO_HTTP, /* protocol */
CURLPROTO_HTTP, /* family */
PROTOPT_CREDSPERREQUEST | /* flags */
PROTOPT_USERPWDCTRL
-};
-
-#ifdef USE_SSL
-/*
- * HTTPS handler interface.
- */
-const struct Curl_handler Curl_handler_https = {
- "HTTPS", /* scheme */
+};
+
+#ifdef USE_SSL
+/*
+ * HTTPS handler interface.
+ */
+const struct Curl_handler Curl_handler_https = {
+ "HTTPS", /* scheme */
http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- Curl_http_connect, /* connect_it */
- https_connecting, /* connecting */
- ZERO_NULL, /* doing */
- https_getsock, /* proto_getsock */
- http_getsock_do, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+ Curl_http, /* do_it */
+ Curl_http_done, /* done */
+ ZERO_NULL, /* do_more */
+ Curl_http_connect, /* connect_it */
+ https_connecting, /* connecting */
+ ZERO_NULL, /* doing */
+ https_getsock, /* proto_getsock */
+ http_getsock_do, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_HTTPS, /* defport */
+ PORT_HTTPS, /* defport */
CURLPROTO_HTTPS, /* protocol */
CURLPROTO_HTTP, /* family */
PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN_NPN | /* flags */
PROTOPT_USERPWDCTRL
-};
-#endif
-
+};
+#endif
+
static CURLcode http_setup_conn(struct connectdata *conn)
-{
+{
/* allocate the HTTP-specific struct for the Curl_easy, only to survive
- during this request */
+ during this request */
struct HTTP *http;
struct Curl_easy *data = conn->data;
DEBUGASSERT(data->req.p.http == NULL);
-
+
http = calloc(1, sizeof(struct HTTP));
if(!http)
- return CURLE_OUT_OF_MEMORY;
-
+ return CURLE_OUT_OF_MEMORY;
+
Curl_mime_initpart(&http->form, conn->data);
data->req.p.http = http;
@@ -190,113 +190,113 @@ static CURLcode http_setup_conn(struct connectdata *conn)
Curl_http2_setup_conn(conn);
Curl_http2_setup_req(data);
}
- return CURLE_OK;
-}
-
+ return CURLE_OK;
+}
+
#ifndef CURL_DISABLE_PROXY
-/*
+/*
* checkProxyHeaders() checks the linked list of custom proxy headers
* if proxy headers are not available, then it will lookup into http header
* link list
- *
+ *
* It takes a connectdata struct as input instead of the Curl_easy simply to
* know if this is a proxy request or not, as it then might check a different
* header list. Provide the header prefix without colon!.
- */
+ */
char *Curl_checkProxyheaders(const struct connectdata *conn,
const char *thisheader)
-{
- struct curl_slist *head;
- size_t thislen = strlen(thisheader);
+{
+ struct curl_slist *head;
+ size_t thislen = strlen(thisheader);
struct Curl_easy *data = conn->data;
-
+
for(head = (conn->bits.proxy && data->set.sep_headers) ?
data->set.proxyheaders : data->set.headers;
head; head = head->next) {
if(strncasecompare(head->data, thisheader, thislen) &&
Curl_headersep(head->data[thislen]))
- return head->data;
- }
+ return head->data;
+ }
- return NULL;
-}
+ return NULL;
+}
#else
/* disabled */
#define Curl_checkProxyheaders(x,y) NULL
#endif
-
-/*
- * Strip off leading and trailing whitespace from the value in the
- * given HTTP header line and return a strdupped copy. Returns NULL in
- * case of allocation failure. Returns an empty string if the header value
- * consists entirely of whitespace.
- */
+
+/*
+ * Strip off leading and trailing whitespace from the value in the
+ * given HTTP header line and return a strdupped copy. Returns NULL in
+ * case of allocation failure. Returns an empty string if the header value
+ * consists entirely of whitespace.
+ */
char *Curl_copy_header_value(const char *header)
-{
- const char *start;
- const char *end;
- char *value;
- size_t len;
-
- /* Find the end of the header name */
+{
+ const char *start;
+ const char *end;
+ char *value;
+ size_t len;
+
+ /* Find the end of the header name */
while(*header && (*header != ':'))
++header;
-
+
if(*header)
- /* Skip over colon */
+ /* Skip over colon */
++header;
-
- /* Find the first non-space letter */
+
+ /* Find the first non-space letter */
start = header;
- while(*start && ISSPACE(*start))
- start++;
-
- /* data is in the host encoding so
- use '\r' and '\n' instead of 0x0d and 0x0a */
- end = strchr(start, '\r');
- if(!end)
- end = strchr(start, '\n');
- if(!end)
- end = strchr(start, '\0');
- if(!end)
- return NULL;
-
- /* skip all trailing space letters */
- while((end > start) && ISSPACE(*end))
- end--;
-
- /* get length of the type */
+ while(*start && ISSPACE(*start))
+ start++;
+
+ /* data is in the host encoding so
+ use '\r' and '\n' instead of 0x0d and 0x0a */
+ end = strchr(start, '\r');
+ if(!end)
+ end = strchr(start, '\n');
+ if(!end)
+ end = strchr(start, '\0');
+ if(!end)
+ return NULL;
+
+ /* skip all trailing space letters */
+ while((end > start) && ISSPACE(*end))
+ end--;
+
+ /* get length of the type */
len = end - start + 1;
-
- value = malloc(len + 1);
- if(!value)
- return NULL;
-
- memcpy(value, start, len);
+
+ value = malloc(len + 1);
+ if(!value)
+ return NULL;
+
+ memcpy(value, start, len);
value[len] = 0; /* null-terminate */
-
- return value;
-}
-
+
+ return value;
+}
+
#ifndef CURL_DISABLE_HTTP_AUTH
-/*
- * http_output_basic() sets up an Authorization: header (or the proxy version)
- * for HTTP Basic authentication.
- *
- * Returns CURLcode.
- */
-static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
-{
- size_t size = 0;
- char *authorization = NULL;
+/*
+ * http_output_basic() sets up an Authorization: header (or the proxy version)
+ * for HTTP Basic authentication.
+ *
+ * Returns CURLcode.
+ */
+static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
+{
+ size_t size = 0;
+ char *authorization = NULL;
struct Curl_easy *data = conn->data;
- char **userp;
- const char *user;
- const char *pwd;
+ char **userp;
+ const char *user;
+ const char *pwd;
CURLcode result;
char *out;
-
- if(proxy) {
+
+ if(proxy) {
#ifndef CURL_DISABLE_PROXY
userp = &data->state.aptr.proxyuserpwd;
user = conn->http_proxy.user;
@@ -304,41 +304,41 @@ static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
#else
return CURLE_NOT_BUILT_IN;
#endif
- }
- else {
+ }
+ else {
userp = &data->state.aptr.userpwd;
- user = conn->user;
- pwd = conn->passwd;
- }
-
+ user = conn->user;
+ pwd = conn->passwd;
+ }
+
out = aprintf("%s:%s", user, pwd ? pwd : "");
if(!out)
return CURLE_OUT_OF_MEMORY;
-
+
result = Curl_base64_encode(data, out, strlen(out), &authorization, &size);
if(result)
goto fail;
-
+
if(!authorization) {
result = CURLE_REMOTE_ACCESS_DENIED;
goto fail;
}
-
+
free(*userp);
- *userp = aprintf("%sAuthorization: Basic %s\r\n",
+ *userp = aprintf("%sAuthorization: Basic %s\r\n",
proxy ? "Proxy-" : "",
- authorization);
- free(authorization);
+ authorization);
+ free(authorization);
if(!*userp) {
result = CURLE_OUT_OF_MEMORY;
goto fail;
}
-
+
fail:
free(out);
return result;
-}
-
+}
+
/*
* http_output_bearer() sets up an Authorization: header
* for HTTP Bearer authentication.
@@ -367,144 +367,144 @@ static CURLcode http_output_bearer(struct connectdata *conn)
#endif
-/* pickoneauth() selects the most favourable authentication method from the
- * ones available and the ones we want.
- *
- * return TRUE if one was picked
- */
+/* pickoneauth() selects the most favourable authentication method from the
+ * ones available and the ones we want.
+ *
+ * return TRUE if one was picked
+ */
static bool pickoneauth(struct auth *pick, unsigned long mask)
-{
- bool picked;
- /* only deal with authentication we want */
+{
+ bool picked;
+ /* only deal with authentication we want */
unsigned long avail = pick->avail & pick->want & mask;
- picked = TRUE;
-
- /* The order of these checks is highly relevant, as this will be the order
- of preference in case of the existence of multiple accepted types. */
+ picked = TRUE;
+
+ /* The order of these checks is highly relevant, as this will be the order
+ of preference in case of the existence of multiple accepted types. */
if(avail & CURLAUTH_NEGOTIATE)
pick->picked = CURLAUTH_NEGOTIATE;
else if(avail & CURLAUTH_BEARER)
pick->picked = CURLAUTH_BEARER;
- else if(avail & CURLAUTH_DIGEST)
- pick->picked = CURLAUTH_DIGEST;
- else if(avail & CURLAUTH_NTLM)
- pick->picked = CURLAUTH_NTLM;
- else if(avail & CURLAUTH_NTLM_WB)
- pick->picked = CURLAUTH_NTLM_WB;
- else if(avail & CURLAUTH_BASIC)
- pick->picked = CURLAUTH_BASIC;
- else {
- pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
- picked = FALSE;
- }
- pick->avail = CURLAUTH_NONE; /* clear it here */
-
- return picked;
-}
-
-/*
+ else if(avail & CURLAUTH_DIGEST)
+ pick->picked = CURLAUTH_DIGEST;
+ else if(avail & CURLAUTH_NTLM)
+ pick->picked = CURLAUTH_NTLM;
+ else if(avail & CURLAUTH_NTLM_WB)
+ pick->picked = CURLAUTH_NTLM_WB;
+ else if(avail & CURLAUTH_BASIC)
+ pick->picked = CURLAUTH_BASIC;
+ else {
+ pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
+ picked = FALSE;
+ }
+ pick->avail = CURLAUTH_NONE; /* clear it here */
+
+ return picked;
+}
+
+/*
* http_perhapsrewind()
- *
- * If we are doing POST or PUT {
- * If we have more data to send {
- * If we are doing NTLM {
- * Keep sending since we must not disconnect
- * }
- * else {
- * If there is more than just a little data left to send, close
- * the current connection by force.
- * }
- * }
- * If we have sent any data {
- * If we don't have track of all the data {
- * call app to tell it to rewind
- * }
- * else {
- * rewind internally so that the operation can restart fine
- * }
- * }
- * }
- */
-static CURLcode http_perhapsrewind(struct connectdata *conn)
-{
+ *
+ * If we are doing POST or PUT {
+ * If we have more data to send {
+ * If we are doing NTLM {
+ * Keep sending since we must not disconnect
+ * }
+ * else {
+ * If there is more than just a little data left to send, close
+ * the current connection by force.
+ * }
+ * }
+ * If we have sent any data {
+ * If we don't have track of all the data {
+ * call app to tell it to rewind
+ * }
+ * else {
+ * rewind internally so that the operation can restart fine
+ * }
+ * }
+ * }
+ */
+static CURLcode http_perhapsrewind(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
struct HTTP *http = data->req.p.http;
- curl_off_t bytessent;
- curl_off_t expectsend = -1; /* default is unknown */
-
- if(!http)
- /* If this is still NULL, we have not reach very far and we can safely
- skip this rewinding stuff */
- return CURLE_OK;
-
+ curl_off_t bytessent;
+ curl_off_t expectsend = -1; /* default is unknown */
+
+ if(!http)
+ /* If this is still NULL, we have not reach very far and we can safely
+ skip this rewinding stuff */
+ return CURLE_OK;
+
switch(data->state.httpreq) {
- case HTTPREQ_GET:
- case HTTPREQ_HEAD:
- return CURLE_OK;
- default:
- break;
- }
-
+ case HTTPREQ_GET:
+ case HTTPREQ_HEAD:
+ return CURLE_OK;
+ default:
+ break;
+ }
+
bytessent = data->req.writebytecount;
-
+
if(conn->bits.authneg) {
- /* This is a state where we are known to be negotiating and we don't send
- any data then. */
- expectsend = 0;
+ /* This is a state where we are known to be negotiating and we don't send
+ any data then. */
+ expectsend = 0;
}
else if(!conn->bits.protoconnstart) {
/* HTTP CONNECT in progress: there is no body */
expectsend = 0;
}
- else {
- /* figure out how much data we are expected to send */
+ else {
+ /* figure out how much data we are expected to send */
switch(data->state.httpreq) {
- case HTTPREQ_POST:
- case HTTPREQ_PUT:
+ case HTTPREQ_POST:
+ case HTTPREQ_PUT:
if(data->state.infilesize != -1)
expectsend = data->state.infilesize;
- break;
- case HTTPREQ_POST_FORM:
+ break;
+ case HTTPREQ_POST_FORM:
case HTTPREQ_POST_MIME:
- expectsend = http->postsize;
- break;
- default:
- break;
- }
- }
-
- conn->bits.rewindaftersend = FALSE; /* default */
-
- if((expectsend == -1) || (expectsend > bytessent)) {
+ expectsend = http->postsize;
+ break;
+ default:
+ break;
+ }
+ }
+
+ conn->bits.rewindaftersend = FALSE; /* default */
+
+ if((expectsend == -1) || (expectsend > bytessent)) {
#if defined(USE_NTLM)
- /* There is still data left to send */
- if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
- (data->state.authhost.picked == CURLAUTH_NTLM) ||
- (data->state.authproxy.picked == CURLAUTH_NTLM_WB) ||
- (data->state.authhost.picked == CURLAUTH_NTLM_WB)) {
- if(((expectsend - bytessent) < 2000) ||
+ /* There is still data left to send */
+ if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
+ (data->state.authhost.picked == CURLAUTH_NTLM) ||
+ (data->state.authproxy.picked == CURLAUTH_NTLM_WB) ||
+ (data->state.authhost.picked == CURLAUTH_NTLM_WB)) {
+ if(((expectsend - bytessent) < 2000) ||
(conn->http_ntlm_state != NTLMSTATE_NONE) ||
(conn->proxy_ntlm_state != NTLMSTATE_NONE)) {
- /* The NTLM-negotiation has started *OR* there is just a little (<2K)
- data left to send, keep on sending. */
-
- /* rewind data when completely done sending! */
+ /* The NTLM-negotiation has started *OR* there is just a little (<2K)
+ data left to send, keep on sending. */
+
+ /* rewind data when completely done sending! */
if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) {
- conn->bits.rewindaftersend = TRUE;
- infof(data, "Rewind stream after send\n");
- }
-
- return CURLE_OK;
- }
-
- if(conn->bits.close)
- /* this is already marked to get closed */
- return CURLE_OK;
-
+ conn->bits.rewindaftersend = TRUE;
+ infof(data, "Rewind stream after send\n");
+ }
+
+ return CURLE_OK;
+ }
+
+ if(conn->bits.close)
+ /* this is already marked to get closed */
+ return CURLE_OK;
+
infof(data, "NTLM send, close instead of sending %"
CURL_FORMAT_CURL_OFF_T " bytes\n",
(curl_off_t)(expectsend - bytessent));
- }
+ }
#endif
#if defined(USE_SPNEGO)
/* There is still data left to send */
@@ -515,7 +515,7 @@ static CURLcode http_perhapsrewind(struct connectdata *conn)
(conn->proxy_negotiate_state != GSS_AUTHNONE)) {
/* The NEGOTIATE-negotiation has started *OR*
there is just a little (<2K) data left to send, keep on sending. */
-
+
/* rewind data when completely done sending! */
if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) {
conn->bits.rewindaftersend = TRUE;
@@ -537,69 +537,69 @@ static CURLcode http_perhapsrewind(struct connectdata *conn)
/* This is not NEGOTIATE/NTLM or many bytes left to send: close */
streamclose(conn, "Mid-auth HTTP and much data left to send");
- data->req.size = 0; /* don't download any more than 0 bytes */
-
- /* There still is data left to send, but this connection is marked for
- closure so we can safely do the rewind right now */
- }
-
- if(bytessent)
- /* we rewind now at once since if we already sent something */
- return Curl_readrewind(conn);
-
- return CURLE_OK;
-}
-
-/*
- * Curl_http_auth_act() gets called when all HTTP headers have been received
- * and it checks what authentication methods that are available and decides
- * which one (if any) to use. It will set 'newurl' if an auth method was
- * picked.
- */
-
-CURLcode Curl_http_auth_act(struct connectdata *conn)
-{
+ data->req.size = 0; /* don't download any more than 0 bytes */
+
+ /* There still is data left to send, but this connection is marked for
+ closure so we can safely do the rewind right now */
+ }
+
+ if(bytessent)
+ /* we rewind now at once since if we already sent something */
+ return Curl_readrewind(conn);
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_http_auth_act() gets called when all HTTP headers have been received
+ * and it checks what authentication methods that are available and decides
+ * which one (if any) to use. It will set 'newurl' if an auth method was
+ * picked.
+ */
+
+CURLcode Curl_http_auth_act(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- bool pickhost = FALSE;
- bool pickproxy = FALSE;
+ bool pickhost = FALSE;
+ bool pickproxy = FALSE;
CURLcode result = CURLE_OK;
unsigned long authmask = ~0ul;
-
+
if(!data->set.str[STRING_BEARER])
authmask &= (unsigned long)~CURLAUTH_BEARER;
- if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
- /* this is a transient response code, ignore */
- return CURLE_OK;
-
- if(data->state.authproblem)
- return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
-
+ if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
+ /* this is a transient response code, ignore */
+ return CURLE_OK;
+
+ if(data->state.authproblem)
+ return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
+
if((conn->bits.user_passwd || data->set.str[STRING_BEARER]) &&
- ((data->req.httpcode == 401) ||
- (conn->bits.authneg && data->req.httpcode < 300))) {
+ ((data->req.httpcode == 401) ||
+ (conn->bits.authneg && data->req.httpcode < 300))) {
pickhost = pickoneauth(&data->state.authhost, authmask);
- if(!pickhost)
- data->state.authproblem = TRUE;
+ if(!pickhost)
+ data->state.authproblem = TRUE;
if(data->state.authhost.picked == CURLAUTH_NTLM &&
conn->httpversion > 11) {
infof(data, "Forcing HTTP/1.1 for NTLM");
connclose(conn, "Force HTTP/1.1 connection");
conn->data->set.httpversion = CURL_HTTP_VERSION_1_1;
}
- }
+ }
#ifndef CURL_DISABLE_PROXY
- if(conn->bits.proxy_user_passwd &&
- ((data->req.httpcode == 407) ||
- (conn->bits.authneg && data->req.httpcode < 300))) {
+ if(conn->bits.proxy_user_passwd &&
+ ((data->req.httpcode == 407) ||
+ (conn->bits.authneg && data->req.httpcode < 300))) {
pickproxy = pickoneauth(&data->state.authproxy,
authmask & ~CURLAUTH_BEARER);
- if(!pickproxy)
- data->state.authproblem = TRUE;
- }
+ if(!pickproxy)
+ data->state.authproblem = TRUE;
+ }
#endif
-
- if(pickhost || pickproxy) {
+
+ if(pickhost || pickproxy) {
if((data->state.httpreq != HTTPREQ_GET) &&
(data->state.httpreq != HTTPREQ_HEAD) &&
!conn->bits.rewindaftersend) {
@@ -607,100 +607,100 @@ CURLcode Curl_http_auth_act(struct connectdata *conn)
if(result)
return result;
}
- /* In case this is GSS auth, the newurl field is already allocated so
- we must make sure to free it before allocating a new one. As figured
- out in bug #2284386 */
- Curl_safefree(data->req.newurl);
- data->req.newurl = strdup(data->change.url); /* clone URL */
- if(!data->req.newurl)
- return CURLE_OUT_OF_MEMORY;
- }
- else if((data->req.httpcode < 300) &&
- (!data->state.authhost.done) &&
- conn->bits.authneg) {
- /* no (known) authentication available,
- authentication is not "done" yet and
- no authentication seems to be required and
- we didn't try HEAD or GET */
+ /* In case this is GSS auth, the newurl field is already allocated so
+ we must make sure to free it before allocating a new one. As figured
+ out in bug #2284386 */
+ Curl_safefree(data->req.newurl);
+ data->req.newurl = strdup(data->change.url); /* clone URL */
+ if(!data->req.newurl)
+ return CURLE_OUT_OF_MEMORY;
+ }
+ else if((data->req.httpcode < 300) &&
+ (!data->state.authhost.done) &&
+ conn->bits.authneg) {
+ /* no (known) authentication available,
+ authentication is not "done" yet and
+ no authentication seems to be required and
+ we didn't try HEAD or GET */
if((data->state.httpreq != HTTPREQ_GET) &&
(data->state.httpreq != HTTPREQ_HEAD)) {
- data->req.newurl = strdup(data->change.url); /* clone URL */
- if(!data->req.newurl)
- return CURLE_OUT_OF_MEMORY;
- data->state.authhost.done = TRUE;
- }
- }
- if(http_should_fail(conn)) {
+ data->req.newurl = strdup(data->change.url); /* clone URL */
+ if(!data->req.newurl)
+ return CURLE_OUT_OF_MEMORY;
+ data->state.authhost.done = TRUE;
+ }
+ }
+ if(http_should_fail(conn)) {
failf(data, "The requested URL returned error: %d",
data->req.httpcode);
result = CURLE_HTTP_RETURNED_ERROR;
- }
-
+ }
+
return result;
-}
-
+}
+
#ifndef CURL_DISABLE_HTTP_AUTH
-/*
- * Output the correct authentication header depending on the auth type
- * and whether or not it is to a proxy.
- */
-static CURLcode
-output_auth_headers(struct connectdata *conn,
- struct auth *authstatus,
- const char *request,
- const char *path,
- bool proxy)
-{
+/*
+ * Output the correct authentication header depending on the auth type
+ * and whether or not it is to a proxy.
+ */
+static CURLcode
+output_auth_headers(struct connectdata *conn,
+ struct auth *authstatus,
+ const char *request,
+ const char *path,
+ bool proxy)
+{
const char *auth = NULL;
- CURLcode result = CURLE_OK;
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
-#ifdef CURL_DISABLE_CRYPTO_AUTH
- (void)request;
- (void)path;
-#endif
-
+
+#ifdef CURL_DISABLE_CRYPTO_AUTH
+ (void)request;
+ (void)path;
+#endif
+
#ifdef USE_SPNEGO
if(authstatus->picked == CURLAUTH_NEGOTIATE) {
auth = "Negotiate";
- result = Curl_output_negotiate(conn, proxy);
- if(result)
- return result;
- }
- else
-#endif
-#ifdef USE_NTLM
- if(authstatus->picked == CURLAUTH_NTLM) {
+ result = Curl_output_negotiate(conn, proxy);
+ if(result)
+ return result;
+ }
+ else
+#endif
+#ifdef USE_NTLM
+ if(authstatus->picked == CURLAUTH_NTLM) {
auth = "NTLM";
- result = Curl_output_ntlm(conn, proxy);
- if(result)
- return result;
- }
- else
-#endif
-#if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
- if(authstatus->picked == CURLAUTH_NTLM_WB) {
+ result = Curl_output_ntlm(conn, proxy);
+ if(result)
+ return result;
+ }
+ else
+#endif
+#if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
+ if(authstatus->picked == CURLAUTH_NTLM_WB) {
auth = "NTLM_WB";
- result = Curl_output_ntlm_wb(conn, proxy);
- if(result)
- return result;
- }
- else
-#endif
-#ifndef CURL_DISABLE_CRYPTO_AUTH
- if(authstatus->picked == CURLAUTH_DIGEST) {
+ result = Curl_output_ntlm_wb(conn, proxy);
+ if(result)
+ return result;
+ }
+ else
+#endif
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+ if(authstatus->picked == CURLAUTH_DIGEST) {
auth = "Digest";
- result = Curl_output_digest(conn,
- proxy,
- (const unsigned char *)request,
- (const unsigned char *)path);
- if(result)
- return result;
- }
- else
-#endif
- if(authstatus->picked == CURLAUTH_BASIC) {
- /* Basic */
+ result = Curl_output_digest(conn,
+ proxy,
+ (const unsigned char *)request,
+ (const unsigned char *)path);
+ if(result)
+ return result;
+ }
+ else
+#endif
+ if(authstatus->picked == CURLAUTH_BASIC) {
+ /* Basic */
if(
#ifndef CURL_DISABLE_PROXY
(proxy && conn->bits.proxy_user_passwd &&
@@ -709,15 +709,15 @@ output_auth_headers(struct connectdata *conn,
(!proxy && conn->bits.user_passwd &&
!Curl_checkheaders(conn, "Authorization"))) {
auth = "Basic";
- result = http_output_basic(conn, proxy);
- if(result)
- return result;
- }
-
- /* NOTE: this function should set 'done' TRUE, as the other auth
- functions work that way */
- authstatus->done = TRUE;
- }
+ result = http_output_basic(conn, proxy);
+ if(result)
+ return result;
+ }
+
+ /* NOTE: this function should set 'done' TRUE, as the other auth
+ functions work that way */
+ authstatus->done = TRUE;
+ }
if(authstatus->picked == CURLAUTH_BEARER) {
/* Bearer */
if((!proxy && data->set.str[STRING_BEARER] &&
@@ -727,15 +727,15 @@ output_auth_headers(struct connectdata *conn,
if(result)
return result;
}
-
+
/* NOTE: this function should set 'done' TRUE, as the other auth
functions work that way */
authstatus->done = TRUE;
}
- if(auth) {
+ if(auth) {
#ifndef CURL_DISABLE_PROXY
- infof(data, "%s auth using %s with user '%s'\n",
+ infof(data, "%s auth using %s with user '%s'\n",
proxy ? "Proxy" : "Server", auth,
proxy ? (conn->http_proxy.user ? conn->http_proxy.user : "") :
(conn->user ? conn->user : ""));
@@ -744,99 +744,99 @@ output_auth_headers(struct connectdata *conn,
auth, conn->user ? conn->user : "");
#endif
authstatus->multipass = (!authstatus->done) ? TRUE : FALSE;
- }
- else
+ }
+ else
authstatus->multipass = FALSE;
-
- return CURLE_OK;
-}
-
-/**
- * Curl_http_output_auth() setups the authentication headers for the
- * host/proxy and the correct authentication
- * method. conn->data->state.authdone is set to TRUE when authentication is
- * done.
- *
- * @param conn all information about the current connection
- * @param request pointer to the request keyword
+
+ return CURLE_OK;
+}
+
+/**
+ * Curl_http_output_auth() setups the authentication headers for the
+ * host/proxy and the correct authentication
+ * method. conn->data->state.authdone is set to TRUE when authentication is
+ * done.
+ *
+ * @param conn all information about the current connection
+ * @param request pointer to the request keyword
* @param path pointer to the requested path; should include query part
- * @param proxytunnel boolean if this is the request setting up a "proxy
- * tunnel"
- *
- * @returns CURLcode
- */
-CURLcode
-Curl_http_output_auth(struct connectdata *conn,
- const char *request,
- const char *path,
- bool proxytunnel) /* TRUE if this is the request setting
- up the proxy tunnel */
-{
- CURLcode result = CURLE_OK;
+ * @param proxytunnel boolean if this is the request setting up a "proxy
+ * tunnel"
+ *
+ * @returns CURLcode
+ */
+CURLcode
+Curl_http_output_auth(struct connectdata *conn,
+ const char *request,
+ const char *path,
+ bool proxytunnel) /* TRUE if this is the request setting
+ up the proxy tunnel */
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct auth *authhost;
- struct auth *authproxy;
-
- DEBUGASSERT(data);
-
- authhost = &data->state.authhost;
- authproxy = &data->state.authproxy;
-
+ struct auth *authhost;
+ struct auth *authproxy;
+
+ DEBUGASSERT(data);
+
+ authhost = &data->state.authhost;
+ authproxy = &data->state.authproxy;
+
if(
#ifndef CURL_DISABLE_PROXY
(conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
#endif
conn->bits.user_passwd || data->set.str[STRING_BEARER])
/* continue please */;
- else {
- authhost->done = TRUE;
- authproxy->done = TRUE;
- return CURLE_OK; /* no authentication with no user or password */
- }
-
- if(authhost->want && !authhost->picked)
- /* The app has selected one or more methods, but none has been picked
- so far by a server round-trip. Then we set the picked one to the
- want one, and if this is one single bit it'll be used instantly. */
- authhost->picked = authhost->want;
-
- if(authproxy->want && !authproxy->picked)
- /* The app has selected one or more methods, but none has been picked so
- far by a proxy round-trip. Then we set the picked one to the want one,
- and if this is one single bit it'll be used instantly. */
- authproxy->picked = authproxy->want;
-
-#ifndef CURL_DISABLE_PROXY
- /* Send proxy authentication header if needed */
- if(conn->bits.httpproxy &&
+ else {
+ authhost->done = TRUE;
+ authproxy->done = TRUE;
+ return CURLE_OK; /* no authentication with no user or password */
+ }
+
+ if(authhost->want && !authhost->picked)
+ /* The app has selected one or more methods, but none has been picked
+ so far by a server round-trip. Then we set the picked one to the
+ want one, and if this is one single bit it'll be used instantly. */
+ authhost->picked = authhost->want;
+
+ if(authproxy->want && !authproxy->picked)
+ /* The app has selected one or more methods, but none has been picked so
+ far by a proxy round-trip. Then we set the picked one to the want one,
+ and if this is one single bit it'll be used instantly. */
+ authproxy->picked = authproxy->want;
+
+#ifndef CURL_DISABLE_PROXY
+ /* Send proxy authentication header if needed */
+ if(conn->bits.httpproxy &&
(conn->bits.tunnel_proxy == (bit)proxytunnel)) {
- result = output_auth_headers(conn, authproxy, request, path, TRUE);
- if(result)
- return result;
- }
- else
-#else
- (void)proxytunnel;
-#endif /* CURL_DISABLE_PROXY */
- /* we have no proxy so let's pretend we're done authenticating
- with it */
- authproxy->done = TRUE;
-
- /* To prevent the user+password to get sent to other than the original
- host due to a location-follow, we do some weirdo checks here */
- if(!data->state.this_is_a_follow ||
- conn->bits.netrc ||
- !data->state.first_host ||
+ result = output_auth_headers(conn, authproxy, request, path, TRUE);
+ if(result)
+ return result;
+ }
+ else
+#else
+ (void)proxytunnel;
+#endif /* CURL_DISABLE_PROXY */
+ /* we have no proxy so let's pretend we're done authenticating
+ with it */
+ authproxy->done = TRUE;
+
+ /* To prevent the user+password to get sent to other than the original
+ host due to a location-follow, we do some weirdo checks here */
+ if(!data->state.this_is_a_follow ||
+ conn->bits.netrc ||
+ !data->state.first_host ||
data->set.allow_auth_to_other_hosts ||
strcasecompare(data->state.first_host, conn->host.name)) {
- result = output_auth_headers(conn, authhost, request, path, FALSE);
- }
- else
- authhost->done = TRUE;
-
- return result;
-}
-
+ result = output_auth_headers(conn, authhost, request, path, FALSE);
+ }
+ else
+ authhost->done = TRUE;
+
+ return result;
+}
+
#else
/* when disabled */
CURLcode
@@ -853,52 +853,52 @@ Curl_http_output_auth(struct connectdata *conn,
}
#endif
-/*
- * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
- * headers. They are dealt with both in the transfer.c main loop and in the
- * proxy CONNECT loop.
- */
-
+/*
+ * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
+ * headers. They are dealt with both in the transfer.c main loop and in the
+ * proxy CONNECT loop.
+ */
+
CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
const char *auth) /* the first non-space */
-{
- /*
- * This resource requires authentication
- */
+{
+ /*
+ * This resource requires authentication
+ */
struct Curl_easy *data = conn->data;
-
+
#ifdef USE_SPNEGO
curlnegotiate *negstate = proxy ? &conn->proxy_negotiate_state :
&conn->http_negotiate_state;
#endif
- unsigned long *availp;
- struct auth *authp;
-
+ unsigned long *availp;
+ struct auth *authp;
+
if(proxy) {
- availp = &data->info.proxyauthavail;
- authp = &data->state.authproxy;
- }
- else {
- availp = &data->info.httpauthavail;
- authp = &data->state.authhost;
- }
-
- /*
- * Here we check if we want the specific single authentication (using ==) and
- * if we do, we initiate usage of it.
- *
- * If the provided authentication is wanted as one out of several accepted
- * types (using &), we OR this authentication type to the authavail
- * variable.
- *
- * Note:
- *
- * ->picked is first set to the 'want' value (one or more bits) before the
- * request is sent, and then it is again set _after_ all response 401/407
- * headers have been received but then only to a single preferred method
- * (bit).
- */
-
+ availp = &data->info.proxyauthavail;
+ authp = &data->state.authproxy;
+ }
+ else {
+ availp = &data->info.httpauthavail;
+ authp = &data->state.authhost;
+ }
+
+ /*
+ * Here we check if we want the specific single authentication (using ==) and
+ * if we do, we initiate usage of it.
+ *
+ * If the provided authentication is wanted as one out of several accepted
+ * types (using &), we OR this authentication type to the authavail
+ * variable.
+ *
+ * Note:
+ *
+ * ->picked is first set to the 'want' value (one or more bits) before the
+ * request is sent, and then it is again set _after_ all response 401/407
+ * headers have been received but then only to a single preferred method
+ * (bit).
+ */
+
while(*auth) {
#ifdef USE_SPNEGO
if(checkprefix("Negotiate", auth)) {
@@ -906,7 +906,7 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
Curl_auth_is_spnego_supported()) {
*availp |= CURLAUTH_NEGOTIATE;
authp->avail |= CURLAUTH_NEGOTIATE;
-
+
if(authp->picked == CURLAUTH_NEGOTIATE) {
CURLcode result = Curl_input_negotiate(conn, proxy, auth);
if(!result) {
@@ -917,16 +917,16 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
data->state.authproblem = FALSE;
/* we received a GSS auth token and we dealt with it fine */
*negstate = GSS_AUTHRECV;
- }
+ }
else
data->state.authproblem = TRUE;
- }
- }
- }
- else
-#endif
-#ifdef USE_NTLM
- /* NTLM support requires the SSL crypto libs */
+ }
+ }
+ }
+ else
+#endif
+#ifdef USE_NTLM
+ /* NTLM support requires the SSL crypto libs */
if(checkprefix("NTLM", auth)) {
if((authp->avail & CURLAUTH_NTLM) ||
(authp->avail & CURLAUTH_NTLM_WB) ||
@@ -940,65 +940,65 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
CURLcode result = Curl_input_ntlm(conn, proxy, auth);
if(!result) {
data->state.authproblem = FALSE;
-#ifdef NTLM_WB_ENABLED
+#ifdef NTLM_WB_ENABLED
if(authp->picked == CURLAUTH_NTLM_WB) {
*availp &= ~CURLAUTH_NTLM;
authp->avail &= ~CURLAUTH_NTLM;
*availp |= CURLAUTH_NTLM_WB;
authp->avail |= CURLAUTH_NTLM_WB;
-
+
result = Curl_input_ntlm_wb(conn, proxy, auth);
if(result) {
infof(data, "Authentication problem. Ignoring this.\n");
data->state.authproblem = TRUE;
}
- }
+ }
#endif
- }
+ }
else {
infof(data, "Authentication problem. Ignoring this.\n");
data->state.authproblem = TRUE;
}
- }
- }
- }
- else
-#endif
-#ifndef CURL_DISABLE_CRYPTO_AUTH
+ }
+ }
+ }
+ else
+#endif
+#ifndef CURL_DISABLE_CRYPTO_AUTH
if(checkprefix("Digest", auth)) {
if((authp->avail & CURLAUTH_DIGEST) != 0)
- infof(data, "Ignoring duplicate digest auth header.\n");
+ infof(data, "Ignoring duplicate digest auth header.\n");
else if(Curl_auth_is_digest_supported()) {
CURLcode result;
- *availp |= CURLAUTH_DIGEST;
- authp->avail |= CURLAUTH_DIGEST;
-
- /* We call this function on input Digest headers even if Digest
- * authentication isn't activated yet, as we need to store the
+ *availp |= CURLAUTH_DIGEST;
+ authp->avail |= CURLAUTH_DIGEST;
+
+ /* We call this function on input Digest headers even if Digest
+ * authentication isn't activated yet, as we need to store the
* incoming data from this header in case we are going to use
* Digest */
result = Curl_input_digest(conn, proxy, auth);
if(result) {
- infof(data, "Authentication problem. Ignoring this.\n");
- data->state.authproblem = TRUE;
- }
- }
- }
- else
-#endif
+ infof(data, "Authentication problem. Ignoring this.\n");
+ data->state.authproblem = TRUE;
+ }
+ }
+ }
+ else
+#endif
if(checkprefix("Basic", auth)) {
- *availp |= CURLAUTH_BASIC;
- authp->avail |= CURLAUTH_BASIC;
- if(authp->picked == CURLAUTH_BASIC) {
- /* We asked for Basic authentication but got a 40X back
- anyway, which basically means our name+password isn't
- valid. */
- authp->avail = CURLAUTH_NONE;
- infof(data, "Authentication problem. Ignoring this.\n");
- data->state.authproblem = TRUE;
- }
- }
+ *availp |= CURLAUTH_BASIC;
+ authp->avail |= CURLAUTH_BASIC;
+ if(authp->picked == CURLAUTH_BASIC) {
+ /* We asked for Basic authentication but got a 40X back
+ anyway, which basically means our name+password isn't
+ valid. */
+ authp->avail = CURLAUTH_NONE;
+ infof(data, "Authentication problem. Ignoring this.\n");
+ data->state.authproblem = TRUE;
+ }
+ }
else
if(checkprefix("Bearer", auth)) {
*availp |= CURLAUTH_BEARER;
@@ -1011,151 +1011,151 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
data->state.authproblem = TRUE;
}
}
-
- /* there may be multiple methods on one line, so keep reading */
+
+ /* there may be multiple methods on one line, so keep reading */
while(*auth && *auth != ',') /* read up to the next comma */
auth++;
if(*auth == ',') /* if we're on a comma, skip it */
auth++;
while(*auth && ISSPACE(*auth))
auth++;
- }
-
- return CURLE_OK;
-}
-
-/**
- * http_should_fail() determines whether an HTTP response has gotten us
- * into an error state or not.
- *
- * @param conn all information about the current connection
- *
- * @retval 0 communications should continue
- *
- * @retval 1 communications should not continue
- */
-static int http_should_fail(struct connectdata *conn)
-{
+ }
+
+ return CURLE_OK;
+}
+
+/**
+ * http_should_fail() determines whether an HTTP response has gotten us
+ * into an error state or not.
+ *
+ * @param conn all information about the current connection
+ *
+ * @retval 0 communications should continue
+ *
+ * @retval 1 communications should not continue
+ */
+static int http_should_fail(struct connectdata *conn)
+{
struct Curl_easy *data;
- int httpcode;
-
- DEBUGASSERT(conn);
- data = conn->data;
- DEBUGASSERT(data);
-
- httpcode = data->req.httpcode;
-
- /*
- ** If we haven't been asked to fail on error,
- ** don't fail.
- */
- if(!data->set.http_fail_on_error)
- return 0;
-
- /*
- ** Any code < 400 is never terminal.
- */
- if(httpcode < 400)
- return 0;
-
- /*
- ** Any code >= 400 that's not 401 or 407 is always
- ** a terminal error
- */
+ int httpcode;
+
+ DEBUGASSERT(conn);
+ data = conn->data;
+ DEBUGASSERT(data);
+
+ httpcode = data->req.httpcode;
+
+ /*
+ ** If we haven't been asked to fail on error,
+ ** don't fail.
+ */
+ if(!data->set.http_fail_on_error)
+ return 0;
+
+ /*
+ ** Any code < 400 is never terminal.
+ */
+ if(httpcode < 400)
+ return 0;
+
+ /*
+ ** Any code >= 400 that's not 401 or 407 is always
+ ** a terminal error
+ */
if((httpcode != 401) && (httpcode != 407))
- return 1;
-
- /*
- ** All we have left to deal with is 401 and 407
- */
- DEBUGASSERT((httpcode == 401) || (httpcode == 407));
-
- /*
- ** Examine the current authentication state to see if this
- ** is an error. The idea is for this function to get
- ** called after processing all the headers in a response
- ** message. So, if we've been to asked to authenticate a
- ** particular stage, and we've done it, we're OK. But, if
- ** we're already completely authenticated, it's not OK to
- ** get another 401 or 407.
- **
- ** It is possible for authentication to go stale such that
- ** the client needs to reauthenticate. Once that info is
- ** available, use it here.
- */
-
- /*
- ** Either we're not authenticating, or we're supposed to
- ** be authenticating something else. This is an error.
- */
- if((httpcode == 401) && !conn->bits.user_passwd)
- return TRUE;
+ return 1;
+
+ /*
+ ** All we have left to deal with is 401 and 407
+ */
+ DEBUGASSERT((httpcode == 401) || (httpcode == 407));
+
+ /*
+ ** Examine the current authentication state to see if this
+ ** is an error. The idea is for this function to get
+ ** called after processing all the headers in a response
+ ** message. So, if we've been to asked to authenticate a
+ ** particular stage, and we've done it, we're OK. But, if
+ ** we're already completely authenticated, it's not OK to
+ ** get another 401 or 407.
+ **
+ ** It is possible for authentication to go stale such that
+ ** the client needs to reauthenticate. Once that info is
+ ** available, use it here.
+ */
+
+ /*
+ ** Either we're not authenticating, or we're supposed to
+ ** be authenticating something else. This is an error.
+ */
+ if((httpcode == 401) && !conn->bits.user_passwd)
+ return TRUE;
#ifndef CURL_DISABLE_PROXY
- if((httpcode == 407) && !conn->bits.proxy_user_passwd)
- return TRUE;
-#endif
-
- return data->state.authproblem;
-}
-
-/*
- * readmoredata() is a "fread() emulation" to provide POST and/or request
- * data. It is used when a huge POST is to be made and the entire chunk wasn't
- * sent in the first send(). This function will then be called from the
- * transfer.c loop when more data is to be sent to the peer.
- *
- * Returns the amount of bytes it filled the buffer with.
- */
-static size_t readmoredata(char *buffer,
- size_t size,
- size_t nitems,
- void *userp)
-{
- struct connectdata *conn = (struct connectdata *)userp;
+ if((httpcode == 407) && !conn->bits.proxy_user_passwd)
+ return TRUE;
+#endif
+
+ return data->state.authproblem;
+}
+
+/*
+ * readmoredata() is a "fread() emulation" to provide POST and/or request
+ * data. It is used when a huge POST is to be made and the entire chunk wasn't
+ * sent in the first send(). This function will then be called from the
+ * transfer.c loop when more data is to be sent to the peer.
+ *
+ * Returns the amount of bytes it filled the buffer with.
+ */
+static size_t readmoredata(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *userp)
+{
+ struct connectdata *conn = (struct connectdata *)userp;
struct HTTP *http = conn->data->req.p.http;
- size_t fullsize = size * nitems;
-
+ size_t fullsize = size * nitems;
+
if(!http->postsize)
- /* nothing to return */
- return 0;
-
- /* make sure that a HTTP request is never sent away chunked! */
- conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
-
- if(http->postsize <= (curl_off_t)fullsize) {
- memcpy(buffer, http->postdata, (size_t)http->postsize);
- fullsize = (size_t)http->postsize;
-
- if(http->backup.postsize) {
- /* move backup data into focus and continue on that */
- http->postdata = http->backup.postdata;
- http->postsize = http->backup.postsize;
+ /* nothing to return */
+ return 0;
+
+ /* make sure that a HTTP request is never sent away chunked! */
+ conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
+
+ if(http->postsize <= (curl_off_t)fullsize) {
+ memcpy(buffer, http->postdata, (size_t)http->postsize);
+ fullsize = (size_t)http->postsize;
+
+ if(http->backup.postsize) {
+ /* move backup data into focus and continue on that */
+ http->postdata = http->backup.postdata;
+ http->postsize = http->backup.postsize;
conn->data->state.fread_func = http->backup.fread_func;
conn->data->state.in = http->backup.fread_in;
-
- http->sending++; /* move one step up */
-
+
+ http->sending++; /* move one step up */
+
http->backup.postsize = 0;
- }
- else
- http->postsize = 0;
-
- return fullsize;
- }
-
- memcpy(buffer, http->postdata, fullsize);
- http->postdata += fullsize;
- http->postsize -= fullsize;
-
- return fullsize;
-}
-
-/*
+ }
+ else
+ http->postsize = 0;
+
+ return fullsize;
+ }
+
+ memcpy(buffer, http->postdata, fullsize);
+ http->postdata += fullsize;
+ http->postsize -= fullsize;
+
+ return fullsize;
+}
+
+/*
* Curl_buffer_send() sends a header buffer and frees all associated
- * memory. Body data may be appended to the header data if desired.
- *
- * Returns CURLcode
- */
+ * memory. Body data may be appended to the header data if desired.
+ *
+ * Returns CURLcode
+ */
CURLcode Curl_buffer_send(struct dynbuf *in,
struct connectdata *conn,
/* add the number of sent bytes to this
@@ -1164,60 +1164,60 @@ CURLcode Curl_buffer_send(struct dynbuf *in,
/* how much of the buffer contains body data */
size_t included_body_bytes,
int socketindex)
-{
- ssize_t amount;
+{
+ ssize_t amount;
CURLcode result;
- char *ptr;
- size_t size;
+ char *ptr;
+ size_t size;
struct Curl_easy *data = conn->data;
struct HTTP *http = data->req.p.http;
- size_t sendsize;
- curl_socket_t sockfd;
- size_t headersize;
-
- DEBUGASSERT(socketindex <= SECONDARYSOCKET);
-
- sockfd = conn->sock[socketindex];
-
- /* The looping below is required since we use non-blocking sockets, but due
- to the circumstances we will just loop and try again and again etc */
-
+ size_t sendsize;
+ curl_socket_t sockfd;
+ size_t headersize;
+
+ DEBUGASSERT(socketindex <= SECONDARYSOCKET);
+
+ sockfd = conn->sock[socketindex];
+
+ /* The looping below is required since we use non-blocking sockets, but due
+ to the circumstances we will just loop and try again and again etc */
+
ptr = Curl_dyn_ptr(in);
size = Curl_dyn_len(in);
-
- headersize = size - included_body_bytes; /* the initial part that isn't body
- is header */
-
- DEBUGASSERT(size > included_body_bytes);
-
+
+ headersize = size - included_body_bytes; /* the initial part that isn't body
+ is header */
+
+ DEBUGASSERT(size > included_body_bytes);
+
result = Curl_convert_to_network(data, ptr, headersize);
- /* Curl_convert_to_network calls failf if unsuccessful */
+ /* Curl_convert_to_network calls failf if unsuccessful */
if(result) {
- /* conversion failed, free memory and return to the caller */
+ /* conversion failed, free memory and return to the caller */
Curl_dyn_free(in);
return result;
- }
-
+ }
+
if((conn->handler->flags & PROTOPT_SSL
#ifndef CURL_DISABLE_PROXY
|| conn->http_proxy.proxytype == CURLPROXY_HTTPS
#endif
)
&& conn->httpversion != 20) {
- /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk
- when we speak HTTPS, as if only a fraction of it is sent now, this data
- needs to fit into the normal read-callback buffer later on and that
- buffer is using this size.
- */
-
+ /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk
+ when we speak HTTPS, as if only a fraction of it is sent now, this data
+ needs to fit into the normal read-callback buffer later on and that
+ buffer is using this size.
+ */
+
sendsize = CURLMIN(size, CURL_MAX_WRITE_SIZE);
-
- /* OpenSSL is very picky and we must send the SAME buffer pointer to the
- library when we attempt to re-send this buffer. Sending the same data
- is not enough, we must use the exact same address. For this reason, we
- must copy the data to the uploadbuffer first, since that is the buffer
- we will be using if this send is retried later.
- */
+
+ /* OpenSSL is very picky and we must send the SAME buffer pointer to the
+ library when we attempt to re-send this buffer. Sending the same data
+ is not enough, we must use the exact same address. For this reason, we
+ must copy the data to the uploadbuffer first, since that is the buffer
+ we will be using if this send is retried later.
+ */
result = Curl_get_upload_buffer(data);
if(result) {
/* malloc failed, free memory and return to the caller */
@@ -1226,7 +1226,7 @@ CURLcode Curl_buffer_send(struct dynbuf *in,
}
memcpy(data->state.ulbuf, ptr, sendsize);
ptr = data->state.ulbuf;
- }
+ }
else {
#ifdef CURLDEBUG
/* Allow debug builds override this logic to force short initial sends */
@@ -1240,163 +1240,163 @@ CURLcode Curl_buffer_send(struct dynbuf *in,
}
else
#endif
- sendsize = size;
+ sendsize = size;
}
-
+
result = Curl_write(conn, sockfd, ptr, sendsize, &amount);
-
+
if(!result) {
- /*
- * Note that we may not send the entire chunk at once, and we have a set
- * number of data bytes at the end of the big buffer (out of which we may
- * only send away a part).
- */
- /* how much of the header that was sent */
+ /*
+ * Note that we may not send the entire chunk at once, and we have a set
+ * number of data bytes at the end of the big buffer (out of which we may
+ * only send away a part).
+ */
+ /* how much of the header that was sent */
size_t headlen = (size_t)amount>headersize ? headersize : (size_t)amount;
- size_t bodylen = amount - headlen;
-
+ size_t bodylen = amount - headlen;
+
/* this data _may_ contain binary stuff */
Curl_debug(data, CURLINFO_HEADER_OUT, ptr, headlen);
if(bodylen)
/* there was body data sent beyond the initial header part, pass that on
to the debug callback too */
Curl_debug(data, CURLINFO_DATA_OUT, ptr + headlen, bodylen);
-
- /* 'amount' can never be a very large value here so typecasting it so a
- signed 31 bit value should not cause problems even if ssize_t is
- 64bit */
- *bytes_written += (long)amount;
-
- if(http) {
+
+ /* 'amount' can never be a very large value here so typecasting it so a
+ signed 31 bit value should not cause problems even if ssize_t is
+ 64bit */
+ *bytes_written += (long)amount;
+
+ if(http) {
/* if we sent a piece of the body here, up the byte counter for it
accordingly */
data->req.writebytecount += bodylen;
Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
- if((size_t)amount != size) {
- /* The whole request could not be sent in one system call. We must
- queue it up and send it later when we get the chance. We must not
- loop here and wait until it might work again. */
-
- size -= amount;
-
+ if((size_t)amount != size) {
+ /* The whole request could not be sent in one system call. We must
+ queue it up and send it later when we get the chance. We must not
+ loop here and wait until it might work again. */
+
+ size -= amount;
+
ptr = Curl_dyn_ptr(in) + amount;
-
- /* backup the currently set pointers */
+
+ /* backup the currently set pointers */
http->backup.fread_func = data->state.fread_func;
http->backup.fread_in = data->state.in;
- http->backup.postdata = http->postdata;
- http->backup.postsize = http->postsize;
-
- /* set the new pointers for the request-sending */
+ http->backup.postdata = http->postdata;
+ http->backup.postsize = http->postsize;
+
+ /* set the new pointers for the request-sending */
data->state.fread_func = (curl_read_callback)readmoredata;
data->state.in = (void *)conn;
- http->postdata = ptr;
- http->postsize = (curl_off_t)size;
-
+ http->postdata = ptr;
+ http->postsize = (curl_off_t)size;
+
http->send_buffer = *in; /* copy the whole struct */
- http->sending = HTTPSEND_REQUEST;
-
- return CURLE_OK;
- }
- http->sending = HTTPSEND_BODY;
- /* the full buffer was sent, clean up and return */
- }
- else {
- if((size_t)amount != size)
- /* We have no continue-send mechanism now, fail. This can only happen
- when this function is used from the CONNECT sending function. We
- currently (stupidly) assume that the whole request is always sent
- away in the first single chunk.
-
- This needs FIXing.
- */
- return CURLE_SEND_ERROR;
- }
- }
+ http->sending = HTTPSEND_REQUEST;
+
+ return CURLE_OK;
+ }
+ http->sending = HTTPSEND_BODY;
+ /* the full buffer was sent, clean up and return */
+ }
+ else {
+ if((size_t)amount != size)
+ /* We have no continue-send mechanism now, fail. This can only happen
+ when this function is used from the CONNECT sending function. We
+ currently (stupidly) assume that the whole request is always sent
+ away in the first single chunk.
+
+ This needs FIXing.
+ */
+ return CURLE_SEND_ERROR;
+ }
+ }
Curl_dyn_free(in);
-
+
return result;
-}
-
-/* end of the add_buffer functions */
-/* ------------------------------------------------------------------------- */
-
-
-
-/*
- * Curl_compareheader()
- *
- * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
- * Pass headers WITH the colon.
- */
-bool
-Curl_compareheader(const char *headerline, /* line to check */
- const char *header, /* header keyword _with_ colon */
- const char *content) /* content string to find */
-{
- /* RFC2616, section 4.2 says: "Each header field consists of a name followed
- * by a colon (":") and the field value. Field names are case-insensitive.
- * The field value MAY be preceded by any amount of LWS, though a single SP
- * is preferred." */
-
- size_t hlen = strlen(header);
- size_t clen;
- size_t len;
- const char *start;
- const char *end;
-
+}
+
+/* end of the add_buffer functions */
+/* ------------------------------------------------------------------------- */
+
+
+
+/*
+ * Curl_compareheader()
+ *
+ * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
+ * Pass headers WITH the colon.
+ */
+bool
+Curl_compareheader(const char *headerline, /* line to check */
+ const char *header, /* header keyword _with_ colon */
+ const char *content) /* content string to find */
+{
+ /* RFC2616, section 4.2 says: "Each header field consists of a name followed
+ * by a colon (":") and the field value. Field names are case-insensitive.
+ * The field value MAY be preceded by any amount of LWS, though a single SP
+ * is preferred." */
+
+ size_t hlen = strlen(header);
+ size_t clen;
+ size_t len;
+ const char *start;
+ const char *end;
+
if(!strncasecompare(headerline, header, hlen))
- return FALSE; /* doesn't start with header */
-
- /* pass the header */
- start = &headerline[hlen];
-
+ return FALSE; /* doesn't start with header */
+
+ /* pass the header */
+ start = &headerline[hlen];
+
/* pass all whitespace */
- while(*start && ISSPACE(*start))
- start++;
-
- /* find the end of the header line */
- end = strchr(start, '\r'); /* lines end with CRLF */
- if(!end) {
- /* in case there's a non-standard compliant line here */
- end = strchr(start, '\n');
-
- if(!end)
- /* hm, there's no line ending here, use the zero byte! */
- end = strchr(start, '\0');
- }
-
- len = end-start; /* length of the content part of the input line */
- clen = strlen(content); /* length of the word to find */
-
- /* find the content string in the rest of the line */
+ while(*start && ISSPACE(*start))
+ start++;
+
+ /* find the end of the header line */
+ end = strchr(start, '\r'); /* lines end with CRLF */
+ if(!end) {
+ /* in case there's a non-standard compliant line here */
+ end = strchr(start, '\n');
+
+ if(!end)
+ /* hm, there's no line ending here, use the zero byte! */
+ end = strchr(start, '\0');
+ }
+
+ len = end-start; /* length of the content part of the input line */
+ clen = strlen(content); /* length of the word to find */
+
+ /* find the content string in the rest of the line */
for(; len >= clen; len--, start++) {
if(strncasecompare(start, content, clen))
- return TRUE; /* match! */
- }
-
- return FALSE; /* no match */
-}
-
-/*
- * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
- * the generic Curl_connect().
- */
-CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
-{
- CURLcode result;
-
- /* We default to persistent connections. We set this already in this connect
- function to make the re-use checks properly be able to check this bit. */
+ return TRUE; /* match! */
+ }
+
+ return FALSE; /* no match */
+}
+
+/*
+ * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
+ * the generic Curl_connect().
+ */
+CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
+{
+ CURLcode result;
+
+ /* We default to persistent connections. We set this already in this connect
+ function to make the re-use checks properly be able to check this bit. */
connkeep(conn, "HTTP default");
-
+
#ifndef CURL_DISABLE_PROXY
- /* the CONNECT procedure might not have been completed */
+ /* the CONNECT procedure might not have been completed */
result = Curl_proxy_connect(conn, FIRSTSOCKET);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
if(conn->bits.proxy_connect_closed)
/* this is not an error, just part of the connection negotiation */
return CURLE_OK;
@@ -1405,9 +1405,9 @@ CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
return CURLE_OK; /* wait for HTTPS proxy SSL initialization to complete */
if(Curl_connect_ongoing(conn))
- /* nothing else to do except wait right now - we're not done here. */
- return CURLE_OK;
-
+ /* nothing else to do except wait right now - we're not done here. */
+ return CURLE_OK;
+
if(conn->data->set.haproxyprotocol) {
/* add HAProxy PROXY protocol header */
result = add_haproxy_protocol_header(conn);
@@ -1417,28 +1417,28 @@ CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
#endif
if(conn->given->protocol & CURLPROTO_HTTPS) {
- /* perform SSL initialization */
- result = https_connecting(conn, done);
- if(result)
- return result;
- }
- else
- *done = TRUE;
-
- return CURLE_OK;
-}
-
-/* this returns the socket to wait for in the DO and DOING state for the multi
- interface and then we're always _sending_ a request and thus we wait for
- the single socket to become writable only */
-static int http_getsock_do(struct connectdata *conn,
+ /* perform SSL initialization */
+ result = https_connecting(conn, done);
+ if(result)
+ return result;
+ }
+ else
+ *done = TRUE;
+
+ return CURLE_OK;
+}
+
+/* this returns the socket to wait for in the DO and DOING state for the multi
+ interface and then we're always _sending_ a request and thus we wait for
+ the single socket to become writable only */
+static int http_getsock_do(struct connectdata *conn,
curl_socket_t *socks)
-{
- /* write mode */
- socks[0] = conn->sock[FIRSTSOCKET];
- return GETSOCK_WRITESOCK(0);
-}
-
+{
+ /* write mode */
+ socks[0] = conn->sock[FIRSTSOCKET];
+ return GETSOCK_WRITESOCK(0);
+}
+
#ifndef CURL_DISABLE_PROXY
static CURLcode add_haproxy_protocol_header(struct connectdata *conn)
{
@@ -1477,12 +1477,12 @@ static CURLcode add_haproxy_protocol_header(struct connectdata *conn)
}
#endif
-#ifdef USE_SSL
-static CURLcode https_connecting(struct connectdata *conn, bool *done)
-{
- CURLcode result;
- DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL));
-
+#ifdef USE_SSL
+static CURLcode https_connecting(struct connectdata *conn, bool *done)
+{
+ CURLcode result;
+ DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL));
+
#ifdef ENABLE_QUIC
if(conn->transport == TRNSPRT_QUIC) {
*done = TRUE;
@@ -1490,48 +1490,48 @@ static CURLcode https_connecting(struct connectdata *conn, bool *done)
}
#endif
- /* perform SSL initialization for this socket */
- result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
- if(result)
+ /* perform SSL initialization for this socket */
+ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
+ if(result)
connclose(conn, "Failed HTTPS connection");
- return result;
-}
-
-static int https_getsock(struct connectdata *conn,
+ return result;
+}
+
+static int https_getsock(struct connectdata *conn,
curl_socket_t *socks)
-{
+{
if(conn->handler->flags & PROTOPT_SSL)
return Curl_ssl_getsock(conn, socks);
- return GETSOCK_BLANK;
-}
-#endif /* USE_SSL */
-
-/*
+ return GETSOCK_BLANK;
+}
+#endif /* USE_SSL */
+
+/*
* Curl_http_done() gets called after a single HTTP request has been
* performed.
- */
-
-CURLcode Curl_http_done(struct connectdata *conn,
- CURLcode status, bool premature)
-{
+ */
+
+CURLcode Curl_http_done(struct connectdata *conn,
+ CURLcode status, bool premature)
+{
struct Curl_easy *data = conn->data;
struct HTTP *http = data->req.p.http;
-
+
/* Clear multipass flag. If authentication isn't done yet, then it will get
* a chance to be set back to true when we output the next auth header */
data->state.authhost.multipass = FALSE;
data->state.authproxy.multipass = FALSE;
- Curl_unencode_cleanup(conn);
-
- /* set the proper values (possibly modified on POST) */
- conn->seek_func = data->set.seek_func; /* restore */
- conn->seek_client = data->set.seek_client; /* restore */
-
+ Curl_unencode_cleanup(conn);
+
+ /* set the proper values (possibly modified on POST) */
+ conn->seek_func = data->set.seek_func; /* restore */
+ conn->seek_client = data->set.seek_client; /* restore */
+
if(!http)
- return CURLE_OK;
-
+ return CURLE_OK;
+
Curl_dyn_free(&http->send_buffer);
Curl_http2_done(data, premature);
Curl_quic_done(data, premature);
@@ -1540,36 +1540,36 @@ CURLcode Curl_http_done(struct connectdata *conn,
if(status)
return status;
-
- if(!premature && /* this check is pointless when DONE is called before the
- entire operation is complete */
- !conn->bits.retry &&
- !data->set.connect_only &&
+
+ if(!premature && /* this check is pointless when DONE is called before the
+ entire operation is complete */
+ !conn->bits.retry &&
+ !data->set.connect_only &&
(data->req.bytecount +
data->req.headerbytecount -
data->req.deductheadercount) <= 0) {
- /* If this connection isn't simply closed to be retried, AND nothing was
- read from the HTTP server (that counts), this can't be right so we
- return an error here */
- failf(data, "Empty reply from server");
- return CURLE_GOT_NOTHING;
- }
-
- return CURLE_OK;
-}
-
-/*
- * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
- * to avoid it include:
- *
- * - if the user specifically requested HTTP 1.0
- * - if the server we are connected to only supports 1.0
- * - if any server previously contacted to handle this request only supports
- * 1.0.
- */
+ /* If this connection isn't simply closed to be retried, AND nothing was
+ read from the HTTP server (that counts), this can't be right so we
+ return an error here */
+ failf(data, "Empty reply from server");
+ return CURLE_GOT_NOTHING;
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
+ * to avoid it include:
+ *
+ * - if the user specifically requested HTTP 1.0
+ * - if the server we are connected to only supports 1.0
+ * - if any server previously contacted to handle this request only supports
+ * 1.0.
+ */
static bool use_http_1_1plus(const struct Curl_easy *data,
- const struct connectdata *conn)
-{
+ const struct connectdata *conn)
+{
if((data->state.httpversion == 10) || (conn->httpversion == 10))
return FALSE;
if((data->set.httpversion == CURL_HTTP_VERSION_1_0) &&
@@ -1577,8 +1577,8 @@ static bool use_http_1_1plus(const struct Curl_easy *data,
return FALSE;
return ((data->set.httpversion == CURL_HTTP_VERSION_NONE) ||
(data->set.httpversion >= CURL_HTTP_VERSION_1_1));
-}
-
+}
+
static const char *get_http_string(const struct Curl_easy *data,
const struct connectdata *conn)
{
@@ -1599,34 +1599,34 @@ static const char *get_http_string(const struct Curl_easy *data,
return "1.0";
}
-/* check and possibly add an Expect: header */
+/* check and possibly add an Expect: header */
static CURLcode expect100(struct Curl_easy *data,
- struct connectdata *conn,
+ struct connectdata *conn,
struct dynbuf *req)
-{
- CURLcode result = CURLE_OK;
- data->state.expect100header = FALSE; /* default to false unless it is set
- to TRUE below */
+{
+ CURLcode result = CURLE_OK;
+ data->state.expect100header = FALSE; /* default to false unless it is set
+ to TRUE below */
if(!data->state.disableexpect && use_http_1_1plus(data, conn) &&
(conn->httpversion < 20)) {
/* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an
Expect: 100-continue to the headers which actually speeds up post
operations (as there is one packet coming back from the web server) */
const char *ptr = Curl_checkheaders(conn, "Expect");
- if(ptr) {
- data->state.expect100header =
- Curl_compareheader(ptr, "Expect:", "100-continue");
- }
- else {
+ if(ptr) {
+ data->state.expect100header =
+ Curl_compareheader(ptr, "Expect:", "100-continue");
+ }
+ else {
result = Curl_dyn_add(req, "Expect: 100-continue\r\n");
if(!result)
- data->state.expect100header = TRUE;
- }
- }
+ data->state.expect100header = TRUE;
+ }
+ }
+
+ return result;
+}
- return result;
-}
-
enum proxy_use {
HEADER_SERVER, /* direct to server */
HEADER_PROXY, /* regular request to proxy */
@@ -1678,26 +1678,26 @@ CURLcode Curl_http_compile_trailers(struct curl_slist *trailers,
return result;
}
-CURLcode Curl_add_custom_headers(struct connectdata *conn,
+CURLcode Curl_add_custom_headers(struct connectdata *conn,
bool is_connect,
struct dynbuf *req)
-{
- char *ptr;
+{
+ char *ptr;
struct curl_slist *h[2];
struct curl_slist *headers;
int numlists = 1; /* by default */
struct Curl_easy *data = conn->data;
int i;
-
+
#ifndef CURL_DISABLE_PROXY
enum proxy_use proxy;
-
+
if(is_connect)
proxy = HEADER_CONNECT;
else
proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy?
HEADER_PROXY:HEADER_SERVER;
-
+
switch(proxy) {
case HEADER_SERVER:
h[0] = data->set.headers;
@@ -1720,7 +1720,7 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
(void)is_connect;
h[0] = data->set.headers;
#endif
-
+
/* loop through one or two lists */
for(i = 0; i < numlists; i++) {
headers = h[i];
@@ -1757,20 +1757,20 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
}
}
ptr = optr;
- }
- }
- if(ptr) {
+ }
+ }
+ if(ptr) {
/* we require a colon for this to be a true header */
-
+
ptr++; /* pass the colon */
- while(*ptr && ISSPACE(*ptr))
- ptr++;
-
+ while(*ptr && ISSPACE(*ptr))
+ ptr++;
+
if(*ptr || semicolonp) {
/* only send this if the contents was non-blank or done special */
CURLcode result = CURLE_OK;
char *compare = semicolonp ? semicolonp : headers->data;
-
+
if(data->state.aptr.host &&
/* a Host: header was sent already, don't pass on any custom Host:
header as that will produce *two* in the same request! */
@@ -1809,42 +1809,42 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
;
else {
result = Curl_dyn_addf(req, "%s\r\n", compare);
- }
+ }
if(semicolonp)
free(semicolonp);
if(result)
return result;
- }
- }
+ }
+ }
headers = headers->next;
- }
- }
+ }
+ }
+
+ return CURLE_OK;
+}
- return CURLE_OK;
-}
-
#ifndef CURL_DISABLE_PARSEDATE
CURLcode Curl_add_timecondition(const struct connectdata *conn,
struct dynbuf *req)
-{
+{
struct Curl_easy *data = conn->data;
- const struct tm *tm;
- struct tm keeptime;
+ const struct tm *tm;
+ struct tm keeptime;
CURLcode result;
char datestr[80];
const char *condp;
-
+
if(data->set.timecondition == CURL_TIMECOND_NONE)
/* no condition was asked for */
return CURLE_OK;
- result = Curl_gmtime(data->set.timevalue, &keeptime);
- if(result) {
- failf(data, "Invalid TIMEVALUE");
- return result;
- }
- tm = &keeptime;
-
+ result = Curl_gmtime(data->set.timevalue, &keeptime);
+ if(result) {
+ failf(data, "Invalid TIMEVALUE");
+ return result;
+ }
+ tm = &keeptime;
+
switch(data->set.timecondition) {
default:
return CURLE_BAD_FUNCTION_ARGUMENT;
@@ -1865,14 +1865,14 @@ CURLcode Curl_add_timecondition(const struct connectdata *conn,
return CURLE_OK;
}
- /* The If-Modified-Since header family should have their times set in
- * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
- * represented in Greenwich Mean Time (GMT), without exception. For the
- * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
- * Time)." (see page 20 of RFC2616).
- */
-
- /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
+ /* The If-Modified-Since header family should have their times set in
+ * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
+ * represented in Greenwich Mean Time (GMT), without exception. For the
+ * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
+ * Time)." (see page 20 of RFC2616).
+ */
+
+ /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
msnprintf(datestr, sizeof(datestr),
"%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
condp,
@@ -1883,11 +1883,11 @@ CURLcode Curl_add_timecondition(const struct connectdata *conn,
tm->tm_hour,
tm->tm_min,
tm->tm_sec);
-
+
result = Curl_dyn_add(req, datestr);
-
- return result;
-}
+
+ return result;
+}
#else
/* disabled */
CURLcode Curl_add_timecondition(const struct connectdata *conn,
@@ -1898,40 +1898,40 @@ CURLcode Curl_add_timecondition(const struct connectdata *conn,
return CURLE_OK;
}
#endif
-
-/*
+
+/*
* Curl_http() gets called from the generic multi_do() function when a HTTP
- * request is to be performed. This creates and sends a properly constructed
- * HTTP request.
- */
-CURLcode Curl_http(struct connectdata *conn, bool *done)
-{
+ * request is to be performed. This creates and sends a properly constructed
+ * HTTP request.
+ */
+CURLcode Curl_http(struct connectdata *conn, bool *done)
+{
struct Curl_easy *data = conn->data;
CURLcode result = CURLE_OK;
- struct HTTP *http;
+ struct HTTP *http;
const char *path = data->state.up.path;
const char *query = data->state.up.query;
- bool paste_ftp_userpwd = FALSE;
- char ftp_typecode[sizeof("/;type=?")] = "";
- const char *host = conn->host.name;
- const char *te = ""; /* transfer-encoding */
- const char *ptr;
- const char *request;
+ bool paste_ftp_userpwd = FALSE;
+ char ftp_typecode[sizeof("/;type=?")] = "";
+ const char *host = conn->host.name;
+ const char *te = ""; /* transfer-encoding */
+ const char *ptr;
+ const char *request;
Curl_HttpReq httpreq = data->state.httpreq;
#if !defined(CURL_DISABLE_COOKIES)
- char *addcookies = NULL;
+ char *addcookies = NULL;
#endif
- curl_off_t included_body = 0;
- const char *httpstring;
+ curl_off_t included_body = 0;
+ const char *httpstring;
struct dynbuf req;
- curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */
+ curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */
char *altused = NULL;
-
- /* Always consider the DO phase done after this function call, even if there
- may be parts of the request that is not yet sent, since we can deal with
- the rest of the request in the PERFORM phase. */
- *done = TRUE;
-
+
+ /* Always consider the DO phase done after this function call, even if there
+ may be parts of the request that is not yet sent, since we can deal with
+ the rest of the request in the PERFORM phase. */
+ *done = TRUE;
+
if(conn->transport != TRNSPRT_QUIC) {
if(conn->httpversion < 20) { /* unless the connection is re-used and
already http2 */
@@ -1979,61 +1979,61 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
http = data->req.p.http;
DEBUGASSERT(http);
-
- if(!data->state.this_is_a_follow) {
+
+ if(!data->state.this_is_a_follow) {
/* Free to avoid leaking memory on multiple requests*/
free(data->state.first_host);
-
- data->state.first_host = strdup(conn->host.name);
- if(!data->state.first_host)
- return CURLE_OUT_OF_MEMORY;
+
+ data->state.first_host = strdup(conn->host.name);
+ if(!data->state.first_host)
+ return CURLE_OUT_OF_MEMORY;
data->state.first_remote_port = conn->remote_port;
- }
-
+ }
+
if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) &&
- data->set.upload) {
- httpreq = HTTPREQ_PUT;
- }
-
- /* Now set the 'request' pointer to the proper request string */
- if(data->set.str[STRING_CUSTOMREQUEST])
- request = data->set.str[STRING_CUSTOMREQUEST];
- else {
- if(data->set.opt_no_body)
- request = "HEAD";
- else {
- DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
- switch(httpreq) {
- case HTTPREQ_POST:
- case HTTPREQ_POST_FORM:
+ data->set.upload) {
+ httpreq = HTTPREQ_PUT;
+ }
+
+ /* Now set the 'request' pointer to the proper request string */
+ if(data->set.str[STRING_CUSTOMREQUEST])
+ request = data->set.str[STRING_CUSTOMREQUEST];
+ else {
+ if(data->set.opt_no_body)
+ request = "HEAD";
+ else {
+ DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
+ switch(httpreq) {
+ case HTTPREQ_POST:
+ case HTTPREQ_POST_FORM:
case HTTPREQ_POST_MIME:
- request = "POST";
- break;
- case HTTPREQ_PUT:
- request = "PUT";
- break;
- default: /* this should never happen */
- case HTTPREQ_GET:
- request = "GET";
- break;
- case HTTPREQ_HEAD:
- request = "HEAD";
- break;
- }
- }
- }
-
- /* The User-Agent string might have been allocated in url.c already, because
- it might have been used in the proxy connect, but if we have got a header
- with the user-agent string specified, we erase the previously made string
- here. */
+ request = "POST";
+ break;
+ case HTTPREQ_PUT:
+ request = "PUT";
+ break;
+ default: /* this should never happen */
+ case HTTPREQ_GET:
+ request = "GET";
+ break;
+ case HTTPREQ_HEAD:
+ request = "HEAD";
+ break;
+ }
+ }
+ }
+
+ /* The User-Agent string might have been allocated in url.c already, because
+ it might have been used in the proxy connect, but if we have got a header
+ with the user-agent string specified, we erase the previously made string
+ here. */
if(Curl_checkheaders(conn, "User-Agent")) {
free(data->state.aptr.uagent);
data->state.aptr.uagent = NULL;
- }
-
- /* setup the authentication headers */
+ }
+
+ /* setup the authentication headers */
{
char *pq = NULL;
if(query && *query) {
@@ -2046,76 +2046,76 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
if(result)
return result;
}
-
+
if(((data->state.authhost.multipass && !data->state.authhost.done)
|| (data->state.authproxy.multipass && !data->state.authproxy.done)) &&
- (httpreq != HTTPREQ_GET) &&
- (httpreq != HTTPREQ_HEAD)) {
- /* Auth is required and we are not authenticated yet. Make a PUT or POST
- with content-length zero as a "probe". */
- conn->bits.authneg = TRUE;
- }
- else
- conn->bits.authneg = FALSE;
-
+ (httpreq != HTTPREQ_GET) &&
+ (httpreq != HTTPREQ_HEAD)) {
+ /* Auth is required and we are not authenticated yet. Make a PUT or POST
+ with content-length zero as a "probe". */
+ conn->bits.authneg = TRUE;
+ }
+ else
+ conn->bits.authneg = FALSE;
+
Curl_safefree(data->state.aptr.ref);
if(data->change.referer && !Curl_checkheaders(conn, "Referer")) {
data->state.aptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
if(!data->state.aptr.ref)
- return CURLE_OUT_OF_MEMORY;
- }
- else
+ return CURLE_OUT_OF_MEMORY;
+ }
+ else
data->state.aptr.ref = NULL;
-
+
#if !defined(CURL_DISABLE_COOKIES)
if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(conn, "Cookie"))
- addcookies = data->set.str[STRING_COOKIE];
+ addcookies = data->set.str[STRING_COOKIE];
#endif
-
+
if(!Curl_checkheaders(conn, "Accept-Encoding") &&
- data->set.str[STRING_ENCODING]) {
+ data->set.str[STRING_ENCODING]) {
Curl_safefree(data->state.aptr.accept_encoding);
data->state.aptr.accept_encoding =
- aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
+ aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
if(!data->state.aptr.accept_encoding)
- return CURLE_OUT_OF_MEMORY;
- }
+ return CURLE_OUT_OF_MEMORY;
+ }
else {
Curl_safefree(data->state.aptr.accept_encoding);
data->state.aptr.accept_encoding = NULL;
}
-
-#ifdef HAVE_LIBZ
- /* we only consider transfer-encoding magic if libz support is built-in */
-
+
+#ifdef HAVE_LIBZ
+ /* we only consider transfer-encoding magic if libz support is built-in */
+
if(!Curl_checkheaders(conn, "TE") &&
data->set.http_transfer_encoding) {
- /* When we are to insert a TE: header in the request, we must also insert
- TE in a Connection: header, so we need to merge the custom provided
- Connection: header and prevent the original to get sent. Note that if
- the user has inserted his/hers own TE: header we don't do this magic
- but then assume that the user will handle it all! */
+ /* When we are to insert a TE: header in the request, we must also insert
+ TE in a Connection: header, so we need to merge the custom provided
+ Connection: header and prevent the original to get sent. Note that if
+ the user has inserted his/hers own TE: header we don't do this magic
+ but then assume that the user will handle it all! */
char *cptr = Curl_checkheaders(conn, "Connection");
-#define TE_HEADER "TE: gzip\r\n"
-
+#define TE_HEADER "TE: gzip\r\n"
+
Curl_safefree(data->state.aptr.te);
-
+
if(cptr) {
cptr = Curl_copy_header_value(cptr);
if(!cptr)
return CURLE_OUT_OF_MEMORY;
}
- /* Create the (updated) Connection: header */
+ /* Create the (updated) Connection: header */
data->state.aptr.te = aprintf("Connection: %s%sTE\r\n" TE_HEADER,
cptr ? cptr : "", (cptr && *cptr) ? ", ":"");
-
+
free(cptr);
if(!data->state.aptr.te)
- return CURLE_OUT_OF_MEMORY;
- }
-#endif
-
+ return CURLE_OUT_OF_MEMORY;
+ }
+#endif
+
switch(httpreq) {
case HTTPREQ_POST_MIME:
http->sendit = &data->set.mimepost;
@@ -2161,79 +2161,79 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
#endif
ptr = Curl_checkheaders(conn, "Transfer-Encoding");
- if(ptr) {
- /* Some kind of TE is requested, check if 'chunked' is chosen */
- data->req.upload_chunky =
- Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
- }
- else {
+ if(ptr) {
+ /* Some kind of TE is requested, check if 'chunked' is chosen */
+ data->req.upload_chunky =
+ Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
+ }
+ else {
if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
(((httpreq == HTTPREQ_POST_MIME || httpreq == HTTPREQ_POST_FORM) &&
http->postsize < 0) ||
((data->set.upload || httpreq == HTTPREQ_POST) &&
data->state.infilesize == -1))) {
- if(conn->bits.authneg)
- /* don't enable chunked during auth neg */
- ;
- else if(use_http_1_1plus(data, conn)) {
+ if(conn->bits.authneg)
+ /* don't enable chunked during auth neg */
+ ;
+ else if(use_http_1_1plus(data, conn)) {
if(conn->httpversion < 20)
/* HTTP, upload, unknown file size and not HTTP 1.0 */
data->req.upload_chunky = TRUE;
- }
- else {
- failf(data, "Chunky upload is not supported by HTTP 1.0");
- return CURLE_UPLOAD_FAILED;
- }
- }
- else {
- /* else, no chunky upload */
- data->req.upload_chunky = FALSE;
- }
-
- if(data->req.upload_chunky)
- te = "Transfer-Encoding: chunked\r\n";
- }
-
+ }
+ else {
+ failf(data, "Chunky upload is not supported by HTTP 1.0");
+ return CURLE_UPLOAD_FAILED;
+ }
+ }
+ else {
+ /* else, no chunky upload */
+ data->req.upload_chunky = FALSE;
+ }
+
+ if(data->req.upload_chunky)
+ te = "Transfer-Encoding: chunked\r\n";
+ }
+
Curl_safefree(data->state.aptr.host);
-
+
ptr = Curl_checkheaders(conn, "Host");
- if(ptr && (!data->state.this_is_a_follow ||
+ if(ptr && (!data->state.this_is_a_follow ||
strcasecompare(data->state.first_host, conn->host.name))) {
-#if !defined(CURL_DISABLE_COOKIES)
- /* If we have a given custom Host: header, we extract the host name in
- order to possibly use it for cookie reasons later on. We only allow the
- custom Host: header if this is NOT a redirect, as setting Host: in the
- redirected request is being out on thin ice. Except if the host name
- is the same as the first one! */
+#if !defined(CURL_DISABLE_COOKIES)
+ /* If we have a given custom Host: header, we extract the host name in
+ order to possibly use it for cookie reasons later on. We only allow the
+ custom Host: header if this is NOT a redirect, as setting Host: in the
+ redirected request is being out on thin ice. Except if the host name
+ is the same as the first one! */
char *cookiehost = Curl_copy_header_value(ptr);
- if(!cookiehost)
- return CURLE_OUT_OF_MEMORY;
- if(!*cookiehost)
- /* ignore empty data */
- free(cookiehost);
- else {
- /* If the host begins with '[', we start searching for the port after
- the bracket has been closed */
- if(*cookiehost == '[') {
- char *closingbracket;
- /* since the 'cookiehost' is an allocated memory area that will be
- freed later we cannot simply increment the pointer */
- memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
- closingbracket = strchr(cookiehost, ']');
- if(closingbracket)
- *closingbracket = 0;
- }
- else {
+ if(!cookiehost)
+ return CURLE_OUT_OF_MEMORY;
+ if(!*cookiehost)
+ /* ignore empty data */
+ free(cookiehost);
+ else {
+ /* If the host begins with '[', we start searching for the port after
+ the bracket has been closed */
+ if(*cookiehost == '[') {
+ char *closingbracket;
+ /* since the 'cookiehost' is an allocated memory area that will be
+ freed later we cannot simply increment the pointer */
+ memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
+ closingbracket = strchr(cookiehost, ']');
+ if(closingbracket)
+ *closingbracket = 0;
+ }
+ else {
int startsearch = 0;
- char *colon = strchr(cookiehost + startsearch, ':');
- if(colon)
- *colon = 0; /* The host must not include an embedded port number */
- }
+ char *colon = strchr(cookiehost + startsearch, ':');
+ if(colon)
+ *colon = 0; /* The host must not include an embedded port number */
+ }
Curl_safefree(data->state.aptr.cookiehost);
data->state.aptr.cookiehost = cookiehost;
- }
-#endif
-
+ }
+#endif
+
if(strcmp("Host:", ptr)) {
data->state.aptr.host = aprintf("Host:%s\r\n", &ptr[5]);
if(!data->state.aptr.host)
@@ -2242,54 +2242,54 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
else
/* when clearing the header */
data->state.aptr.host = NULL;
- }
- else {
- /* When building Host: headers, we must put the host name within
- [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
-
- if(((conn->given->protocol&CURLPROTO_HTTPS) &&
- (conn->remote_port == PORT_HTTPS)) ||
- ((conn->given->protocol&CURLPROTO_HTTP) &&
- (conn->remote_port == PORT_HTTP)) )
- /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include
- the port number in the host string */
+ }
+ else {
+ /* When building Host: headers, we must put the host name within
+ [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
+
+ if(((conn->given->protocol&CURLPROTO_HTTPS) &&
+ (conn->remote_port == PORT_HTTPS)) ||
+ ((conn->given->protocol&CURLPROTO_HTTP) &&
+ (conn->remote_port == PORT_HTTP)) )
+ /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include
+ the port number in the host string */
data->state.aptr.host = aprintf("Host: %s%s%s\r\n",
- conn->bits.ipv6_ip?"[":"",
- host,
- conn->bits.ipv6_ip?"]":"");
- else
+ conn->bits.ipv6_ip?"[":"",
+ host,
+ conn->bits.ipv6_ip?"]":"");
+ else
data->state.aptr.host = aprintf("Host: %s%s%s:%d\r\n",
- conn->bits.ipv6_ip?"[":"",
- host,
- conn->bits.ipv6_ip?"]":"",
- conn->remote_port);
-
+ conn->bits.ipv6_ip?"[":"",
+ host,
+ conn->bits.ipv6_ip?"]":"",
+ conn->remote_port);
+
if(!data->state.aptr.host)
- /* without Host: we can't make a nice request */
- return CURLE_OUT_OF_MEMORY;
- }
-
-#ifndef CURL_DISABLE_PROXY
+ /* without Host: we can't make a nice request */
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+#ifndef CURL_DISABLE_PROXY
if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
- /* Using a proxy but does not tunnel through it */
-
- /* The path sent to the proxy is in fact the entire URL. But if the remote
- host is a IDN-name, we must make sure that the request we produce only
- uses the encoded host name! */
-
+ /* Using a proxy but does not tunnel through it */
+
+ /* The path sent to the proxy is in fact the entire URL. But if the remote
+ host is a IDN-name, we must make sure that the request we produce only
+ uses the encoded host name! */
+
/* and no fragment part */
CURLUcode uc;
CURLU *h = curl_url_dup(data->state.uh);
if(!h)
return CURLE_OUT_OF_MEMORY;
-
+
if(conn->host.dispname != conn->host.name) {
uc = curl_url_set(h, CURLUPART_HOST, conn->host.name, 0);
if(uc) {
curl_url_cleanup(h);
return CURLE_OUT_OF_MEMORY;
- }
- }
+ }
+ }
uc = curl_url_set(h, CURLUPART_FRAGMENT, NULL, 0);
if(uc) {
curl_url_cleanup(h);
@@ -2321,88 +2321,88 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
curl_url_cleanup(h);
if(strcasecompare("ftp", data->state.up.scheme)) {
- if(data->set.proxy_transfer_mode) {
- /* when doing ftp, append ;type=<a|i> if not present */
+ if(data->set.proxy_transfer_mode) {
+ /* when doing ftp, append ;type=<a|i> if not present */
char *type = strstr(path, ";type=");
- if(type && type[6] && type[7] == 0) {
+ if(type && type[6] && type[7] == 0) {
switch(Curl_raw_toupper(type[6])) {
- case 'A':
- case 'D':
- case 'I':
- break;
- default:
- type = NULL;
- }
- }
- if(!type) {
- char *p = ftp_typecode;
- /* avoid sending invalid URLs like ftp://example.com;type=i if the
- * user specified ftp://example.com without the slash */
+ case 'A':
+ case 'D':
+ case 'I':
+ break;
+ default:
+ type = NULL;
+ }
+ }
+ if(!type) {
+ char *p = ftp_typecode;
+ /* avoid sending invalid URLs like ftp://example.com;type=i if the
+ * user specified ftp://example.com without the slash */
if(!*data->state.up.path && path[strlen(path) - 1] != '/') {
- *p++ = '/';
- }
+ *p++ = '/';
+ }
msnprintf(p, sizeof(ftp_typecode) - 1, ";type=%c",
data->set.prefer_ascii ? 'a' : 'i');
- }
- }
+ }
+ }
if(conn->bits.user_passwd)
- paste_ftp_userpwd = TRUE;
- }
- }
-#endif /* CURL_DISABLE_PROXY */
-
+ paste_ftp_userpwd = TRUE;
+ }
+ }
+#endif /* CURL_DISABLE_PROXY */
+
http->p_accept = Curl_checkheaders(conn, "Accept")?NULL:"Accept: */*\r\n";
-
+
if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) &&
- data->state.resume_from) {
- /**********************************************************************
- * Resuming upload in HTTP means that we PUT or POST and that we have
- * got a resume_from value set. The resume value has already created
- * a Range: header that will be passed along. We need to "fast forward"
- * the file the given number of bytes and decrease the assume upload
- * file size before we continue this venture in the dark lands of HTTP.
+ data->state.resume_from) {
+ /**********************************************************************
+ * Resuming upload in HTTP means that we PUT or POST and that we have
+ * got a resume_from value set. The resume value has already created
+ * a Range: header that will be passed along. We need to "fast forward"
+ * the file the given number of bytes and decrease the assume upload
+ * file size before we continue this venture in the dark lands of HTTP.
* Resuming mime/form posting at an offset > 0 has no sense and is ignored.
- *********************************************************************/
-
+ *********************************************************************/
+
if(data->state.resume_from < 0) {
- /*
- * This is meant to get the size of the present remote-file by itself.
- * We don't support this now. Bail out!
- */
- data->state.resume_from = 0;
- }
-
- if(data->state.resume_from && !data->state.this_is_a_follow) {
- /* do we still game? */
-
- /* Now, let's read off the proper amount of bytes from the
- input. */
+ /*
+ * This is meant to get the size of the present remote-file by itself.
+ * We don't support this now. Bail out!
+ */
+ data->state.resume_from = 0;
+ }
+
+ if(data->state.resume_from && !data->state.this_is_a_follow) {
+ /* do we still game? */
+
+ /* Now, let's read off the proper amount of bytes from the
+ input. */
int seekerr = CURL_SEEKFUNC_CANTSEEK;
- if(conn->seek_func) {
+ if(conn->seek_func) {
Curl_set_in_callback(data, true);
- seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
- SEEK_SET);
+ seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
+ SEEK_SET);
Curl_set_in_callback(data, false);
- }
-
- if(seekerr != CURL_SEEKFUNC_OK) {
+ }
+
+ if(seekerr != CURL_SEEKFUNC_OK) {
curl_off_t passed = 0;
- if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
- failf(data, "Could not seek stream");
- return CURLE_READ_ERROR;
- }
- /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
+ if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
+ failf(data, "Could not seek stream");
+ return CURLE_READ_ERROR;
+ }
+ /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
do {
size_t readthisamountnow =
(data->state.resume_from - passed > data->set.buffer_size) ?
(size_t)data->set.buffer_size :
curlx_sotouz(data->state.resume_from - passed);
-
+
size_t actuallyread =
data->state.fread_func(data->state.buffer, 1, readthisamountnow,
data->state.in);
-
+
passed += actuallyread;
if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
/* this checks for greater-than only to make sure that the
@@ -2412,89 +2412,89 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
return CURLE_READ_ERROR;
}
} while(passed < data->state.resume_from);
- }
-
- /* now, decrease the size of the read */
+ }
+
+ /* now, decrease the size of the read */
if(data->state.infilesize>0) {
data->state.infilesize -= data->state.resume_from;
-
+
if(data->state.infilesize <= 0) {
- failf(data, "File already completely uploaded");
- return CURLE_PARTIAL_FILE;
- }
- }
- /* we've passed, proceed as normal */
- }
- }
- if(data->state.use_range) {
- /*
- * A range is selected. We use different headers whether we're downloading
- * or uploading and we always let customized headers override our internal
- * ones if any such are specified.
- */
- if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
+ failf(data, "File already completely uploaded");
+ return CURLE_PARTIAL_FILE;
+ }
+ }
+ /* we've passed, proceed as normal */
+ }
+ }
+ if(data->state.use_range) {
+ /*
+ * A range is selected. We use different headers whether we're downloading
+ * or uploading and we always let customized headers override our internal
+ * ones if any such are specified.
+ */
+ if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
!Curl_checkheaders(conn, "Range")) {
- /* if a line like this was already allocated, free the previous one */
+ /* if a line like this was already allocated, free the previous one */
free(data->state.aptr.rangeline);
data->state.aptr.rangeline = aprintf("Range: bytes=%s\r\n",
- data->state.range);
- }
+ data->state.range);
+ }
else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) &&
!Curl_checkheaders(conn, "Content-Range")) {
-
- /* if a line like this was already allocated, free the previous one */
+
+ /* if a line like this was already allocated, free the previous one */
free(data->state.aptr.rangeline);
-
- if(data->set.set_resume_from < 0) {
- /* Upload resume was asked for, but we don't know the size of the
- remote part so we tell the server (and act accordingly) that we
- upload the whole file (again) */
+
+ if(data->set.set_resume_from < 0) {
+ /* Upload resume was asked for, but we don't know the size of the
+ remote part so we tell the server (and act accordingly) that we
+ upload the whole file (again) */
data->state.aptr.rangeline =
aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T
"/%" CURL_FORMAT_CURL_OFF_T "\r\n",
data->state.infilesize - 1, data->state.infilesize);
-
- }
- else if(data->state.resume_from) {
- /* This is because "resume" was selected */
+
+ }
+ else if(data->state.resume_from) {
+ /* This is because "resume" was selected */
curl_off_t total_expected_size =
data->state.resume_from + data->state.infilesize;
data->state.aptr.rangeline =
aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T
"/%" CURL_FORMAT_CURL_OFF_T "\r\n",
- data->state.range, total_expected_size-1,
- total_expected_size);
- }
- else {
- /* Range was selected and then we just pass the incoming range and
- append total size */
+ data->state.range, total_expected_size-1,
+ total_expected_size);
+ }
+ else {
+ /* Range was selected and then we just pass the incoming range and
+ append total size */
data->state.aptr.rangeline =
aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n",
data->state.range, data->state.infilesize);
- }
+ }
if(!data->state.aptr.rangeline)
- return CURLE_OUT_OF_MEMORY;
- }
- }
-
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
+
httpstring = get_http_string(data, conn);
-
- /* initialize a dynamic send-buffer */
+
+ /* initialize a dynamic send-buffer */
Curl_dyn_init(&req, DYN_HTTP_REQUEST);
-
- /* add the main request stuff */
- /* GET/HEAD/POST/PUT */
+
+ /* add the main request stuff */
+ /* GET/HEAD/POST/PUT */
result = Curl_dyn_addf(&req, "%s ", request);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
if(data->set.str[STRING_TARGET]) {
path = data->set.str[STRING_TARGET];
query = NULL;
}
#ifndef CURL_DISABLE_PROXY
- /* url */
+ /* url */
if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
char *url = data->set.str[STRING_TEMP_URL];
result = Curl_dyn_add(&req, url);
@@ -2512,9 +2512,9 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
if(query)
result = Curl_dyn_addf(&req, "?%s", query);
}
- if(result)
- return result;
-
+ if(result)
+ return result;
+
#ifndef CURL_DISABLE_ALTSVC
if(conn->bits.altused && !Curl_checkheaders(conn, "Alt-Used")) {
altused = aprintf("Alt-Used: %s:%d\r\n",
@@ -2525,7 +2525,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
}
#endif
- result =
+ result =
Curl_dyn_addf(&req,
"%s" /* ftp typecode (;type=x) */
" HTTP/%s\r\n" /* HTTP version */
@@ -2541,7 +2541,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
"%s" /* Proxy-Connection */
"%s" /* transfer-encoding */
"%s",/* Alt-Used */
-
+
ftp_typecode,
httpstring,
(data->state.aptr.host?data->state.aptr.host:""),
@@ -2572,95 +2572,95 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
#endif
te,
altused ? altused : ""
- );
-
+ );
+
/* clear userpwd and proxyuserpwd to avoid re-using old credentials
* from re-used connections */
Curl_safefree(data->state.aptr.userpwd);
Curl_safefree(data->state.aptr.proxyuserpwd);
free(altused);
-
- if(result)
- return result;
-
- if(!(conn->handler->flags&PROTOPT_SSL) &&
+
+ if(result)
+ return result;
+
+ if(!(conn->handler->flags&PROTOPT_SSL) &&
conn->httpversion != 20 &&
(data->set.httpversion == CURL_HTTP_VERSION_2)) {
/* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done
- over SSL */
+ over SSL */
result = Curl_http2_request_upgrade(&req, conn);
- if(result)
- return result;
- }
-
-#if !defined(CURL_DISABLE_COOKIES)
- if(data->cookies || addcookies) {
+ if(result)
+ return result;
+ }
+
+#if !defined(CURL_DISABLE_COOKIES)
+ if(data->cookies || addcookies) {
struct Cookie *co = NULL; /* no cookies from start */
int count = 0;
-
+
if(data->cookies && data->state.cookie_engine) {
- Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
- co = Curl_cookie_getlist(data->cookies,
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+ co = Curl_cookie_getlist(data->cookies,
data->state.aptr.cookiehost?
data->state.aptr.cookiehost:host,
data->state.up.path,
- (conn->handler->protocol&CURLPROTO_HTTPS)?
- TRUE:FALSE);
- Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
- }
- if(co) {
+ (conn->handler->protocol&CURLPROTO_HTTPS)?
+ TRUE:FALSE);
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ }
+ if(co) {
struct Cookie *store = co;
- /* now loop through all cookies that matched */
- while(co) {
- if(co->value) {
- if(0 == count) {
+ /* now loop through all cookies that matched */
+ while(co) {
+ if(co->value) {
+ if(0 == count) {
result = Curl_dyn_add(&req, "Cookie: ");
- if(result)
- break;
- }
+ if(result)
+ break;
+ }
result = Curl_dyn_addf(&req, "%s%s=%s", count?"; ":"",
co->name, co->value);
- if(result)
- break;
- count++;
- }
- co = co->next; /* next cookie please */
- }
+ if(result)
+ break;
+ count++;
+ }
+ co = co->next; /* next cookie please */
+ }
Curl_cookie_freelist(store);
- }
+ }
if(addcookies && !result) {
- if(!count)
+ if(!count)
result = Curl_dyn_add(&req, "Cookie: ");
if(!result) {
result = Curl_dyn_addf(&req, "%s%s", count?"; ":"", addcookies);
- count++;
- }
- }
+ count++;
+ }
+ }
if(count && !result)
result = Curl_dyn_add(&req, "\r\n");
-
- if(result)
- return result;
- }
-#endif
-
+
+ if(result)
+ return result;
+ }
+#endif
+
result = Curl_add_timecondition(conn, &req);
if(result)
return result;
-
+
result = Curl_add_custom_headers(conn, FALSE, &req);
- if(result)
- return result;
-
- http->postdata = NULL; /* nothing to post at this point */
+ if(result)
+ return result;
+
+ http->postdata = NULL; /* nothing to post at this point */
Curl_pgrsSetUploadSize(data, -1); /* upload size is unknown atm */
-
- /* If 'authdone' is FALSE, we must not set the write socket index to the
- Curl_transfer() call below, as we're not ready to actually upload any
- data yet. */
-
- switch(httpreq) {
-
+
+ /* If 'authdone' is FALSE, we must not set the write socket index to the
+ Curl_transfer() call below, as we're not ready to actually upload any
+ data yet. */
+
+ switch(httpreq) {
+
case HTTPREQ_PUT: /* Let's PUT the data to the server! */
if(conn->bits.authneg)
@@ -2704,27 +2704,27 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
return result;
break;
- case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_FORM:
case HTTPREQ_POST_MIME:
/* This is form posting using mime data. */
if(conn->bits.authneg) {
- /* nothing to post! */
+ /* nothing to post! */
result = Curl_dyn_add(&req, "Content-Length: 0\r\n\r\n");
- if(result)
- return result;
-
+ if(result)
+ return result;
+
result = Curl_buffer_send(&req, conn, &data->info.request_size, 0,
FIRSTSOCKET);
- if(result)
- failf(data, "Failed sending POST request");
- else
- /* setup variables for the upcoming transfer */
+ if(result)
+ failf(data, "Failed sending POST request");
+ else
+ /* setup variables for the upcoming transfer */
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1);
- break;
- }
-
+ break;
+ }
+
data->state.infilesize = postsize = http->postsize;
-
+
/* We only set Content-Length and allow a custom Content-Length if
we don't upload data chunked, as RFC2616 forbids us to set both
kinds of headers (Transfer-Encoding: chunked and Content-Length) */
@@ -2735,23 +2735,23 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
result = Curl_dyn_addf(&req,
"Content-Length: %" CURL_FORMAT_CURL_OFF_T
"\r\n", postsize);
- if(result)
- return result;
- }
-
+ if(result)
+ return result;
+ }
+
#ifndef CURL_DISABLE_MIME
/* Output mime-generated headers. */
- {
+ {
struct curl_slist *hdr;
-
+
for(hdr = http->sendit->curlheaders; hdr; hdr = hdr->next) {
result = Curl_dyn_addf(&req, "%s\r\n", hdr->data);
if(result)
return result;
- }
- }
+ }
+ }
#endif
-
+
/* For really small posts we don't use Expect: headers at all, and for
the somewhat bigger ones we allow the app to disable it. Just make
sure that the expect100header is always set to the preferred value
@@ -2760,51 +2760,51 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
if(ptr) {
data->state.expect100header =
Curl_compareheader(ptr, "Expect:", "100-continue");
- }
+ }
else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) {
result = expect100(data, conn, &req);
- if(result)
- return result;
- }
+ if(result)
+ return result;
+ }
else
data->state.expect100header = FALSE;
-
+
/* make the request end in a true CRLF */
result = Curl_dyn_add(&req, "\r\n");
- if(result)
- return result;
-
- /* set the upload size to the progress meter */
- Curl_pgrsSetUploadSize(data, postsize);
-
+ if(result)
+ return result;
+
+ /* set the upload size to the progress meter */
+ Curl_pgrsSetUploadSize(data, postsize);
+
/* Read from mime structure. */
data->state.fread_func = (curl_read_callback) Curl_mime_read;
data->state.in = (void *) http->sendit;
http->sending = HTTPSEND_BODY;
- /* this sends the buffer and frees all the buffer resources */
+ /* this sends the buffer and frees all the buffer resources */
result = Curl_buffer_send(&req, conn, &data->info.request_size, 0,
FIRSTSOCKET);
- if(result)
+ if(result)
failf(data, "Failed sending POST request");
- else
- /* prepare for transfer */
+ else
+ /* prepare for transfer */
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE,
postsize?FIRSTSOCKET:-1);
- if(result)
- return result;
-
- break;
-
- case HTTPREQ_POST:
- /* this is the simple POST, using x-www-form-urlencoded style */
-
- if(conn->bits.authneg)
- postsize = 0;
+ if(result)
+ return result;
+
+ break;
+
+ case HTTPREQ_POST:
+ /* this is the simple POST, using x-www-form-urlencoded style */
+
+ if(conn->bits.authneg)
+ postsize = 0;
else
/* the size of the post body */
postsize = data->state.infilesize;
-
+
/* We only set Content-Length and allow a custom Content-Length if
we don't upload data chunked, as RFC2616 forbids us to set both
kinds of headers (Transfer-Encoding: chunked and Content-Length) */
@@ -2816,62 +2816,62 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
"\r\n", postsize);
if(result)
return result;
- }
-
+ }
+
if(!Curl_checkheaders(conn, "Content-Type")) {
result = Curl_dyn_add(&req, "Content-Type: application/"
"x-www-form-urlencoded\r\n");
- if(result)
- return result;
- }
-
- /* For really small posts we don't use Expect: headers at all, and for
- the somewhat bigger ones we allow the app to disable it. Just make
- sure that the expect100header is always set to the preferred value
- here. */
+ if(result)
+ return result;
+ }
+
+ /* For really small posts we don't use Expect: headers at all, and for
+ the somewhat bigger ones we allow the app to disable it. Just make
+ sure that the expect100header is always set to the preferred value
+ here. */
ptr = Curl_checkheaders(conn, "Expect");
- if(ptr) {
- data->state.expect100header =
- Curl_compareheader(ptr, "Expect:", "100-continue");
- }
+ if(ptr) {
+ data->state.expect100header =
+ Curl_compareheader(ptr, "Expect:", "100-continue");
+ }
else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) {
result = expect100(data, conn, &req);
- if(result)
- return result;
- }
- else
- data->state.expect100header = FALSE;
-
- if(data->set.postfields) {
-
+ if(result)
+ return result;
+ }
+ else
+ data->state.expect100header = FALSE;
+
+ if(data->set.postfields) {
+
/* In HTTP2, we send request body in DATA frame regardless of
its size. */
if(conn->httpversion != 20 &&
!data->state.expect100header &&
(postsize < MAX_INITIAL_POST_SIZE)) {
- /* if we don't use expect: 100 AND
- postsize is less than MAX_INITIAL_POST_SIZE
-
- then append the post data to the HTTP request header. This limit
- is no magic limit but only set to prevent really huge POSTs to
- get the data duplicated with malloc() and family. */
-
+ /* if we don't use expect: 100 AND
+ postsize is less than MAX_INITIAL_POST_SIZE
+
+ then append the post data to the HTTP request header. This limit
+ is no magic limit but only set to prevent really huge POSTs to
+ get the data duplicated with malloc() and family. */
+
/* end of headers! */
result = Curl_dyn_add(&req, "\r\n");
- if(result)
- return result;
-
- if(!data->req.upload_chunky) {
- /* We're not sending it 'chunked', append it to the request
- already now to reduce the number if send() calls */
+ if(result)
+ return result;
+
+ if(!data->req.upload_chunky) {
+ /* We're not sending it 'chunked', append it to the request
+ already now to reduce the number if send() calls */
result = Curl_dyn_addn(&req, data->set.postfields,
(size_t)postsize);
- included_body = postsize;
- }
- else {
- if(postsize) {
+ included_body = postsize;
+ }
+ else {
+ if(postsize) {
char chunk[16];
- /* Append the POST data chunky-style */
+ /* Append the POST data chunky-style */
msnprintf(chunk, sizeof(chunk), "%x\r\n", (int)postsize);
result = Curl_dyn_add(&req, chunk);
if(!result) {
@@ -2881,125 +2881,125 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
if(!result)
result = Curl_dyn_add(&req, "\r\n");
included_body += 2;
- }
- }
+ }
+ }
if(!result) {
result = Curl_dyn_add(&req, "\x30\x0d\x0a\x0d\x0a");
/* 0 CR LF CR LF */
included_body += 5;
}
- }
- if(result)
- return result;
- /* Make sure the progress information is accurate */
- Curl_pgrsSetUploadSize(data, postsize);
- }
- else {
- /* A huge POST coming up, do data separate from the request */
- http->postsize = postsize;
- http->postdata = data->set.postfields;
-
- http->sending = HTTPSEND_BODY;
-
+ }
+ if(result)
+ return result;
+ /* Make sure the progress information is accurate */
+ Curl_pgrsSetUploadSize(data, postsize);
+ }
+ else {
+ /* A huge POST coming up, do data separate from the request */
+ http->postsize = postsize;
+ http->postdata = data->set.postfields;
+
+ http->sending = HTTPSEND_BODY;
+
data->state.fread_func = (curl_read_callback)readmoredata;
data->state.in = (void *)conn;
-
- /* set the upload size to the progress meter */
- Curl_pgrsSetUploadSize(data, http->postsize);
-
+
+ /* set the upload size to the progress meter */
+ Curl_pgrsSetUploadSize(data, http->postsize);
+
/* end of headers! */
result = Curl_dyn_add(&req, "\r\n");
- if(result)
- return result;
- }
- }
- else {
+ if(result)
+ return result;
+ }
+ }
+ else {
/* end of headers! */
result = Curl_dyn_add(&req, "\r\n");
- if(result)
- return result;
-
- if(data->req.upload_chunky && conn->bits.authneg) {
- /* Chunky upload is selected and we're negotiating auth still, send
- end-of-data only */
+ if(result)
+ return result;
+
+ if(data->req.upload_chunky && conn->bits.authneg) {
+ /* Chunky upload is selected and we're negotiating auth still, send
+ end-of-data only */
result = Curl_dyn_add(&req, (char *)"\x30\x0d\x0a\x0d\x0a");
- /* 0 CR LF CR LF */
- if(result)
- return result;
- }
-
+ /* 0 CR LF CR LF */
+ if(result)
+ return result;
+ }
+
else if(data->state.infilesize) {
- /* set the upload size to the progress meter */
- Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
-
- /* set the pointer to mark that we will send the post body using the
- read callback, but only if we're not in authenticate
- negotiation */
- if(!conn->bits.authneg) {
- http->postdata = (char *)&http->postdata;
- http->postsize = postsize;
- }
- }
- }
- /* issue the request */
+ /* set the upload size to the progress meter */
+ Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
+
+ /* set the pointer to mark that we will send the post body using the
+ read callback, but only if we're not in authenticate
+ negotiation */
+ if(!conn->bits.authneg) {
+ http->postdata = (char *)&http->postdata;
+ http->postsize = postsize;
+ }
+ }
+ }
+ /* issue the request */
result = Curl_buffer_send(&req, conn, &data->info.request_size,
(size_t)included_body, FIRSTSOCKET);
-
- if(result)
- failf(data, "Failed sending HTTP POST request");
- else
+
+ if(result)
+ failf(data, "Failed sending HTTP POST request");
+ else
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE,
http->postdata?FIRSTSOCKET:-1);
- break;
-
- default:
+ break;
+
+ default:
result = Curl_dyn_add(&req, "\r\n");
- if(result)
- return result;
-
- /* issue the request */
+ if(result)
+ return result;
+
+ /* issue the request */
result = Curl_buffer_send(&req, conn, &data->info.request_size, 0,
FIRSTSOCKET);
-
- if(result)
- failf(data, "Failed sending HTTP request");
- else
- /* HTTP GET/HEAD download: */
+
+ if(result)
+ failf(data, "Failed sending HTTP request");
+ else
+ /* HTTP GET/HEAD download: */
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1);
- }
- if(result)
- return result;
+ }
+ if(result)
+ return result;
if(!postsize && (http->sending != HTTPSEND_REQUEST))
data->req.upload_done = TRUE;
-
+
if(data->req.writebytecount) {
- /* if a request-body has been sent off, we make sure this progress is noted
- properly */
+ /* if a request-body has been sent off, we make sure this progress is noted
+ properly */
Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
- if(Curl_pgrsUpdate(conn))
- result = CURLE_ABORTED_BY_CALLBACK;
-
+ if(Curl_pgrsUpdate(conn))
+ result = CURLE_ABORTED_BY_CALLBACK;
+
if(data->req.writebytecount >= postsize) {
- /* already sent the entire request body, mark the "upload" as
- complete */
+ /* already sent the entire request body, mark the "upload" as
+ complete */
infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T
" out of %" CURL_FORMAT_CURL_OFF_T " bytes\n",
data->req.writebytecount, postsize);
- data->req.upload_done = TRUE;
- data->req.keepon &= ~KEEP_SEND; /* we're done writing */
- data->req.exp100 = EXP100_SEND_DATA; /* already sent */
+ data->req.upload_done = TRUE;
+ data->req.keepon &= ~KEEP_SEND; /* we're done writing */
+ data->req.exp100 = EXP100_SEND_DATA; /* already sent */
Curl_expire_done(data, EXPIRE_100_TIMEOUT);
- }
- }
-
+ }
+ }
+
if((conn->httpversion == 20) && data->req.upload_chunky)
/* upload_chunky was set above to set up the request in a chunky fashion,
but is disabled here again to avoid that the chunked encoded version is
actually used when sending the request body over h2 */
data->req.upload_chunky = FALSE;
- return result;
-}
-
+ return result;
+}
+
typedef enum {
STATUS_UNKNOWN, /* not enough data to tell yet */
STATUS_DONE, /* a status line was read */
@@ -3014,168 +3014,168 @@ static bool checkprefixmax(const char *prefix, const char *buffer, size_t len)
return curl_strnequal(prefix, buffer, ch);
}
-/*
- * checkhttpprefix()
- *
- * Returns TRUE if member of the list matches prefix of string
- */
+/*
+ * checkhttpprefix()
+ *
+ * Returns TRUE if member of the list matches prefix of string
+ */
static statusline
checkhttpprefix(struct Curl_easy *data,
const char *s, size_t len)
-{
- struct curl_slist *head = data->set.http200aliases;
+{
+ struct curl_slist *head = data->set.http200aliases;
statusline rc = STATUS_BAD;
statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN;
-#ifdef CURL_DOES_CONVERSIONS
- /* convert from the network encoding using a scratch area */
- char *scratch = strdup(s);
- if(NULL == scratch) {
+#ifdef CURL_DOES_CONVERSIONS
+ /* convert from the network encoding using a scratch area */
+ char *scratch = strdup(s);
+ if(NULL == scratch) {
failf(data, "Failed to allocate memory for conversion!");
- return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
- }
+ return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
+ }
if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
- /* Curl_convert_from_network calls failf if unsuccessful */
- free(scratch);
- return FALSE; /* can't return CURLE_foobar so return FALSE */
- }
- s = scratch;
-#endif /* CURL_DOES_CONVERSIONS */
-
- while(head) {
+ /* Curl_convert_from_network calls failf if unsuccessful */
+ free(scratch);
+ return FALSE; /* can't return CURLE_foobar so return FALSE */
+ }
+ s = scratch;
+#endif /* CURL_DOES_CONVERSIONS */
+
+ while(head) {
if(checkprefixmax(head->data, s, len)) {
rc = onmatch;
- break;
- }
- head = head->next;
- }
-
+ break;
+ }
+ head = head->next;
+ }
+
if((rc != STATUS_DONE) && (checkprefixmax("HTTP/", s, len)))
rc = onmatch;
-
-#ifdef CURL_DOES_CONVERSIONS
- free(scratch);
-#endif /* CURL_DOES_CONVERSIONS */
- return rc;
-}
-
-#ifndef CURL_DISABLE_RTSP
+
+#ifdef CURL_DOES_CONVERSIONS
+ free(scratch);
+#endif /* CURL_DOES_CONVERSIONS */
+ return rc;
+}
+
+#ifndef CURL_DISABLE_RTSP
static statusline
checkrtspprefix(struct Curl_easy *data,
const char *s, size_t len)
-{
+{
statusline result = STATUS_BAD;
statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN;
-
-#ifdef CURL_DOES_CONVERSIONS
- /* convert from the network encoding using a scratch area */
- char *scratch = strdup(s);
- if(NULL == scratch) {
+
+#ifdef CURL_DOES_CONVERSIONS
+ /* convert from the network encoding using a scratch area */
+ char *scratch = strdup(s);
+ if(NULL == scratch) {
failf(data, "Failed to allocate memory for conversion!");
- return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
- }
+ return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
+ }
if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
- /* Curl_convert_from_network calls failf if unsuccessful */
+ /* Curl_convert_from_network calls failf if unsuccessful */
result = FALSE; /* can't return CURLE_foobar so return FALSE */
- }
+ }
else if(checkprefixmax("RTSP/", scratch, len))
result = onmatch;
free(scratch);
-#else
- (void)data; /* unused */
+#else
+ (void)data; /* unused */
if(checkprefixmax("RTSP/", s, len))
result = onmatch;
-#endif /* CURL_DOES_CONVERSIONS */
+#endif /* CURL_DOES_CONVERSIONS */
return result;
-}
-#endif /* CURL_DISABLE_RTSP */
-
+}
+#endif /* CURL_DISABLE_RTSP */
+
static statusline
checkprotoprefix(struct Curl_easy *data, struct connectdata *conn,
const char *s, size_t len)
-{
-#ifndef CURL_DISABLE_RTSP
- if(conn->handler->protocol & CURLPROTO_RTSP)
+{
+#ifndef CURL_DISABLE_RTSP
+ if(conn->handler->protocol & CURLPROTO_RTSP)
return checkrtspprefix(data, s, len);
-#else
- (void)conn;
-#endif /* CURL_DISABLE_RTSP */
-
+#else
+ (void)conn;
+#endif /* CURL_DISABLE_RTSP */
+
return checkhttpprefix(data, s, len);
-}
-
+}
+
static void print_http_error(struct Curl_easy *data)
-{
- struct SingleRequest *k = &data->req;
+{
+ struct SingleRequest *k = &data->req;
char *beg = Curl_dyn_ptr(&data->state.headerb);
-
- /* make sure that data->req.p points to the HTTP status line */
- if(!strncmp(beg, "HTTP", 4)) {
-
- /* skip to HTTP status code */
- beg = strchr(beg, ' ');
- if(beg && *++beg) {
-
- /* find trailing CR */
- char end_char = '\r';
- char *end = strchr(beg, end_char);
- if(!end) {
- /* try to find LF (workaround for non-compliant HTTP servers) */
- end_char = '\n';
- end = strchr(beg, end_char);
- }
-
- if(end) {
- /* temporarily replace CR or LF by NUL and print the error message */
- *end = '\0';
- failf(data, "The requested URL returned error: %s", beg);
-
- /* restore the previously replaced CR or LF */
- *end = end_char;
- return;
- }
- }
- }
-
- /* fall-back to printing the HTTP status code only */
- failf(data, "The requested URL returned error: %d", k->httpcode);
-}
-
-/*
- * Read any HTTP header lines from the server and pass them to the client app.
- */
+
+ /* make sure that data->req.p points to the HTTP status line */
+ if(!strncmp(beg, "HTTP", 4)) {
+
+ /* skip to HTTP status code */
+ beg = strchr(beg, ' ');
+ if(beg && *++beg) {
+
+ /* find trailing CR */
+ char end_char = '\r';
+ char *end = strchr(beg, end_char);
+ if(!end) {
+ /* try to find LF (workaround for non-compliant HTTP servers) */
+ end_char = '\n';
+ end = strchr(beg, end_char);
+ }
+
+ if(end) {
+ /* temporarily replace CR or LF by NUL and print the error message */
+ *end = '\0';
+ failf(data, "The requested URL returned error: %s", beg);
+
+ /* restore the previously replaced CR or LF */
+ *end = end_char;
+ return;
+ }
+ }
+ }
+
+ /* fall-back to printing the HTTP status code only */
+ failf(data, "The requested URL returned error: %d", k->httpcode);
+}
+
+/*
+ * Read any HTTP header lines from the server and pass them to the client app.
+ */
CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
struct connectdata *conn,
ssize_t *nread,
bool *stop_reading)
-{
- CURLcode result;
- struct SingleRequest *k = &data->req;
+{
+ CURLcode result;
+ struct SingleRequest *k = &data->req;
ssize_t onread = *nread;
char *ostr = k->str;
char *headp;
char *str_start;
char *end_ptr;
-
- /* header line within buffer loop */
- do {
- size_t rest_length;
- size_t full_length;
- int writetype;
-
- /* str_start is start of line within buf */
+
+ /* header line within buffer loop */
+ do {
+ size_t rest_length;
+ size_t full_length;
+ int writetype;
+
+ /* str_start is start of line within buf */
str_start = k->str;
-
- /* data is in network encoding so use 0x0a instead of '\n' */
+
+ /* data is in network encoding so use 0x0a instead of '\n' */
end_ptr = memchr(str_start, 0x0a, *nread);
-
+
if(!end_ptr) {
- /* Not a complete header line within buffer, append the data to
- the end of the headerbuff. */
+ /* Not a complete header line within buffer, append the data to
+ the end of the headerbuff. */
result = Curl_dyn_addn(&data->state.headerb, str_start, *nread);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
if(!k->headerline) {
/* check if this looks like a protocol header */
statusline st =
@@ -3184,88 +3184,88 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
Curl_dyn_len(&data->state.headerb));
if(st == STATUS_BAD) {
- /* this is not the beginning of a protocol first header line */
- k->header = FALSE;
- k->badheader = HEADER_ALLBAD;
+ /* this is not the beginning of a protocol first header line */
+ k->header = FALSE;
+ k->badheader = HEADER_ALLBAD;
streamclose(conn, "bad HTTP: No end-of-message indicator");
if(!data->set.http09_allowed) {
failf(data, "Received HTTP/0.9 when not allowed\n");
return CURLE_UNSUPPORTED_PROTOCOL;
}
- break;
- }
- }
-
- break; /* read more and try again */
- }
-
- /* decrease the size of the remaining (supposed) header line */
+ break;
+ }
+ }
+
+ break; /* read more and try again */
+ }
+
+ /* decrease the size of the remaining (supposed) header line */
rest_length = (end_ptr - k->str) + 1;
- *nread -= (ssize_t)rest_length;
-
+ *nread -= (ssize_t)rest_length;
+
k->str = end_ptr + 1; /* move past new line */
-
+
full_length = k->str - str_start;
-
+
result = Curl_dyn_addn(&data->state.headerb, str_start, full_length);
- if(result)
- return result;
-
- /****
+ if(result)
+ return result;
+
+ /****
* We now have a FULL header line in 'headerb'.
- *****/
-
- if(!k->headerline) {
- /* the first read header */
+ *****/
+
+ if(!k->headerline) {
+ /* the first read header */
statusline st = checkprotoprefix(data, conn,
Curl_dyn_ptr(&data->state.headerb),
Curl_dyn_len(&data->state.headerb));
if(st == STATUS_BAD) {
streamclose(conn, "bad HTTP: No end-of-message indicator");
- /* this is not the beginning of a protocol first header line */
+ /* this is not the beginning of a protocol first header line */
if(!data->set.http09_allowed) {
failf(data, "Received HTTP/0.9 when not allowed\n");
return CURLE_UNSUPPORTED_PROTOCOL;
}
- k->header = FALSE;
- if(*nread)
- /* since there's more, this is a partial bad header */
- k->badheader = HEADER_PARTHEADER;
- else {
- /* this was all we read so it's all a bad header */
- k->badheader = HEADER_ALLBAD;
+ k->header = FALSE;
+ if(*nread)
+ /* since there's more, this is a partial bad header */
+ k->badheader = HEADER_PARTHEADER;
+ else {
+ /* this was all we read so it's all a bad header */
+ k->badheader = HEADER_ALLBAD;
*nread = onread;
k->str = ostr;
return CURLE_OK;
- }
- break;
- }
- }
-
+ }
+ break;
+ }
+ }
+
/* headers are in network encoding so use 0x0a and 0x0d instead of '\n'
and '\r' */
headp = Curl_dyn_ptr(&data->state.headerb);
if((0x0a == *headp) || (0x0d == *headp)) {
- size_t headerlen;
- /* Zero-length header line means end of headers! */
-
-#ifdef CURL_DOES_CONVERSIONS
+ size_t headerlen;
+ /* Zero-length header line means end of headers! */
+
+#ifdef CURL_DOES_CONVERSIONS
if(0x0d == *headp) {
*headp = '\r'; /* replace with CR in host encoding */
headp++; /* pass the CR byte */
- }
+ }
if(0x0a == *headp) {
*headp = '\n'; /* replace with LF in host encoding */
headp++; /* pass the LF byte */
- }
-#else
+ }
+#else
if('\r' == *headp)
headp++; /* pass the \r byte */
if('\n' == *headp)
headp++; /* pass the \n byte */
-#endif /* CURL_DOES_CONVERSIONS */
-
- if(100 <= k->httpcode && 199 >= k->httpcode) {
+#endif /* CURL_DOES_CONVERSIONS */
+
+ if(100 <= k->httpcode && 199 >= k->httpcode) {
/* "A user agent MAY ignore unexpected 1xx status responses." */
switch(k->httpcode) {
case 100:
@@ -3278,7 +3278,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
*/
k->header = TRUE;
k->headerline = 0; /* restart the header line counter */
-
+
/* if we did wait for this do enable write now! */
if(k->exp100 > EXP100_SEND_DATA) {
k->exp100 = EXP100_SEND_DATA;
@@ -3315,26 +3315,26 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
k->header = TRUE;
k->headerline = 0; /* restart the header line counter */
break;
- }
- }
- else {
- k->header = FALSE; /* no more header to parse! */
-
- if((k->size == -1) && !k->chunk && !conn->bits.close &&
+ }
+ }
+ else {
+ k->header = FALSE; /* no more header to parse! */
+
+ if((k->size == -1) && !k->chunk && !conn->bits.close &&
(conn->httpversion == 11) &&
- !(conn->handler->protocol & CURLPROTO_RTSP) &&
+ !(conn->handler->protocol & CURLPROTO_RTSP) &&
data->state.httpreq != HTTPREQ_HEAD) {
- /* On HTTP 1.1, when connection is not to get closed, but no
+ /* On HTTP 1.1, when connection is not to get closed, but no
Content-Length nor Transfer-Encoding chunked have been
- received, according to RFC2616 section 4.4 point 5, we
- assume that the server will close the connection to
- signal the end of the document. */
- infof(data, "no chunk, no close, no size. Assume close to "
- "signal end\n");
+ received, according to RFC2616 section 4.4 point 5, we
+ assume that the server will close the connection to
+ signal the end of the document. */
+ infof(data, "no chunk, no close, no size. Assume close to "
+ "signal end\n");
streamclose(conn, "HTTP: No end-of-message indicator");
- }
- }
-
+ }
+ }
+
/* At this point we have some idea about the fate of the connection.
If we are closing the connection it may result auth failure. */
#if defined(USE_NTLM)
@@ -3365,43 +3365,43 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
conn->proxy_negotiate_state = GSS_AUTHSUCC;
}
#endif
- /*
- * When all the headers have been parsed, see if we should give
- * up and return an error.
- */
- if(http_should_fail(conn)) {
+ /*
+ * When all the headers have been parsed, see if we should give
+ * up and return an error.
+ */
+ if(http_should_fail(conn)) {
failf(data, "The requested URL returned error: %d",
k->httpcode);
- return CURLE_HTTP_RETURNED_ERROR;
- }
-
- /* now, only output this if the header AND body are requested:
- */
- writetype = CLIENTWRITE_HEADER;
- if(data->set.include_header)
- writetype |= CLIENTWRITE_BODY;
-
+ return CURLE_HTTP_RETURNED_ERROR;
+ }
+
+ /* now, only output this if the header AND body are requested:
+ */
+ writetype = CLIENTWRITE_HEADER;
+ if(data->set.include_header)
+ writetype |= CLIENTWRITE_BODY;
+
headerlen = Curl_dyn_len(&data->state.headerb);
- result = Curl_client_write(conn, writetype,
+ result = Curl_client_write(conn, writetype,
Curl_dyn_ptr(&data->state.headerb),
- headerlen);
- if(result)
- return result;
-
- data->info.header_size += (long)headerlen;
- data->req.headerbytecount += (long)headerlen;
-
- data->req.deductheadercount =
- (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
-
+ headerlen);
+ if(result)
+ return result;
+
+ data->info.header_size += (long)headerlen;
+ data->req.headerbytecount += (long)headerlen;
+
+ data->req.deductheadercount =
+ (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
+
/* Curl_http_auth_act() checks what authentication methods
* that are available and decides which one (if any) to
* use. It will set 'newurl' if an auth method was picked. */
result = Curl_http_auth_act(conn);
-
+
if(result)
return result;
-
+
if(k->httpcode >= 300) {
if((!conn->bits.authneg) && !conn->bits.close &&
!conn->bits.rewindaftersend) {
@@ -3426,7 +3426,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
/* We got an error response. If this happened before the whole
* request body has been sent we stop sending and mark the
* connection for closure after we've read the entire response.
- */
+ */
Curl_expire_done(data, EXPIRE_100_TIMEOUT);
if(!k->upload_done) {
if((k->httpcode == 417) && data->state.expect100header) {
@@ -3446,40 +3446,40 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
}
}
else {
- infof(data, "HTTP error before end of send, stop sending\n");
+ infof(data, "HTTP error before end of send, stop sending\n");
streamclose(conn, "Stop sending data before everything sent");
result = Curl_done_sending(conn, k);
if(result)
return result;
- k->upload_done = TRUE;
- if(data->state.expect100header)
- k->exp100 = EXP100_FAILED;
- }
+ k->upload_done = TRUE;
+ if(data->state.expect100header)
+ k->exp100 = EXP100_FAILED;
+ }
}
break;
-
+
default: /* default label present to avoid compiler warnings */
break;
- }
- }
-
- if(conn->bits.rewindaftersend) {
- /* We rewind after a complete send, so thus we continue
- sending now */
- infof(data, "Keep sending data to get tossed away!\n");
- k->keepon |= KEEP_SEND;
- }
- }
-
- if(!k->header) {
- /*
- * really end-of-headers.
- *
- * If we requested a "no body", this is a good time to get
- * out and return home.
- */
- if(data->set.opt_no_body)
- *stop_reading = TRUE;
+ }
+ }
+
+ if(conn->bits.rewindaftersend) {
+ /* We rewind after a complete send, so thus we continue
+ sending now */
+ infof(data, "Keep sending data to get tossed away!\n");
+ k->keepon |= KEEP_SEND;
+ }
+ }
+
+ if(!k->header) {
+ /*
+ * really end-of-headers.
+ *
+ * If we requested a "no body", this is a good time to get
+ * out and return home.
+ */
+ if(data->set.opt_no_body)
+ *stop_reading = TRUE;
#ifndef CURL_DISABLE_RTSP
else if((conn->handler->protocol & CURLPROTO_RTSP) &&
(data->set.rtspreq == RTSPREQ_DESCRIBE) &&
@@ -3490,32 +3490,32 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
reason */
*stop_reading = TRUE;
#endif
- else {
- /* If we know the expected size of this document, we set the
- maximum download size to the size of the expected
- document or else, we won't know when to stop reading!
-
- Note that we set the download maximum even if we read a
- "Connection: close" header, to make sure that
- "Content-Length: 0" still prevents us from attempting to
- read the (missing) response-body.
- */
- /* According to RFC2616 section 4.4, we MUST ignore
- Content-Length: headers if we are now receiving data
- using chunked Transfer-Encoding.
- */
- if(k->chunk)
- k->maxdownload = k->size = -1;
- }
- if(-1 != k->size) {
- /* We do this operation even if no_body is true, since this
- data might be retrieved later with curl_easy_getinfo()
- and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
-
- Curl_pgrsSetDownloadSize(data, k->size);
- k->maxdownload = k->size;
- }
-
+ else {
+ /* If we know the expected size of this document, we set the
+ maximum download size to the size of the expected
+ document or else, we won't know when to stop reading!
+
+ Note that we set the download maximum even if we read a
+ "Connection: close" header, to make sure that
+ "Content-Length: 0" still prevents us from attempting to
+ read the (missing) response-body.
+ */
+ /* According to RFC2616 section 4.4, we MUST ignore
+ Content-Length: headers if we are now receiving data
+ using chunked Transfer-Encoding.
+ */
+ if(k->chunk)
+ k->maxdownload = k->size = -1;
+ }
+ if(-1 != k->size) {
+ /* We do this operation even if no_body is true, since this
+ data might be retrieved later with curl_easy_getinfo()
+ and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
+
+ Curl_pgrsSetDownloadSize(data, k->size);
+ k->maxdownload = k->size;
+ }
+
/* If max download size is *zero* (nothing) we already have
nothing and can safely return ok now! But for HTTP/2, we'd
like to call http2_handle_stream_close to properly close a
@@ -3527,53 +3527,53 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
conn->httpversion == 20)
#endif
)
- *stop_reading = TRUE;
-
- if(*stop_reading) {
- /* we make sure that this socket isn't read more now */
- k->keepon &= ~KEEP_RECV;
- }
-
+ *stop_reading = TRUE;
+
+ if(*stop_reading) {
+ /* we make sure that this socket isn't read more now */
+ k->keepon &= ~KEEP_RECV;
+ }
+
Curl_debug(data, CURLINFO_HEADER_IN, str_start, headerlen);
break; /* exit header line loop */
- }
-
+ }
+
/* We continue reading headers, reset the line-based header */
Curl_dyn_reset(&data->state.headerb);
- continue;
- }
-
- /*
- * Checks for special headers coming up.
- */
-
- if(!k->headerline++) {
- /* This is the first header, it MUST be the error code line
- or else we consider this to be the body right away! */
- int httpversion_major;
- int rtspversion_major;
- int nc = 0;
-#ifdef CURL_DOES_CONVERSIONS
-#define HEADER1 scratch
-#define SCRATCHSIZE 21
- CURLcode res;
+ continue;
+ }
+
+ /*
+ * Checks for special headers coming up.
+ */
+
+ if(!k->headerline++) {
+ /* This is the first header, it MUST be the error code line
+ or else we consider this to be the body right away! */
+ int httpversion_major;
+ int rtspversion_major;
+ int nc = 0;
+#ifdef CURL_DOES_CONVERSIONS
+#define HEADER1 scratch
+#define SCRATCHSIZE 21
+ CURLcode res;
char scratch[SCRATCHSIZE + 1]; /* "HTTP/major.minor 123" */
/* We can't really convert this yet because we don't know if it's the
1st header line or the body. So we do a partial conversion into a
scratch area, leaving the data at 'headp' as-is.
- */
+ */
strncpy(&scratch[0], headp, SCRATCHSIZE);
- scratch[SCRATCHSIZE] = 0; /* null terminate */
- res = Curl_convert_from_network(data,
- &scratch[0],
- SCRATCHSIZE);
- if(res)
- /* Curl_convert_from_network calls failf if unsuccessful */
- return res;
-#else
+ scratch[SCRATCHSIZE] = 0; /* null terminate */
+ res = Curl_convert_from_network(data,
+ &scratch[0],
+ SCRATCHSIZE);
+ if(res)
+ /* Curl_convert_from_network calls failf if unsuccessful */
+ return res;
+#else
#define HEADER1 headp /* no conversion needed, just use headp */
-#endif /* CURL_DOES_CONVERSIONS */
-
+#endif /* CURL_DOES_CONVERSIONS */
+
if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
/*
* https://tools.ietf.org/html/rfc7230#section-3.1.2
@@ -3584,12 +3584,12 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
*/
char separator;
char twoorthree[2];
- nc = sscanf(HEADER1,
+ nc = sscanf(HEADER1,
" HTTP/%1d.%1d%c%3d",
- &httpversion_major,
- &conn->httpversion,
+ &httpversion_major,
+ &conn->httpversion,
&separator,
- &k->httpcode);
+ &k->httpcode);
if(nc == 1 && httpversion_major >= 2 &&
2 == sscanf(HEADER1, " HTTP/%1[23] %d", twoorthree, &k->httpcode)) {
@@ -3599,7 +3599,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
}
if((nc == 4) && (' ' == separator)) {
- conn->httpversion += 10 * httpversion_major;
+ conn->httpversion += 10 * httpversion_major;
if(k->upgr101 == UPGR101_RECEIVED) {
/* supposedly upgraded to http2 now */
@@ -3610,68 +3610,68 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
conn->bundle->multiuse = BUNDLE_NO_MULTIUSE;
infof(data, "Mark bundle as not supporting multiuse\n");
}
- }
+ }
else if(!nc) {
- /* this is the real world, not a Nirvana
- NCSA 1.5.x returns this crap when asked for HTTP/1.1
- */
+ /* this is the real world, not a Nirvana
+ NCSA 1.5.x returns this crap when asked for HTTP/1.1
+ */
nc = sscanf(HEADER1, " HTTP %3d", &k->httpcode);
- conn->httpversion = 10;
-
- /* If user has set option HTTP200ALIASES,
- compare header line against list of aliases
- */
- if(!nc) {
+ conn->httpversion = 10;
+
+ /* If user has set option HTTP200ALIASES,
+ compare header line against list of aliases
+ */
+ if(!nc) {
statusline check =
checkhttpprefix(data,
Curl_dyn_ptr(&data->state.headerb),
Curl_dyn_len(&data->state.headerb));
if(check == STATUS_DONE) {
- nc = 1;
- k->httpcode = 200;
- conn->httpversion = 10;
- }
- }
- }
+ nc = 1;
+ k->httpcode = 200;
+ conn->httpversion = 10;
+ }
+ }
+ }
else {
failf(data, "Unsupported HTTP version in response");
return CURLE_UNSUPPORTED_PROTOCOL;
}
- }
- else if(conn->handler->protocol & CURLPROTO_RTSP) {
+ }
+ else if(conn->handler->protocol & CURLPROTO_RTSP) {
char separator;
- nc = sscanf(HEADER1,
+ nc = sscanf(HEADER1,
" RTSP/%1d.%1d%c%3d",
- &rtspversion_major,
- &conn->rtspversion,
+ &rtspversion_major,
+ &conn->rtspversion,
&separator,
- &k->httpcode);
+ &k->httpcode);
if((nc == 4) && (' ' == separator)) {
- conn->rtspversion += 10 * rtspversion_major;
- conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
- }
- else {
- nc = 0;
- }
- }
-
- if(nc) {
- data->info.httpcode = k->httpcode;
-
- data->info.httpversion = conn->httpversion;
- if(!data->state.httpversion ||
- data->state.httpversion > conn->httpversion)
- /* store the lowest server version we encounter */
- data->state.httpversion = conn->httpversion;
-
- /*
- * This code executes as part of processing the header. As a
- * result, it's not totally clear how to interpret the
- * response code yet as that depends on what other headers may
- * be present. 401 and 407 may be errors, but may be OK
- * depending on how authentication is working. Other codes
- * are definitely errors, so give up here.
- */
+ conn->rtspversion += 10 * rtspversion_major;
+ conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
+ }
+ else {
+ nc = 0;
+ }
+ }
+
+ if(nc) {
+ data->info.httpcode = k->httpcode;
+
+ data->info.httpversion = conn->httpversion;
+ if(!data->state.httpversion ||
+ data->state.httpversion > conn->httpversion)
+ /* store the lowest server version we encounter */
+ data->state.httpversion = conn->httpversion;
+
+ /*
+ * This code executes as part of processing the header. As a
+ * result, it's not totally clear how to interpret the
+ * response code yet as that depends on what other headers may
+ * be present. 401 and 407 may be errors, but may be OK
+ * depending on how authentication is working. Other codes
+ * are definitely errors, so give up here.
+ */
if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET &&
k->httpcode == 416) {
/* "Requested Range Not Satisfiable", just proceed and
@@ -3687,15 +3687,15 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
/* serious error, go home! */
print_http_error(data);
return CURLE_HTTP_RETURNED_ERROR;
- }
-
- if(conn->httpversion == 10) {
- /* Default action for HTTP/1.0 must be to close, unless
- we get one of those fancy headers that tell us the
- server keeps it open for us! */
- infof(data, "HTTP 1.0, assume close after body\n");
+ }
+
+ if(conn->httpversion == 10) {
+ /* Default action for HTTP/1.0 must be to close, unless
+ we get one of those fancy headers that tell us the
+ server keeps it open for us! */
+ infof(data, "HTTP 1.0, assume close after body\n");
connclose(conn, "HTTP/1.0 close after body");
- }
+ }
else if(conn->httpversion == 20 ||
(k->upgr101 == UPGR101_REQUESTED && k->httpcode == 101)) {
DEBUGF(infof(data, "HTTP/2 found, allow multiplexing\n"));
@@ -3703,22 +3703,22 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
of the protocol */
conn->bundle->multiuse = BUNDLE_MULTIPLEX;
}
- else if(conn->httpversion >= 11 &&
- !conn->bits.close) {
+ else if(conn->httpversion >= 11 &&
+ !conn->bits.close) {
/* If HTTP version is >= 1.1 and connection is persistent */
- DEBUGF(infof(data,
+ DEBUGF(infof(data,
"HTTP 1.1 or later with persistent connection\n"));
- }
-
+ }
+
k->http_bodyless = k->httpcode >= 100 && k->httpcode < 200;
- switch(k->httpcode) {
- case 304:
- /* (quote from RFC2616, section 10.3.5): The 304 response
- * MUST NOT contain a message-body, and thus is always
- * terminated by the first empty line after the header
- * fields. */
- if(data->set.timecondition)
- data->info.timecond = TRUE;
+ switch(k->httpcode) {
+ case 304:
+ /* (quote from RFC2616, section 10.3.5): The 304 response
+ * MUST NOT contain a message-body, and thus is always
+ * terminated by the first empty line after the header
+ * fields. */
+ if(data->set.timecondition)
+ data->info.timecond = TRUE;
/* FALLTHROUGH */
case 204:
/* (quote from RFC2616, section 10.2.5): The server has
@@ -3729,23 +3729,23 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
k->size = 0;
k->maxdownload = 0;
k->http_bodyless = TRUE;
- break;
- default:
- break;
- }
- }
- else {
- k->header = FALSE; /* this is not a header line */
- break;
- }
- }
-
+ break;
+ default:
+ break;
+ }
+ }
+ else {
+ k->header = FALSE; /* this is not a header line */
+ break;
+ }
+ }
+
result = Curl_convert_from_network(data, headp, strlen(headp));
- /* Curl_convert_from_network calls failf if unsuccessful */
- if(result)
- return result;
-
- /* Check for Content-Length: header lines to get size */
+ /* Curl_convert_from_network calls failf if unsuccessful */
+ if(result)
+ return result;
+
+ /* Check for Content-Length: header lines to get size */
if(!k->http_bodyless &&
!data->set.ignorecl && checkprefix("Content-Length:", headp)) {
curl_off_t contentlength;
@@ -3757,13 +3757,13 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
failf(data, "Maximum file size exceeded");
return CURLE_FILESIZE_EXCEEDED;
}
- k->size = contentlength;
- k->maxdownload = k->size;
- /* we set the progress download size already at this point
- just to make it easier for apps/callbacks to extract this
- info as soon as possible */
- Curl_pgrsSetDownloadSize(data, k->size);
- }
+ k->size = contentlength;
+ k->maxdownload = k->size;
+ /* we set the progress download size already at this point
+ just to make it easier for apps/callbacks to extract this
+ info as soon as possible */
+ Curl_pgrsSetDownloadSize(data, k->size);
+ }
else if(offt == CURL_OFFT_FLOW) {
/* out of range */
if(data->set.max_filesize) {
@@ -3773,98 +3773,98 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
streamclose(conn, "overflow content-length");
infof(data, "Overflow Content-Length: value!\n");
}
- else {
+ else {
/* negative or just rubbish - bad HTTP */
failf(data, "Invalid Content-Length: value");
return CURLE_WEIRD_SERVER_REPLY;
- }
- }
- /* check for Content-Type: header lines to get the MIME-type */
+ }
+ }
+ /* check for Content-Type: header lines to get the MIME-type */
else if(checkprefix("Content-Type:", headp)) {
char *contenttype = Curl_copy_header_value(headp);
- if(!contenttype)
- return CURLE_OUT_OF_MEMORY;
- if(!*contenttype)
- /* ignore empty data */
- free(contenttype);
- else {
- Curl_safefree(data->info.contenttype);
- data->info.contenttype = contenttype;
- }
- }
+ if(!contenttype)
+ return CURLE_OUT_OF_MEMORY;
+ if(!*contenttype)
+ /* ignore empty data */
+ free(contenttype);
+ else {
+ Curl_safefree(data->info.contenttype);
+ data->info.contenttype = contenttype;
+ }
+ }
#ifndef CURL_DISABLE_PROXY
- else if((conn->httpversion == 10) &&
- conn->bits.httpproxy &&
+ else if((conn->httpversion == 10) &&
+ conn->bits.httpproxy &&
Curl_compareheader(headp, "Proxy-Connection:", "keep-alive")) {
- /*
- * When a HTTP/1.0 reply comes when using a proxy, the
- * 'Proxy-Connection: keep-alive' line tells us the
- * connection will be kept alive for our pleasure.
- * Default action for 1.0 is to close.
- */
+ /*
+ * When a HTTP/1.0 reply comes when using a proxy, the
+ * 'Proxy-Connection: keep-alive' line tells us the
+ * connection will be kept alive for our pleasure.
+ * Default action for 1.0 is to close.
+ */
connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */
- infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
- }
- else if((conn->httpversion == 11) &&
- conn->bits.httpproxy &&
+ infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
+ }
+ else if((conn->httpversion == 11) &&
+ conn->bits.httpproxy &&
Curl_compareheader(headp, "Proxy-Connection:", "close")) {
- /*
- * We get a HTTP/1.1 response from a proxy and it says it'll
- * close down after this transfer.
- */
+ /*
+ * We get a HTTP/1.1 response from a proxy and it says it'll
+ * close down after this transfer.
+ */
connclose(conn, "Proxy-Connection: asked to close after done");
- infof(data, "HTTP/1.1 proxy connection set close!\n");
- }
+ infof(data, "HTTP/1.1 proxy connection set close!\n");
+ }
#endif
- else if((conn->httpversion == 10) &&
+ else if((conn->httpversion == 10) &&
Curl_compareheader(headp, "Connection:", "keep-alive")) {
- /*
- * A HTTP/1.0 reply with the 'Connection: keep-alive' line
- * tells us the connection will be kept alive for our
- * pleasure. Default action for 1.0 is to close.
- *
- * [RFC2068, section 19.7.1] */
+ /*
+ * A HTTP/1.0 reply with the 'Connection: keep-alive' line
+ * tells us the connection will be kept alive for our
+ * pleasure. Default action for 1.0 is to close.
+ *
+ * [RFC2068, section 19.7.1] */
connkeep(conn, "Connection keep-alive");
- infof(data, "HTTP/1.0 connection set to keep alive!\n");
- }
+ infof(data, "HTTP/1.0 connection set to keep alive!\n");
+ }
else if(Curl_compareheader(headp, "Connection:", "close")) {
- /*
- * [RFC 2616, section 8.1.2.1]
- * "Connection: close" is HTTP/1.1 language and means that
- * the connection will close when this request has been
- * served.
- */
+ /*
+ * [RFC 2616, section 8.1.2.1]
+ * "Connection: close" is HTTP/1.1 language and means that
+ * the connection will close when this request has been
+ * served.
+ */
streamclose(conn, "Connection: close used");
- }
+ }
else if(!k->http_bodyless && checkprefix("Transfer-Encoding:", headp)) {
- /* One or more encodings. We check for chunked and/or a compression
- algorithm. */
- /*
- * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
- * means that the server will send a series of "chunks". Each
- * chunk starts with line with info (including size of the
- * coming block) (terminated with CRLF), then a block of data
- * with the previously mentioned size. There can be any amount
- * of chunks, and a chunk-data set to zero signals the
- * end-of-chunks. */
-
+ /* One or more encodings. We check for chunked and/or a compression
+ algorithm. */
+ /*
+ * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
+ * means that the server will send a series of "chunks". Each
+ * chunk starts with line with info (including size of the
+ * coming block) (terminated with CRLF), then a block of data
+ * with the previously mentioned size. There can be any amount
+ * of chunks, and a chunk-data set to zero signals the
+ * end-of-chunks. */
+
result = Curl_build_unencoding_stack(conn, headp + 18, TRUE);
if(result)
return result;
- }
+ }
else if(!k->http_bodyless && checkprefix("Content-Encoding:", headp) &&
- data->set.str[STRING_ENCODING]) {
- /*
- * Process Content-Encoding. Look for the values: identity,
- * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
- * x-compress are the same as gzip and compress. (Sec 3.5 RFC
- * 2616). zlib cannot handle compress. However, errors are
- * handled further down when the response body is processed
- */
+ data->set.str[STRING_ENCODING]) {
+ /*
+ * Process Content-Encoding. Look for the values: identity,
+ * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
+ * x-compress are the same as gzip and compress. (Sec 3.5 RFC
+ * 2616). zlib cannot handle compress. However, errors are
+ * handled further down when the response body is processed
+ */
result = Curl_build_unencoding_stack(conn, headp + 17, FALSE);
if(result)
return result;
- }
+ }
else if(checkprefix("Retry-After:", headp)) {
/* Retry-After = HTTP-date / delay-seconds */
curl_off_t retry_after = 0; /* zero for unknown or "now" */
@@ -3879,23 +3879,23 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
data->info.retry_after = retry_after; /* store it */
}
else if(!k->http_bodyless && checkprefix("Content-Range:", headp)) {
- /* Content-Range: bytes [num]-
- Content-Range: bytes: [num]-
- Content-Range: [num]-
+ /* Content-Range: bytes [num]-
+ Content-Range: bytes: [num]-
+ Content-Range: [num]-
Content-Range: [asterisk]/[total]
-
- The second format was added since Sun's webserver
- JavaWebServer/1.1.1 obviously sends the header this way!
- The third added since some servers use that!
+
+ The second format was added since Sun's webserver
+ JavaWebServer/1.1.1 obviously sends the header this way!
+ The third added since some servers use that!
The forth means the requested range was unsatisfied.
- */
-
+ */
+
char *ptr = headp + 14;
-
+
/* Move forward until first digit or asterisk */
while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
- ptr++;
-
+ ptr++;
+
/* if it truly stopped on a digit */
if(ISDIGIT(*ptr)) {
if(!curlx_strtoofft(ptr, NULL, 10, &k->offset)) {
@@ -3906,34 +3906,34 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
}
else
data->state.resume_from = 0; /* get everything */
- }
-#if !defined(CURL_DISABLE_COOKIES)
+ }
+#if !defined(CURL_DISABLE_COOKIES)
else if(data->cookies && data->state.cookie_engine &&
checkprefix("Set-Cookie:", headp)) {
- Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
- CURL_LOCK_ACCESS_SINGLE);
- Curl_cookie_add(data,
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
+ CURL_LOCK_ACCESS_SINGLE);
+ Curl_cookie_add(data,
data->cookies, TRUE, FALSE, headp + 11,
- /* If there is a custom-set Host: name, use it
- here, or else use real peer host name. */
+ /* If there is a custom-set Host: name, use it
+ here, or else use real peer host name. */
data->state.aptr.cookiehost?
data->state.aptr.cookiehost:conn->host.name,
data->state.up.path,
(conn->handler->protocol&CURLPROTO_HTTPS)?
TRUE:FALSE);
- Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
- }
-#endif
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ }
+#endif
else if(!k->http_bodyless && checkprefix("Last-Modified:", headp) &&
- (data->set.timecondition || data->set.get_filetime) ) {
+ (data->set.timecondition || data->set.get_filetime) ) {
k->timeofdoc = Curl_getdate_capped(headp + strlen("Last-Modified:"));
- if(data->set.get_filetime)
+ if(data->set.get_filetime)
data->info.filetime = k->timeofdoc;
- }
+ }
else if((checkprefix("WWW-Authenticate:", headp) &&
- (401 == k->httpcode)) ||
+ (401 == k->httpcode)) ||
(checkprefix("Proxy-authenticate:", headp) &&
- (407 == k->httpcode))) {
+ (407 == k->httpcode))) {
bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
char *auth = Curl_copy_header_value(headp);
@@ -3944,9 +3944,9 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
free(auth);
- if(result)
- return result;
- }
+ if(result)
+ return result;
+ }
#ifdef USE_SPNEGO
else if(checkprefix("Persistent-Auth", headp)) {
struct negotiatedata *negdata = &conn->negotiate;
@@ -3964,33 +3964,33 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
}
}
#endif
- else if((k->httpcode >= 300 && k->httpcode < 400) &&
+ else if((k->httpcode >= 300 && k->httpcode < 400) &&
checkprefix("Location:", headp) &&
- !data->req.location) {
- /* this is the URL that the server advises us to use instead */
+ !data->req.location) {
+ /* this is the URL that the server advises us to use instead */
char *location = Curl_copy_header_value(headp);
- if(!location)
- return CURLE_OUT_OF_MEMORY;
- if(!*location)
- /* ignore empty data */
- free(location);
- else {
- data->req.location = location;
-
- if(data->set.http_follow_location) {
- DEBUGASSERT(!data->req.newurl);
- data->req.newurl = strdup(data->req.location); /* clone */
- if(!data->req.newurl)
- return CURLE_OUT_OF_MEMORY;
-
- /* some cases of POST and PUT etc needs to rewind the data
- stream at this point */
- result = http_perhapsrewind(conn);
- if(result)
- return result;
- }
- }
- }
+ if(!location)
+ return CURLE_OUT_OF_MEMORY;
+ if(!*location)
+ /* ignore empty data */
+ free(location);
+ else {
+ data->req.location = location;
+
+ if(data->set.http_follow_location) {
+ DEBUGASSERT(!data->req.newurl);
+ data->req.newurl = strdup(data->req.location); /* clone */
+ if(!data->req.newurl)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* some cases of POST and PUT etc needs to rewind the data
+ stream at this point */
+ result = http_perhapsrewind(conn);
+ if(result)
+ return result;
+ }
+ }
+ }
#ifdef USE_HSTS
/* If enabled, the header is incoming and this is over HTTPS */
@@ -4029,40 +4029,40 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
return result;
}
#endif
- else if(conn->handler->protocol & CURLPROTO_RTSP) {
+ else if(conn->handler->protocol & CURLPROTO_RTSP) {
result = Curl_rtsp_parseheader(conn, headp);
- if(result)
- return result;
- }
-
- /*
- * End of header-checks. Write them to the client.
- */
-
- writetype = CLIENTWRITE_HEADER;
- if(data->set.include_header)
- writetype |= CLIENTWRITE_BODY;
-
+ if(result)
+ return result;
+ }
+
+ /*
+ * End of header-checks. Write them to the client.
+ */
+
+ writetype = CLIENTWRITE_HEADER;
+ if(data->set.include_header)
+ writetype |= CLIENTWRITE_BODY;
+
Curl_debug(data, CURLINFO_HEADER_IN, headp,
Curl_dyn_len(&data->state.headerb));
-
+
result = Curl_client_write(conn, writetype, headp,
Curl_dyn_len(&data->state.headerb));
- if(result)
- return result;
-
+ if(result)
+ return result;
+
data->info.header_size += Curl_dyn_len(&data->state.headerb);
data->req.headerbytecount += Curl_dyn_len(&data->state.headerb);
-
+
Curl_dyn_reset(&data->state.headerb);
- }
+ }
while(*k->str); /* header line within buffer */
-
- /* We might have reached the end of the header part here, but
- there might be a non-header part left in the end of the read
- buffer. */
-
- return CURLE_OK;
-}
-
-#endif /* CURL_DISABLE_HTTP */
+
+ /* We might have reached the end of the header part here, but
+ there might be a non-header part left in the end of the read
+ buffer. */
+
+ return CURLE_OK;
+}
+
+#endif /* CURL_DISABLE_HTTP */
diff --git a/contrib/libs/curl/lib/http.h b/contrib/libs/curl/lib/http.h
index f70b0f9c46..1aaec225e2 100644
--- a/contrib/libs/curl/lib/http.h
+++ b/contrib/libs/curl/lib/http.h
@@ -1,47 +1,47 @@
-#ifndef HEADER_CURL_HTTP_H
-#define HEADER_CURL_HTTP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HTTP_H
+#define HEADER_CURL_HTTP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_HTTP
-
-#ifdef USE_NGHTTP2
-#include <nghttp2/nghttp2.h>
-#endif
-
-extern const struct Curl_handler Curl_handler_http;
-
-#ifdef USE_SSL
-extern const struct Curl_handler Curl_handler_https;
-#endif
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_HTTP
+
+#ifdef USE_NGHTTP2
+#include <nghttp2/nghttp2.h>
+#endif
+
+extern const struct Curl_handler Curl_handler_http;
+
+#ifdef USE_SSL
+extern const struct Curl_handler Curl_handler_https;
+#endif
+
/* Header specific functions */
-bool Curl_compareheader(const char *headerline, /* line to check */
- const char *header, /* header keyword _with_ colon */
- const char *content); /* content string to find */
-
+bool Curl_compareheader(const char *headerline, /* line to check */
+ const char *header, /* header keyword _with_ colon */
+ const char *content); /* content string to find */
+
char *Curl_copy_header_value(const char *header);
-
+
char *Curl_checkProxyheaders(const struct connectdata *conn,
const char *thisheader);
CURLcode Curl_buffer_send(struct dynbuf *in,
@@ -49,48 +49,48 @@ CURLcode Curl_buffer_send(struct dynbuf *in,
curl_off_t *bytes_written,
size_t included_body_bytes,
int socketindex);
-
+
CURLcode Curl_add_timecondition(const struct connectdata *conn,
struct dynbuf *buf);
-CURLcode Curl_add_custom_headers(struct connectdata *conn,
+CURLcode Curl_add_custom_headers(struct connectdata *conn,
bool is_connect,
struct dynbuf *req_buffer);
CURLcode Curl_http_compile_trailers(struct curl_slist *trailers,
struct dynbuf *buf,
struct Curl_easy *handle);
-
-/* protocol-specific functions set up to be called by the main engine */
-CURLcode Curl_http(struct connectdata *conn, bool *done);
-CURLcode Curl_http_done(struct connectdata *, CURLcode, bool premature);
-CURLcode Curl_http_connect(struct connectdata *conn, bool *done);
-
-/* These functions are in http.c */
+
+/* protocol-specific functions set up to be called by the main engine */
+CURLcode Curl_http(struct connectdata *conn, bool *done);
+CURLcode Curl_http_done(struct connectdata *, CURLcode, bool premature);
+CURLcode Curl_http_connect(struct connectdata *conn, bool *done);
+
+/* These functions are in http.c */
CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
const char *auth);
-CURLcode Curl_http_auth_act(struct connectdata *conn);
-
-/* If only the PICKNONE bit is set, there has been a round-trip and we
- selected to use no auth at all. Ie, we actively select no auth, as opposed
- to not having one selected. The other CURLAUTH_* defines are present in the
- public curl/curl.h header. */
-#define CURLAUTH_PICKNONE (1<<30) /* don't use auth */
-
-/* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST
- data get included in the initial data chunk sent to the server. If the
- data is larger than this, it will automatically get split up in multiple
- system calls.
-
- This value used to be fairly big (100K), but we must take into account that
- if the server rejects the POST due for authentication reasons, this data
+CURLcode Curl_http_auth_act(struct connectdata *conn);
+
+/* If only the PICKNONE bit is set, there has been a round-trip and we
+ selected to use no auth at all. Ie, we actively select no auth, as opposed
+ to not having one selected. The other CURLAUTH_* defines are present in the
+ public curl/curl.h header. */
+#define CURLAUTH_PICKNONE (1<<30) /* don't use auth */
+
+/* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST
+ data get included in the initial data chunk sent to the server. If the
+ data is larger than this, it will automatically get split up in multiple
+ system calls.
+
+ This value used to be fairly big (100K), but we must take into account that
+ if the server rejects the POST due for authentication reasons, this data
will always be unconditionally sent and thus it may not be larger than can
- always be afforded to send twice.
-
- It must not be greater than 64K to work on VMS.
-*/
-#ifndef MAX_INITIAL_POST_SIZE
-#define MAX_INITIAL_POST_SIZE (64*1024)
-#endif
-
+ always be afforded to send twice.
+
+ It must not be greater than 64K to work on VMS.
+*/
+#ifndef MAX_INITIAL_POST_SIZE
+#define MAX_INITIAL_POST_SIZE (64*1024)
+#endif
+
/* EXPECT_100_THRESHOLD is the request body size limit for when libcurl will
* automatically add an "Expect: 100-continue" header in HTTP requests. When
* the size is unknown, it will always add it.
@@ -98,42 +98,42 @@ CURLcode Curl_http_auth_act(struct connectdata *conn);
*/
#ifndef EXPECT_100_THRESHOLD
#define EXPECT_100_THRESHOLD (1024*1024)
-#endif
-
-#endif /* CURL_DISABLE_HTTP */
-
+#endif
+
+#endif /* CURL_DISABLE_HTTP */
+
#ifdef USE_NGHTTP3
struct h3out; /* see ngtcp2 */
#endif
-/****************************************************************************
- * HTTP unique setup
- ***************************************************************************/
-struct HTTP {
+/****************************************************************************
+ * HTTP unique setup
+ ***************************************************************************/
+struct HTTP {
curl_mimepart *sendit;
- curl_off_t postsize; /* off_t to handle large file sizes */
- const char *postdata;
-
- const char *p_pragma; /* Pragma: string */
- const char *p_accept; /* Accept: string */
-
- /* For FORM posting */
+ curl_off_t postsize; /* off_t to handle large file sizes */
+ const char *postdata;
+
+ const char *p_pragma; /* Pragma: string */
+ const char *p_accept; /* Accept: string */
+
+ /* For FORM posting */
curl_mimepart form;
-
- struct back {
- curl_read_callback fread_func; /* backup storage for fread pointer */
- void *fread_in; /* backup storage for fread_in pointer */
- const char *postdata;
- curl_off_t postsize;
- } backup;
-
- enum {
- HTTPSEND_NADA, /* init */
- HTTPSEND_REQUEST, /* sending a request */
- HTTPSEND_BODY, /* sending body */
- HTTPSEND_LAST /* never use this */
- } sending;
-
+
+ struct back {
+ curl_read_callback fread_func; /* backup storage for fread pointer */
+ void *fread_in; /* backup storage for fread_in pointer */
+ const char *postdata;
+ curl_off_t postsize;
+ } backup;
+
+ enum {
+ HTTPSEND_NADA, /* init */
+ HTTPSEND_REQUEST, /* sending a request */
+ HTTPSEND_BODY, /* sending body */
+ HTTPSEND_LAST /* never use this */
+ } sending;
+
#ifndef CURL_DISABLE_HTTP
struct dynbuf send_buffer; /* used if the request couldn't be sent in one
chunk, points to an allocated send_buffer
@@ -184,8 +184,8 @@ struct HTTP {
struct h3out *h3out; /* per-stream buffers for upload */
struct dynbuf overflow; /* excess data received during a single Curl_read */
#endif
-};
-
+};
+
#ifdef USE_NGHTTP2
/* h2 settings for this connection */
struct h2settings {
@@ -194,10 +194,10 @@ struct h2settings {
};
#endif
-struct http_conn {
-#ifdef USE_NGHTTP2
+struct http_conn {
+#ifdef USE_NGHTTP2
#define H2_BINSETTINGS_LEN 80
- nghttp2_session *h2;
+ nghttp2_session *h2;
uint8_t binsettings[H2_BINSETTINGS_LEN];
size_t binlen; /* length of the binsettings data */
Curl_send *send_underlying; /* underlying send Curl_send callback */
@@ -221,35 +221,35 @@ struct http_conn {
nghttp2_settings_entry local_settings[3];
size_t local_settings_num;
uint32_t error_code; /* HTTP/2 error code */
-#else
- int unused; /* prevent a compiler warning */
-#endif
-};
-
+#else
+ int unused; /* prevent a compiler warning */
+#endif
+};
+
CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
- struct connectdata *conn,
- ssize_t *nread,
- bool *stop_reading);
-
-/**
- * Curl_http_output_auth() setups the authentication headers for the
- * host/proxy and the correct authentication
- * method. conn->data->state.authdone is set to TRUE when authentication is
- * done.
- *
- * @param conn all information about the current connection
- * @param request pointer to the request keyword
- * @param path pointer to the requested path
- * @param proxytunnel boolean if this is the request setting up a "proxy
- * tunnel"
- *
- * @returns CURLcode
- */
-CURLcode
-Curl_http_output_auth(struct connectdata *conn,
- const char *request,
- const char *path,
- bool proxytunnel); /* TRUE if this is the request setting
- up the proxy tunnel */
-
-#endif /* HEADER_CURL_HTTP_H */
+ struct connectdata *conn,
+ ssize_t *nread,
+ bool *stop_reading);
+
+/**
+ * Curl_http_output_auth() setups the authentication headers for the
+ * host/proxy and the correct authentication
+ * method. conn->data->state.authdone is set to TRUE when authentication is
+ * done.
+ *
+ * @param conn all information about the current connection
+ * @param request pointer to the request keyword
+ * @param path pointer to the requested path
+ * @param proxytunnel boolean if this is the request setting up a "proxy
+ * tunnel"
+ *
+ * @returns CURLcode
+ */
+CURLcode
+Curl_http_output_auth(struct connectdata *conn,
+ const char *request,
+ const char *path,
+ bool proxytunnel); /* TRUE if this is the request setting
+ up the proxy tunnel */
+
+#endif /* HEADER_CURL_HTTP_H */
diff --git a/contrib/libs/curl/lib/http2.c b/contrib/libs/curl/lib/http2.c
index 86eb97911b..b138fb4b0f 100644
--- a/contrib/libs/curl/lib/http2.c
+++ b/contrib/libs/curl/lib/http2.c
@@ -1,35 +1,35 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef USE_NGHTTP2
-#include <nghttp2/nghttp2.h>
-#include "urldata.h"
-#include "http2.h"
-#include "http.h"
-#include "sendf.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef USE_NGHTTP2
+#include <nghttp2/nghttp2.h>
+#include "urldata.h"
+#include "http2.h"
+#include "http.h"
+#include "sendf.h"
#include "select.h"
-#include "curl_base64.h"
+#include "curl_base64.h"
#include "strcase.h"
#include "multiif.h"
#include "url.h"
@@ -39,9 +39,9 @@
#include "dynbuf.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
#define H2_BUFSIZE 32768
#if (NGHTTP2_VERSION_NUM < 0x010c00)
@@ -74,7 +74,7 @@ static int h2_process_pending_input(struct connectdata *conn,
struct http_conn *httpc,
CURLcode *err);
-/*
+/*
* Curl_http2_init_state() is called when the easy handle is created and
* allows for HTTP/2 specific init of state.
*/
@@ -327,32 +327,32 @@ static const struct Curl_handler Curl_handler_http2_ssl = {
};
/*
- * Store nghttp2 version info in this buffer, Prefix with a space. Return
- * total length written.
- */
-int Curl_http2_ver(char *p, size_t len)
-{
- nghttp2_info *h2 = nghttp2_version(0);
+ * Store nghttp2 version info in this buffer, Prefix with a space. Return
+ * total length written.
+ */
+int Curl_http2_ver(char *p, size_t len)
+{
+ nghttp2_info *h2 = nghttp2_version(0);
return msnprintf(p, len, "nghttp2/%s", h2->version_str);
-}
-
-/*
- * The implementation of nghttp2_send_callback type. Here we write |data| with
- * size |length| to the network and return the number of bytes actually
- * written. See the documentation of nghttp2_send_callback for the details.
- */
-static ssize_t send_callback(nghttp2_session *h2,
- const uint8_t *data, size_t length, int flags,
- void *userp)
-{
- struct connectdata *conn = (struct connectdata *)userp;
+}
+
+/*
+ * The implementation of nghttp2_send_callback type. Here we write |data| with
+ * size |length| to the network and return the number of bytes actually
+ * written. See the documentation of nghttp2_send_callback for the details.
+ */
+static ssize_t send_callback(nghttp2_session *h2,
+ const uint8_t *data, size_t length, int flags,
+ void *userp)
+{
+ struct connectdata *conn = (struct connectdata *)userp;
struct http_conn *c = &conn->proto.httpc;
- ssize_t written;
+ ssize_t written;
CURLcode result = CURLE_OK;
- (void)h2;
- (void)flags;
-
+ (void)h2;
+ (void)flags;
+
if(!c->send_underlying)
/* called before setup properly! */
return NGHTTP2_ERR_CALLBACK_FAILURE;
@@ -365,16 +365,16 @@ static ssize_t send_callback(nghttp2_session *h2,
}
if(written == -1) {
- failf(conn->data, "Failed sending HTTP2 data");
- return NGHTTP2_ERR_CALLBACK_FAILURE;
- }
+ failf(conn->data, "Failed sending HTTP2 data");
+ return NGHTTP2_ERR_CALLBACK_FAILURE;
+ }
if(!written)
- return NGHTTP2_ERR_WOULDBLOCK;
-
- return written;
-}
-
+ return NGHTTP2_ERR_WOULDBLOCK;
+
+ return written;
+}
+
/* We pass a pointer to this struct in the push callback, but the contents of
the struct are hidden from the user. */
@@ -383,11 +383,11 @@ struct curl_pushheaders {
const nghttp2_push_promise *frame;
};
-/*
+/*
* push header access function. Only to be used from within the push callback
- */
+ */
char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num)
-{
+{
/* Verify that we got a good easy handle in the push header struct, mostly to
detect rubbish input fast(er). */
if(!h || !GOOD_EASY_HANDLE(h->data))
@@ -627,7 +627,7 @@ static void multi_connchanged(struct Curl_multi *multi)
static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
void *userp)
{
- struct connectdata *conn = (struct connectdata *)userp;
+ struct connectdata *conn = (struct connectdata *)userp;
struct http_conn *httpc = &conn->proto.httpc;
struct Curl_easy *data_s = NULL;
struct HTTP *stream = NULL;
@@ -773,9 +773,9 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
size_t nread;
struct connectdata *conn = (struct connectdata *)userp;
(void)session;
- (void)flags;
+ (void)flags;
(void)data;
-
+
DEBUGASSERT(stream_id); /* should never be a zero stream ID here */
/* get the stream from the hash based on Stream ID */
@@ -783,7 +783,7 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
if(!data_s)
/* Receiving a Stream ID not in the hash should not happen, this is an
internal error more than anything else! */
- return NGHTTP2_ERR_CALLBACK_FAILURE;
+ return NGHTTP2_ERR_CALLBACK_FAILURE;
stream = data_s->req.p.http;
if(!stream)
@@ -816,8 +816,8 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
data_s->conn->proto.httpc.pause_stream_id = stream_id;
return NGHTTP2_ERR_PAUSE;
- }
-
+ }
+
/* pause execution of nghttp2 if we received data for another handle
in order to process them first. */
if(conn->data != data_s) {
@@ -1127,9 +1127,9 @@ static ssize_t data_source_read_callback(nghttp2_session *session,
"returns %zu bytes stream %u\n",
nread, stream_id));
- return nread;
-}
-
+ return nread;
+}
+
#if !defined(CURL_DISABLE_VERBOSE_STRINGS)
static int error_callback(nghttp2_session *session,
const char *msg,
@@ -1142,7 +1142,7 @@ static int error_callback(nghttp2_session *session,
return 0;
}
#endif
-
+
static void populate_settings(struct connectdata *conn,
struct http_conn *httpc)
{
@@ -1211,15 +1211,15 @@ void Curl_http2_done(struct Curl_easy *data, bool premature)
}
}
-/*
+/*
* Initialize nghttp2 for a Curl connection
- */
+ */
static CURLcode http2_init(struct connectdata *conn)
{
if(!conn->proto.httpc.h2) {
int rc;
nghttp2_session_callbacks *callbacks;
-
+
conn->proto.httpc.inbuf = malloc(H2_BUFSIZE);
if(conn->proto.httpc.inbuf == NULL)
return CURLE_OUT_OF_MEMORY;
@@ -1263,52 +1263,52 @@ static CURLcode http2_init(struct connectdata *conn)
return CURLE_OK;
}
-/*
- * Append headers to ask for a HTTP1.1 to HTTP2 upgrade.
- */
+/*
+ * Append headers to ask for a HTTP1.1 to HTTP2 upgrade.
+ */
CURLcode Curl_http2_request_upgrade(struct dynbuf *req,
struct connectdata *conn)
-{
- CURLcode result;
- ssize_t binlen;
- char *base64;
- size_t blen;
+{
+ CURLcode result;
+ ssize_t binlen;
+ char *base64;
+ size_t blen;
struct SingleRequest *k = &conn->data->req;
uint8_t *binsettings = conn->proto.httpc.binsettings;
struct http_conn *httpc = &conn->proto.httpc;
-
+
populate_settings(conn, httpc);
-
- /* this returns number of bytes it wrote */
+
+ /* this returns number of bytes it wrote */
binlen = nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN,
httpc->local_settings,
httpc->local_settings_num);
if(binlen <= 0) {
- failf(conn->data, "nghttp2 unexpectedly failed on pack_settings_payload");
+ failf(conn->data, "nghttp2 unexpectedly failed on pack_settings_payload");
Curl_dyn_free(req);
- return CURLE_FAILED_INIT;
- }
+ return CURLE_FAILED_INIT;
+ }
conn->proto.httpc.binlen = binlen;
-
+
result = Curl_base64url_encode(conn->data, (const char *)binsettings, binlen,
&base64, &blen);
if(result) {
Curl_dyn_free(req);
- return result;
+ return result;
}
-
+
result = Curl_dyn_addf(req,
"Connection: Upgrade, HTTP2-Settings\r\n"
"Upgrade: %s\r\n"
"HTTP2-Settings: %s\r\n",
NGHTTP2_CLEARTEXT_PROTO_VERSION_ID, base64);
- free(base64);
-
+ free(base64);
+
k->upgr101 = UPGR101_REQUESTED;
- return result;
-}
-
+ return result;
+}
+
/*
* Returns nonzero if current HTTP/2 session should be closed.
*/
diff --git a/contrib/libs/curl/lib/http2.h b/contrib/libs/curl/lib/http2.h
index b8788a3373..43a6863abe 100644
--- a/contrib/libs/curl/lib/http2.h
+++ b/contrib/libs/curl/lib/http2.h
@@ -1,42 +1,42 @@
-#ifndef HEADER_CURL_HTTP2_H
-#define HEADER_CURL_HTTP2_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HTTP2_H
+#define HEADER_CURL_HTTP2_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef USE_NGHTTP2
-#include "http.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef USE_NGHTTP2
+#include "http.h"
/* value for MAX_CONCURRENT_STREAMS we use until we get an updated setting
from the peer */
#define DEFAULT_MAX_CONCURRENT_STREAMS 13
-/*
- * Store nghttp2 version info in this buffer, Prefix with a space. Return
- * total length written.
- */
-int Curl_http2_ver(char *p, size_t len);
-
+/*
+ * Store nghttp2 version info in this buffer, Prefix with a space. Return
+ * total length written.
+ */
+int Curl_http2_ver(char *p, size_t len);
+
const char *Curl_http2_strerror(uint32_t err);
CURLcode Curl_http2_init(struct connectdata *conn);
@@ -62,7 +62,7 @@ CURLcode Curl_http2_stream_pause(struct Curl_easy *data, bool pause);
/* returns true if the HTTP/2 stream error was HTTP_1_1_REQUIRED */
bool Curl_h2_http_1_1_error(struct connectdata *conn);
-#else /* USE_NGHTTP2 */
+#else /* USE_NGHTTP2 */
#define Curl_http2_request_upgrade(x,y) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_setup(x) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_switched(x,y,z) CURLE_UNSUPPORTED_PROTOCOL
@@ -77,6 +77,6 @@ bool Curl_h2_http_1_1_error(struct connectdata *conn);
#define Curl_http2_cleanup_dependencies(x)
#define Curl_http2_stream_pause(x, y)
#define Curl_h2_http_1_1_error(x) 0
-#endif
-
-#endif /* HEADER_CURL_HTTP2_H */
+#endif
+
+#endif /* HEADER_CURL_HTTP2_H */
diff --git a/contrib/libs/curl/lib/http_chunks.c b/contrib/libs/curl/lib/http_chunks.c
index f03c761288..498481475c 100644
--- a/contrib/libs/curl/lib/http_chunks.c
+++ b/contrib/libs/curl/lib/http_chunks.c
@@ -1,324 +1,324 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_HTTP
-
-#include "urldata.h" /* it includes http_chunks.h */
-#include "sendf.h" /* for the client write stuff */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_HTTP
+
+#include "urldata.h" /* it includes http_chunks.h */
+#include "sendf.h" /* for the client write stuff */
#include "dynbuf.h"
-#include "content_encoding.h"
-#include "http.h"
-#include "non-ascii.h" /* for Curl_convert_to_network prototype */
+#include "content_encoding.h"
+#include "http.h"
+#include "non-ascii.h" /* for Curl_convert_to_network prototype */
#include "strtoofft.h"
#include "warnless.h"
-
+
/* The last #include files should be: */
#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
- * Chunk format (simplified):
- *
- * <HEX SIZE>[ chunk extension ] CRLF
- * <DATA> CRLF
- *
- * Highlights from RFC2616 section 3.6 say:
-
- The chunked encoding modifies the body of a message in order to
- transfer it as a series of chunks, each with its own size indicator,
- followed by an OPTIONAL trailer containing entity-header fields. This
- allows dynamically produced content to be transferred along with the
- information necessary for the recipient to verify that it has
- received the full message.
-
- Chunked-Body = *chunk
- last-chunk
- trailer
- CRLF
-
- chunk = chunk-size [ chunk-extension ] CRLF
- chunk-data CRLF
- chunk-size = 1*HEX
- last-chunk = 1*("0") [ chunk-extension ] CRLF
-
- chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
- chunk-ext-name = token
- chunk-ext-val = token | quoted-string
- chunk-data = chunk-size(OCTET)
- trailer = *(entity-header CRLF)
-
- The chunk-size field is a string of hex digits indicating the size of
- the chunk. The chunked encoding is ended by any chunk whose size is
- zero, followed by the trailer, which is terminated by an empty line.
-
- */
-
+#include "memdebug.h"
+
+/*
+ * Chunk format (simplified):
+ *
+ * <HEX SIZE>[ chunk extension ] CRLF
+ * <DATA> CRLF
+ *
+ * Highlights from RFC2616 section 3.6 say:
+
+ The chunked encoding modifies the body of a message in order to
+ transfer it as a series of chunks, each with its own size indicator,
+ followed by an OPTIONAL trailer containing entity-header fields. This
+ allows dynamically produced content to be transferred along with the
+ information necessary for the recipient to verify that it has
+ received the full message.
+
+ Chunked-Body = *chunk
+ last-chunk
+ trailer
+ CRLF
+
+ chunk = chunk-size [ chunk-extension ] CRLF
+ chunk-data CRLF
+ chunk-size = 1*HEX
+ last-chunk = 1*("0") [ chunk-extension ] CRLF
+
+ chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
+ chunk-ext-name = token
+ chunk-ext-val = token | quoted-string
+ chunk-data = chunk-size(OCTET)
+ trailer = *(entity-header CRLF)
+
+ The chunk-size field is a string of hex digits indicating the size of
+ the chunk. The chunked encoding is ended by any chunk whose size is
+ zero, followed by the trailer, which is terminated by an empty line.
+
+ */
+
#ifdef CURL_DOES_CONVERSIONS
-/* Check for an ASCII hex digit.
+/* Check for an ASCII hex digit.
We avoid the use of ISXDIGIT to accommodate non-ASCII hosts. */
static bool Curl_isxdigit_ascii(char digit)
-{
+{
return (digit >= 0x30 && digit <= 0x39) /* 0-9 */
- || (digit >= 0x41 && digit <= 0x46) /* A-F */
+ || (digit >= 0x41 && digit <= 0x46) /* A-F */
|| (digit >= 0x61 && digit <= 0x66); /* a-f */
-}
+}
#else
#define Curl_isxdigit_ascii(x) Curl_isxdigit(x)
#endif
-
-void Curl_httpchunk_init(struct connectdata *conn)
-{
- struct Curl_chunker *chunk = &conn->chunk;
+
+void Curl_httpchunk_init(struct connectdata *conn)
+{
+ struct Curl_chunker *chunk = &conn->chunk;
chunk->hexindex = 0; /* start at 0 */
chunk->dataleft = 0; /* no data left yet! */
- chunk->state = CHUNK_HEX; /* we get hex first! */
+ chunk->state = CHUNK_HEX; /* we get hex first! */
Curl_dyn_init(&conn->trailer, DYN_H1_TRAILER);
-}
-
-/*
- * chunk_read() returns a OK for normal operations, or a positive return code
- * for errors. STOP means this sequence of chunks is complete. The 'wrote'
- * argument is set to tell the caller how many bytes we actually passed to the
- * client (for byte-counting and whatever).
- *
- * The states and the state-machine is further explained in the header file.
- *
- * This function always uses ASCII hex values to accommodate non-ASCII hosts.
- * For example, 0x0d and 0x0a are used instead of '\r' and '\n'.
- */
-CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
- char *datap,
- ssize_t datalen,
+}
+
+/*
+ * chunk_read() returns a OK for normal operations, or a positive return code
+ * for errors. STOP means this sequence of chunks is complete. The 'wrote'
+ * argument is set to tell the caller how many bytes we actually passed to the
+ * client (for byte-counting and whatever).
+ *
+ * The states and the state-machine is further explained in the header file.
+ *
+ * This function always uses ASCII hex values to accommodate non-ASCII hosts.
+ * For example, 0x0d and 0x0a are used instead of '\r' and '\n'.
+ */
+CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
+ char *datap,
+ ssize_t datalen,
ssize_t *wrotep,
CURLcode *extrap)
-{
+{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct Curl_chunker *ch = &conn->chunk;
- struct SingleRequest *k = &data->req;
- size_t piece;
+ struct Curl_chunker *ch = &conn->chunk;
+ struct SingleRequest *k = &data->req;
+ size_t piece;
curl_off_t length = (curl_off_t)datalen;
- size_t *wrote = (size_t *)wrotep;
-
- *wrote = 0; /* nothing's written yet */
-
- /* the original data is written to the client, but we go on with the
- chunk read process, to properly calculate the content length*/
- if(data->set.http_te_skip && !k->ignorebody) {
- result = Curl_client_write(conn, CLIENTWRITE_BODY, datap, datalen);
+ size_t *wrote = (size_t *)wrotep;
+
+ *wrote = 0; /* nothing's written yet */
+
+ /* the original data is written to the client, but we go on with the
+ chunk read process, to properly calculate the content length*/
+ if(data->set.http_te_skip && !k->ignorebody) {
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, datap, datalen);
if(result) {
*extrap = result;
return CHUNKE_PASSTHRU_ERROR;
}
- }
-
- while(length) {
- switch(ch->state) {
- case CHUNK_HEX:
+ }
+
+ while(length) {
+ switch(ch->state) {
+ case CHUNK_HEX:
if(Curl_isxdigit_ascii(*datap)) {
- if(ch->hexindex < MAXNUM_SIZE) {
- ch->hexbuffer[ch->hexindex] = *datap;
- datap++;
- length--;
- ch->hexindex++;
- }
- else {
- return CHUNKE_TOO_LONG_HEX; /* longer hex than we support */
- }
- }
- else {
+ if(ch->hexindex < MAXNUM_SIZE) {
+ ch->hexbuffer[ch->hexindex] = *datap;
+ datap++;
+ length--;
+ ch->hexindex++;
+ }
+ else {
+ return CHUNKE_TOO_LONG_HEX; /* longer hex than we support */
+ }
+ }
+ else {
char *endptr;
if(0 == ch->hexindex)
- /* This is illegal data, we received junk where we expected
- a hexadecimal digit. */
- return CHUNKE_ILLEGAL_HEX;
+ /* This is illegal data, we received junk where we expected
+ a hexadecimal digit. */
+ return CHUNKE_ILLEGAL_HEX;
- /* length and datap are unmodified */
+ /* length and datap are unmodified */
ch->hexbuffer[ch->hexindex] = 0;
-
- /* convert to host encoding before calling strtoul */
- result = Curl_convert_from_network(conn->data, ch->hexbuffer,
- ch->hexindex);
- if(result) {
- /* Curl_convert_from_network calls failf if unsuccessful */
- /* Treat it as a bad hex character */
+
+ /* convert to host encoding before calling strtoul */
+ result = Curl_convert_from_network(conn->data, ch->hexbuffer,
+ ch->hexindex);
+ if(result) {
+ /* Curl_convert_from_network calls failf if unsuccessful */
+ /* Treat it as a bad hex character */
return CHUNKE_ILLEGAL_HEX;
- }
-
+ }
+
if(curlx_strtoofft(ch->hexbuffer, &endptr, 16, &ch->datasize))
return CHUNKE_ILLEGAL_HEX;
ch->state = CHUNK_LF; /* now wait for the CRLF */
- }
- break;
-
+ }
+ break;
+
case CHUNK_LF:
/* waiting for the LF after a chunk size */
- if(*datap == 0x0a) {
- /* we're now expecting data to come, unless size was zero! */
- if(0 == ch->datasize) {
- ch->state = CHUNK_TRAILER; /* now check for trailers */
- }
+ if(*datap == 0x0a) {
+ /* we're now expecting data to come, unless size was zero! */
+ if(0 == ch->datasize) {
+ ch->state = CHUNK_TRAILER; /* now check for trailers */
+ }
else
- ch->state = CHUNK_DATA;
- }
-
- datap++;
- length--;
- break;
-
- case CHUNK_DATA:
+ ch->state = CHUNK_DATA;
+ }
+
+ datap++;
+ length--;
+ break;
+
+ case CHUNK_DATA:
/* We expect 'datasize' of data. We have 'length' right now, it can be
more or less than 'datasize'. Get the smallest piece.
- */
+ */
piece = curlx_sotouz((ch->datasize >= length)?length:ch->datasize);
-
- /* Write the data portion available */
+
+ /* Write the data portion available */
if(!conn->data->set.http_te_skip && !k->ignorebody) {
if(!conn->data->set.http_ce_skip && k->writer_stack)
result = Curl_unencode_write(conn, k->writer_stack, datap, piece);
else
result = Curl_client_write(conn, CLIENTWRITE_BODY, datap, piece);
-
+
if(result) {
*extrap = result;
return CHUNKE_PASSTHRU_ERROR;
}
- }
-
- *wrote += piece;
- ch->datasize -= piece; /* decrease amount left to expect */
- datap += piece; /* move read pointer forward */
- length -= piece; /* decrease space left in this round */
-
- if(0 == ch->datasize)
- /* end of data this round, we now expect a trailing CRLF */
- ch->state = CHUNK_POSTLF;
- break;
-
- case CHUNK_POSTLF:
- if(*datap == 0x0a) {
+ }
+
+ *wrote += piece;
+ ch->datasize -= piece; /* decrease amount left to expect */
+ datap += piece; /* move read pointer forward */
+ length -= piece; /* decrease space left in this round */
+
+ if(0 == ch->datasize)
+ /* end of data this round, we now expect a trailing CRLF */
+ ch->state = CHUNK_POSTLF;
+ break;
+
+ case CHUNK_POSTLF:
+ if(*datap == 0x0a) {
/* The last one before we go back to hex state and start all over. */
Curl_httpchunk_init(conn); /* sets state back to CHUNK_HEX */
- }
+ }
else if(*datap != 0x0d)
- return CHUNKE_BAD_CHUNK;
+ return CHUNKE_BAD_CHUNK;
datap++;
length--;
- break;
-
- case CHUNK_TRAILER:
+ break;
+
+ case CHUNK_TRAILER:
if((*datap == 0x0d) || (*datap == 0x0a)) {
char *tr = Curl_dyn_ptr(&conn->trailer);
- /* this is the end of a trailer, but if the trailer was zero bytes
- there was no trailer and we move on */
-
+ /* this is the end of a trailer, but if the trailer was zero bytes
+ there was no trailer and we move on */
+
if(tr) {
size_t trlen;
result = Curl_dyn_add(&conn->trailer, (char *)"\x0d\x0a");
if(result)
return CHUNKE_OUT_OF_MEMORY;
-
+
tr = Curl_dyn_ptr(&conn->trailer);
trlen = Curl_dyn_len(&conn->trailer);
- /* Convert to host encoding before calling Curl_client_write */
+ /* Convert to host encoding before calling Curl_client_write */
result = Curl_convert_from_network(conn->data, tr, trlen);
- if(result)
- /* Curl_convert_from_network calls failf if unsuccessful */
- /* Treat it as a bad chunk */
- return CHUNKE_BAD_CHUNK;
-
- if(!data->set.http_te_skip) {
+ if(result)
+ /* Curl_convert_from_network calls failf if unsuccessful */
+ /* Treat it as a bad chunk */
+ return CHUNKE_BAD_CHUNK;
+
+ if(!data->set.http_te_skip) {
result = Curl_client_write(conn, CLIENTWRITE_HEADER, tr, trlen);
if(result) {
*extrap = result;
return CHUNKE_PASSTHRU_ERROR;
}
- }
+ }
Curl_dyn_reset(&conn->trailer);
- ch->state = CHUNK_TRAILER_CR;
+ ch->state = CHUNK_TRAILER_CR;
if(*datap == 0x0a)
/* already on the LF */
break;
- }
- else {
- /* no trailer, we're on the final CRLF pair */
- ch->state = CHUNK_TRAILER_POSTCR;
- break; /* don't advance the pointer */
- }
- }
- else {
+ }
+ else {
+ /* no trailer, we're on the final CRLF pair */
+ ch->state = CHUNK_TRAILER_POSTCR;
+ break; /* don't advance the pointer */
+ }
+ }
+ else {
result = Curl_dyn_addn(&conn->trailer, datap, 1);
if(result)
return CHUNKE_OUT_OF_MEMORY;
- }
- datap++;
- length--;
- break;
-
- case CHUNK_TRAILER_CR:
- if(*datap == 0x0a) {
- ch->state = CHUNK_TRAILER_POSTCR;
- datap++;
- length--;
- }
- else
- return CHUNKE_BAD_CHUNK;
- break;
-
- case CHUNK_TRAILER_POSTCR:
- /* We enter this state when a CR should arrive so we expect to
- have to first pass a CR before we wait for LF */
+ }
+ datap++;
+ length--;
+ break;
+
+ case CHUNK_TRAILER_CR:
+ if(*datap == 0x0a) {
+ ch->state = CHUNK_TRAILER_POSTCR;
+ datap++;
+ length--;
+ }
+ else
+ return CHUNKE_BAD_CHUNK;
+ break;
+
+ case CHUNK_TRAILER_POSTCR:
+ /* We enter this state when a CR should arrive so we expect to
+ have to first pass a CR before we wait for LF */
if((*datap != 0x0d) && (*datap != 0x0a)) {
- /* not a CR then it must be another header in the trailer */
- ch->state = CHUNK_TRAILER;
- break;
- }
- if(*datap == 0x0d) {
+ /* not a CR then it must be another header in the trailer */
+ ch->state = CHUNK_TRAILER;
+ break;
+ }
+ if(*datap == 0x0d) {
/* skip if CR */
- datap++;
- length--;
- }
+ datap++;
+ length--;
+ }
/* now wait for the final LF */
ch->state = CHUNK_STOP;
- break;
-
- case CHUNK_STOP:
- if(*datap == 0x0a) {
- length--;
-
- /* Record the length of any data left in the end of the buffer
- even if there's no more chunks to read */
+ break;
+
+ case CHUNK_STOP:
+ if(*datap == 0x0a) {
+ length--;
+
+ /* Record the length of any data left in the end of the buffer
+ even if there's no more chunks to read */
ch->dataleft = curlx_sotouz(length);
-
- return CHUNKE_STOP; /* return stop */
- }
- else
- return CHUNKE_BAD_CHUNK;
- }
- }
- return CHUNKE_OK;
-}
+
+ return CHUNKE_STOP; /* return stop */
+ }
+ else
+ return CHUNKE_BAD_CHUNK;
+ }
+ }
+ return CHUNKE_OK;
+}
const char *Curl_chunked_strerror(CHUNKcode code)
{
@@ -341,4 +341,4 @@ const char *Curl_chunked_strerror(CHUNKcode code)
}
}
-#endif /* CURL_DISABLE_HTTP */
+#endif /* CURL_DISABLE_HTTP */
diff --git a/contrib/libs/curl/lib/http_chunks.h b/contrib/libs/curl/lib/http_chunks.h
index 08dce5c1ad..c8f072a2de 100644
--- a/contrib/libs/curl/lib/http_chunks.h
+++ b/contrib/libs/curl/lib/http_chunks.h
@@ -1,99 +1,99 @@
-#ifndef HEADER_CURL_HTTP_CHUNKS_H
-#define HEADER_CURL_HTTP_CHUNKS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HTTP_CHUNKS_H
+#define HEADER_CURL_HTTP_CHUNKS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
struct connectdata;
-/*
- * The longest possible hexadecimal number we support in a chunked transfer.
- * Weird enough, RFC2616 doesn't set a maximum size! Since we use strtoul()
- * to convert it, we "only" support 2^32 bytes chunk data.
- */
-#define MAXNUM_SIZE 16
-
-typedef enum {
+/*
+ * The longest possible hexadecimal number we support in a chunked transfer.
+ * Weird enough, RFC2616 doesn't set a maximum size! Since we use strtoul()
+ * to convert it, we "only" support 2^32 bytes chunk data.
+ */
+#define MAXNUM_SIZE 16
+
+typedef enum {
/* await and buffer all hexadecimal digits until we get one that isn't a
hexadecimal digit. When done, we go CHUNK_LF */
- CHUNK_HEX,
-
+ CHUNK_HEX,
+
/* wait for LF, ignore all else */
CHUNK_LF,
-
- /* We eat the amount of data specified. When done, we move on to the
- POST_CR state. */
- CHUNK_DATA,
-
+
+ /* We eat the amount of data specified. When done, we move on to the
+ POST_CR state. */
+ CHUNK_DATA,
+
/* POSTLF should get a CR and then a LF and nothing else, then move back to
HEX as the CRLF combination marks the end of a chunk. A missing CR is no
big deal. */
- CHUNK_POSTLF,
-
+ CHUNK_POSTLF,
+
/* Used to mark that we're out of the game. NOTE: that there's a 'dataleft'
field in the struct that will tell how many bytes that were not passed to
the client in the end of the last buffer! */
- CHUNK_STOP,
-
- /* At this point optional trailer headers can be found, unless the next line
- is CRLF */
- CHUNK_TRAILER,
-
- /* A trailer CR has been found - next state is CHUNK_TRAILER_POSTCR.
- Next char must be a LF */
- CHUNK_TRAILER_CR,
-
- /* A trailer LF must be found now, otherwise CHUNKE_BAD_CHUNK will be
- signalled If this is an empty trailer CHUNKE_STOP will be signalled.
- Otherwise the trailer will be broadcasted via Curl_client_write() and the
- next state will be CHUNK_TRAILER */
+ CHUNK_STOP,
+
+ /* At this point optional trailer headers can be found, unless the next line
+ is CRLF */
+ CHUNK_TRAILER,
+
+ /* A trailer CR has been found - next state is CHUNK_TRAILER_POSTCR.
+ Next char must be a LF */
+ CHUNK_TRAILER_CR,
+
+ /* A trailer LF must be found now, otherwise CHUNKE_BAD_CHUNK will be
+ signalled If this is an empty trailer CHUNKE_STOP will be signalled.
+ Otherwise the trailer will be broadcasted via Curl_client_write() and the
+ next state will be CHUNK_TRAILER */
CHUNK_TRAILER_POSTCR
-} ChunkyState;
-
-typedef enum {
- CHUNKE_STOP = -1,
- CHUNKE_OK = 0,
- CHUNKE_TOO_LONG_HEX = 1,
- CHUNKE_ILLEGAL_HEX,
- CHUNKE_BAD_CHUNK,
- CHUNKE_BAD_ENCODING,
- CHUNKE_OUT_OF_MEMORY,
+} ChunkyState;
+
+typedef enum {
+ CHUNKE_STOP = -1,
+ CHUNKE_OK = 0,
+ CHUNKE_TOO_LONG_HEX = 1,
+ CHUNKE_ILLEGAL_HEX,
+ CHUNKE_BAD_CHUNK,
+ CHUNKE_BAD_ENCODING,
+ CHUNKE_OUT_OF_MEMORY,
CHUNKE_PASSTHRU_ERROR, /* Curl_httpchunk_read() returns a CURLcode to use */
- CHUNKE_LAST
-} CHUNKcode;
-
+ CHUNKE_LAST
+} CHUNKcode;
+
const char *Curl_chunked_strerror(CHUNKcode code);
-struct Curl_chunker {
- char hexbuffer[ MAXNUM_SIZE + 1];
- int hexindex;
- ChunkyState state;
+struct Curl_chunker {
+ char hexbuffer[ MAXNUM_SIZE + 1];
+ int hexindex;
+ ChunkyState state;
curl_off_t datasize;
- size_t dataleft; /* untouched data amount at the end of the last buffer */
-};
-
+ size_t dataleft; /* untouched data amount at the end of the last buffer */
+};
+
/* The following functions are defined in http_chunks.c */
void Curl_httpchunk_init(struct connectdata *conn);
CHUNKcode Curl_httpchunk_read(struct connectdata *conn, char *datap,
ssize_t length, ssize_t *wrote,
CURLcode *passthru);
-#endif /* HEADER_CURL_HTTP_CHUNKS_H */
+#endif /* HEADER_CURL_HTTP_CHUNKS_H */
diff --git a/contrib/libs/curl/lib/http_digest.c b/contrib/libs/curl/lib/http_digest.c
index 36727b35f0..dfa40dcb61 100644
--- a/contrib/libs/curl/lib/http_digest.c
+++ b/contrib/libs/curl/lib/http_digest.c
@@ -1,99 +1,99 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
-
-#include "urldata.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
+
+#include "urldata.h"
#include "strcase.h"
#include "vauth/vauth.h"
-#include "http_digest.h"
+#include "http_digest.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* Test example headers:
-
-WWW-Authenticate: Digest realm="testrealm", nonce="1053604598"
-Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598"
-
-*/
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* Test example headers:
+
+WWW-Authenticate: Digest realm="testrealm", nonce="1053604598"
+Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598"
+
+*/
+
CURLcode Curl_input_digest(struct connectdata *conn,
bool proxy,
const char *header) /* rest of the *-authenticate:
header */
-{
+{
struct Curl_easy *data = conn->data;
-
+
/* Point to the correct struct with this */
struct digestdata *digest;
- if(proxy) {
+ if(proxy) {
digest = &data->state.proxydigest;
- }
- else {
+ }
+ else {
digest = &data->state.digest;
- }
-
+ }
+
if(!checkprefix("Digest", header))
return CURLE_BAD_CONTENT_ENCODING;
header += strlen("Digest");
- while(*header && ISSPACE(*header))
- header++;
-
+ while(*header && ISSPACE(*header))
+ header++;
+
return Curl_auth_decode_digest_http_message(header, digest);
-}
-
-CURLcode Curl_output_digest(struct connectdata *conn,
- bool proxy,
- const unsigned char *request,
- const unsigned char *uripath)
-{
+}
+
+CURLcode Curl_output_digest(struct connectdata *conn,
+ bool proxy,
+ const unsigned char *request,
+ const unsigned char *uripath)
+{
CURLcode result;
struct Curl_easy *data = conn->data;
unsigned char *path = NULL;
- char *tmp = NULL;
+ char *tmp = NULL;
char *response;
size_t len;
bool have_chlg;
/* Point to the address of the pointer that holds the string to send to the
server, which is for a plain host or for a HTTP proxy */
- char **allocuserpwd;
+ char **allocuserpwd;
/* Point to the name and password for this */
- const char *userp;
- const char *passwdp;
+ const char *userp;
+ const char *passwdp;
/* Point to the correct struct with this */
struct digestdata *digest;
- struct auth *authp;
-
- if(proxy) {
+ struct auth *authp;
+
+ if(proxy) {
#ifdef CURL_DISABLE_PROXY
return CURLE_NOT_BUILT_IN;
#else
@@ -101,26 +101,26 @@ CURLcode Curl_output_digest(struct connectdata *conn,
allocuserpwd = &data->state.aptr.proxyuserpwd;
userp = conn->http_proxy.user;
passwdp = conn->http_proxy.passwd;
- authp = &data->state.authproxy;
+ authp = &data->state.authproxy;
#endif
- }
- else {
+ }
+ else {
digest = &data->state.digest;
allocuserpwd = &data->state.aptr.userpwd;
- userp = conn->user;
- passwdp = conn->passwd;
- authp = &data->state.authhost;
- }
-
- Curl_safefree(*allocuserpwd);
-
- /* not set means empty */
- if(!userp)
+ userp = conn->user;
+ passwdp = conn->passwd;
+ authp = &data->state.authhost;
+ }
+
+ Curl_safefree(*allocuserpwd);
+
+ /* not set means empty */
+ if(!userp)
userp = "";
-
- if(!passwdp)
+
+ if(!passwdp)
passwdp = "";
-
+
#if defined(USE_WINDOWS_SSPI)
have_chlg = digest->input_token ? TRUE : FALSE;
#else
@@ -128,58 +128,58 @@ CURLcode Curl_output_digest(struct connectdata *conn,
#endif
if(!have_chlg) {
- authp->done = FALSE;
- return CURLE_OK;
- }
-
- /* So IE browsers < v7 cut off the URI part at the query part when they
- evaluate the MD5 and some (IIS?) servers work with them so we may need to
- do the Digest IE-style. Note that the different ways cause different MD5
- sums to get sent.
-
- Apache servers can be set to do the Digest IE-style automatically using
- the BrowserMatch feature:
+ authp->done = FALSE;
+ return CURLE_OK;
+ }
+
+ /* So IE browsers < v7 cut off the URI part at the query part when they
+ evaluate the MD5 and some (IIS?) servers work with them so we may need to
+ do the Digest IE-style. Note that the different ways cause different MD5
+ sums to get sent.
+
+ Apache servers can be set to do the Digest IE-style automatically using
+ the BrowserMatch feature:
https://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
-
- Further details on Digest implementation differences:
- http://www.fngtps.com/2006/09/http-authentication
- */
-
+
+ Further details on Digest implementation differences:
+ http://www.fngtps.com/2006/09/http-authentication
+ */
+
if(authp->iestyle) {
tmp = strchr((char *)uripath, '?');
if(tmp) {
size_t urilen = tmp - (char *)uripath;
path = (unsigned char *) aprintf("%.*s", urilen, uripath);
}
- }
+ }
if(!tmp)
path = (unsigned char *) strdup((char *) uripath);
-
+
if(!path)
- return CURLE_OUT_OF_MEMORY;
-
+ return CURLE_OUT_OF_MEMORY;
+
result = Curl_auth_create_digest_http_message(data, userp, passwdp, request,
path, digest, &response, &len);
free(path);
if(result)
return result;
-
+
*allocuserpwd = aprintf("%sAuthorization: Digest %s\r\n",
proxy ? "Proxy-" : "",
response);
free(response);
- if(!*allocuserpwd)
- return CURLE_OUT_OF_MEMORY;
-
+ if(!*allocuserpwd)
+ return CURLE_OUT_OF_MEMORY;
+
authp->done = TRUE;
-
- return CURLE_OK;
-}
-
+
+ return CURLE_OK;
+}
+
void Curl_http_auth_cleanup_digest(struct Curl_easy *data)
-{
+{
Curl_auth_digest_cleanup(&data->state.digest);
Curl_auth_digest_cleanup(&data->state.proxydigest);
-}
-
-#endif
+}
+
+#endif
diff --git a/contrib/libs/curl/lib/http_digest.h b/contrib/libs/curl/lib/http_digest.h
index 7ed1d66583..f7001edec1 100644
--- a/contrib/libs/curl/lib/http_digest.h
+++ b/contrib/libs/curl/lib/http_digest.h
@@ -1,42 +1,42 @@
-#ifndef HEADER_CURL_HTTP_DIGEST_H
-#define HEADER_CURL_HTTP_DIGEST_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HTTP_DIGEST_H
+#define HEADER_CURL_HTTP_DIGEST_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
-/* this is for digest header input */
+/* this is for digest header input */
CURLcode Curl_input_digest(struct connectdata *conn,
bool proxy, const char *header);
-
-/* this is for creating digest header output */
-CURLcode Curl_output_digest(struct connectdata *conn,
- bool proxy,
- const unsigned char *request,
- const unsigned char *uripath);
-
+
+/* this is for creating digest header output */
+CURLcode Curl_output_digest(struct connectdata *conn,
+ bool proxy,
+ const unsigned char *request,
+ const unsigned char *uripath);
+
void Curl_http_auth_cleanup_digest(struct Curl_easy *data);
-
+
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_CRYPTO_AUTH */
-#endif /* HEADER_CURL_HTTP_DIGEST_H */
+#endif /* HEADER_CURL_HTTP_DIGEST_H */
diff --git a/contrib/libs/curl/lib/http_negotiate.c b/contrib/libs/curl/lib/http_negotiate.c
index 47375d36e3..872d172fc6 100644
--- a/contrib/libs/curl/lib/http_negotiate.c
+++ b/contrib/libs/curl/lib/http_negotiate.c
@@ -1,56 +1,56 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO)
-
-#include "urldata.h"
-#include "sendf.h"
-#include "http_negotiate.h"
+
+#include "urldata.h"
+#include "sendf.h"
+#include "http_negotiate.h"
#include "vauth/vauth.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy,
const char *header)
-{
+{
CURLcode result;
struct Curl_easy *data = conn->data;
- size_t len;
-
+ size_t len;
+
/* Point to the username, password, service and host */
const char *userp;
const char *passwdp;
const char *service;
const char *host;
-
+
/* Point to the correct struct with this */
struct negotiatedata *neg_ctx;
curlnegotiate state;
-
+
if(proxy) {
#ifndef CURL_DISABLE_PROXY
userp = conn->http_proxy.user;
@@ -63,8 +63,8 @@ CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy,
#else
return CURLE_NOT_BUILT_IN;
#endif
- }
- else {
+ }
+ else {
userp = conn->user;
passwdp = conn->passwd;
service = data->set.str[STRING_SERVICE_NAME] ?
@@ -72,21 +72,21 @@ CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy,
host = conn->host.name;
neg_ctx = &conn->negotiate;
state = conn->http_negotiate_state;
- }
-
+ }
+
/* Not set means empty */
if(!userp)
userp = "";
-
+
if(!passwdp)
passwdp = "";
-
+
/* Obtain the input token, if any */
header += strlen("Negotiate");
- while(*header && ISSPACE(*header))
- header++;
-
- len = strlen(header);
+ while(*header && ISSPACE(*header))
+ header++;
+
+ len = strlen(header);
neg_ctx->havenegdata = len != 0;
if(!len) {
if(state == GSS_AUTHSUCC) {
@@ -98,9 +98,9 @@ CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy,
negotiation mechanisms */
Curl_http_auth_cleanup_negotiate(conn);
return CURLE_LOGIN_DENIED;
- }
- }
-
+ }
+ }
+
/* Supports SSL channel binding for Windows ISS extended protection */
#if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS)
neg_ctx->sslContext = conn->sslContext;
@@ -109,15 +109,15 @@ CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy,
/* Initialize the security context and decode our challenge */
result = Curl_auth_decode_spnego_message(data, userp, passwdp, service,
host, header, neg_ctx);
-
+
if(result)
Curl_http_auth_cleanup_negotiate(conn);
-
+
return result;
-}
-
-CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
-{
+}
+
+CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
+{
struct negotiatedata *neg_ctx = proxy ? &conn->proxyneg :
&conn->negotiate;
struct auth *authp = proxy ? &conn->data->state.authproxy :
@@ -126,12 +126,12 @@ CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
&conn->http_negotiate_state;
struct Curl_easy *data = conn->data;
char *base64 = NULL;
- size_t len = 0;
- char *userp;
+ size_t len = 0;
+ char *userp;
CURLcode result;
-
+
authp->done = FALSE;
-
+
if(*state == GSS_AUTHRECV) {
if(neg_ctx->havenegdata) {
neg_ctx->havemultiplerequests = TRUE;
@@ -142,7 +142,7 @@ CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
neg_ctx->noauthpersist = !neg_ctx->havemultiplerequests;
}
}
-
+
if(neg_ctx->noauthpersist ||
(*state != GSS_AUTHDONE && *state != GSS_AUTHSUCC)) {
@@ -200,26 +200,26 @@ CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
}
#endif
#endif
- }
+ }
if(*state == GSS_AUTHDONE || *state == GSS_AUTHSUCC) {
/* connection is already authenticated,
* don't send a header in future requests */
authp->done = TRUE;
- }
-
+ }
+
neg_ctx->havenegdata = FALSE;
-
+
return CURLE_OK;
-}
-
+}
+
void Curl_http_auth_cleanup_negotiate(struct connectdata *conn)
-{
+{
conn->http_negotiate_state = GSS_AUTHNONE;
conn->proxy_negotiate_state = GSS_AUTHNONE;
Curl_auth_cleanup_spnego(&conn->negotiate);
Curl_auth_cleanup_spnego(&conn->proxyneg);
-}
-
+}
+
#endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */
diff --git a/contrib/libs/curl/lib/http_negotiate.h b/contrib/libs/curl/lib/http_negotiate.h
index 5ef5775685..cf1d007dce 100644
--- a/contrib/libs/curl/lib/http_negotiate.h
+++ b/contrib/libs/curl/lib/http_negotiate.h
@@ -1,40 +1,40 @@
-#ifndef HEADER_CURL_HTTP_NEGOTIATE_H
-#define HEADER_CURL_HTTP_NEGOTIATE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HTTP_NEGOTIATE_H
+#define HEADER_CURL_HTTP_NEGOTIATE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO)
-
-/* this is for Negotiate header input */
+
+/* this is for Negotiate header input */
CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy,
const char *header);
-
-/* this is for creating Negotiate header output */
-CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy);
-
+
+/* this is for creating Negotiate header output */
+CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy);
+
void Curl_http_auth_cleanup_negotiate(struct connectdata *conn);
-
+
#else /* !CURL_DISABLE_HTTP && USE_SPNEGO */
#define Curl_http_auth_cleanup_negotiate(x)
#endif
-
-#endif /* HEADER_CURL_HTTP_NEGOTIATE_H */
+
+#endif /* HEADER_CURL_HTTP_NEGOTIATE_H */
diff --git a/contrib/libs/curl/lib/http_proxy.c b/contrib/libs/curl/lib/http_proxy.c
index 61b8e2675d..4242251219 100644
--- a/contrib/libs/curl/lib/http_proxy.c
+++ b/contrib/libs/curl/lib/http_proxy.c
@@ -1,54 +1,54 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include "http_proxy.h"
-#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
-
-#include <curl/curl.h>
-#include "sendf.h"
-#include "http.h"
-#include "url.h"
-#include "select.h"
-#include "progress.h"
-#include "non-ascii.h"
-#include "connect.h"
-#include "curlx.h"
+#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
+
+#include <curl/curl.h>
+#include "sendf.h"
+#include "http.h"
+#include "url.h"
+#include "select.h"
+#include "progress.h"
+#include "non-ascii.h"
+#include "connect.h"
+#include "curlx.h"
#include "vtls/vtls.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
/*
* Perform SSL initialization for HTTPS proxy. Sets
* proxy_ssl_connected connection bit when complete. Can be
* called multiple times.
*/
static CURLcode https_proxy_connect(struct connectdata *conn, int sockindex)
-{
+{
#ifdef USE_SSL
CURLcode result = CURLE_OK;
DEBUGASSERT(conn->http_proxy.proxytype == CURLPROXY_HTTPS);
@@ -81,29 +81,29 @@ CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex)
return result; /* wait for HTTPS proxy SSL initialization to complete */
}
- if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
-#ifndef CURL_DISABLE_PROXY
- /* for [protocol] tunneled through HTTP proxy */
- struct HTTP http_proxy;
- void *prot_save;
+ if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
+#ifndef CURL_DISABLE_PROXY
+ /* for [protocol] tunneled through HTTP proxy */
+ struct HTTP http_proxy;
+ void *prot_save;
const char *hostname;
int remote_port;
- CURLcode result;
-
- /* BLOCKING */
- /* We want "seamless" operations through HTTP proxy tunnel */
-
- /* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the
- * member conn->proto.http; we want [protocol] through HTTP and we have
- * to change the member temporarily for connecting to the HTTP
- * proxy. After Curl_proxyCONNECT we have to set back the member to the
- * original pointer
- *
- * This function might be called several times in the multi interface case
+ CURLcode result;
+
+ /* BLOCKING */
+ /* We want "seamless" operations through HTTP proxy tunnel */
+
+ /* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the
+ * member conn->proto.http; we want [protocol] through HTTP and we have
+ * to change the member temporarily for connecting to the HTTP
+ * proxy. After Curl_proxyCONNECT we have to set back the member to the
+ * original pointer
+ *
+ * This function might be called several times in the multi interface case
* if the proxy's CONNECT response is not instant.
- */
+ */
prot_save = conn->data->req.p.http;
- memset(&http_proxy, 0, sizeof(http_proxy));
+ memset(&http_proxy, 0, sizeof(http_proxy));
conn->data->req.p.http = &http_proxy;
connkeep(conn, "HTTP proxy CONNECT");
@@ -126,25 +126,25 @@ CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex)
remote_port = conn->remote_port;
result = Curl_proxyCONNECT(conn, sockindex, hostname, remote_port);
conn->data->req.p.http = prot_save;
- if(CURLE_OK != result)
- return result;
+ if(CURLE_OK != result)
+ return result;
Curl_safefree(data->state.aptr.proxyuserpwd);
-#else
- return CURLE_NOT_BUILT_IN;
-#endif
- }
- /* no HTTP tunnel proxy, just return */
- return CURLE_OK;
-}
-
+#else
+ return CURLE_NOT_BUILT_IN;
+#endif
+ }
+ /* no HTTP tunnel proxy, just return */
+ return CURLE_OK;
+}
+
bool Curl_connect_complete(struct connectdata *conn)
{
return !conn->connect_state ||
(conn->connect_state->tunnel_state == TUNNEL_COMPLETE);
}
-
+
bool Curl_connect_ongoing(struct connectdata *conn)
-{
+{
return conn->connect_state &&
(conn->connect_state->tunnel_state != TUNNEL_COMPLETE);
}
@@ -188,49 +188,49 @@ static CURLcode CONNECT(struct connectdata *conn,
{
int subversion = 0;
struct Curl_easy *data = conn->data;
- struct SingleRequest *k = &data->req;
- CURLcode result;
- curl_socket_t tunnelsocket = conn->sock[sockindex];
+ struct SingleRequest *k = &data->req;
+ CURLcode result;
+ curl_socket_t tunnelsocket = conn->sock[sockindex];
struct http_connect_state *s = conn->connect_state;
char *linep;
size_t perline;
-
-#define SELECT_OK 0
-#define SELECT_ERROR 1
-
+
+#define SELECT_OK 0
+#define SELECT_ERROR 1
+
if(Curl_connect_complete(conn))
- return CURLE_OK; /* CONNECT is already completed */
-
- conn->bits.proxy_connect_closed = FALSE;
-
- do {
+ return CURLE_OK; /* CONNECT is already completed */
+
+ conn->bits.proxy_connect_closed = FALSE;
+
+ do {
timediff_t check;
if(TUNNEL_INIT == s->tunnel_state) {
- /* BEGIN CONNECT PHASE */
- char *host_port;
+ /* BEGIN CONNECT PHASE */
+ char *host_port;
struct dynbuf req;
-
+
infof(data, "Establish HTTP proxy tunnel to %s:%d\n",
- hostname, remote_port);
-
- /* This only happens if we've looped here due to authentication
- reasons, and we don't really use the newly cloned URL here
- then. Just free() it. */
+ hostname, remote_port);
+
+ /* This only happens if we've looped here due to authentication
+ reasons, and we don't really use the newly cloned URL here
+ then. Just free() it. */
free(data->req.newurl);
data->req.newurl = NULL;
-
+
host_port = aprintf("%s:%d", hostname, remote_port);
if(!host_port)
- return CURLE_OUT_OF_MEMORY;
-
+ return CURLE_OUT_OF_MEMORY;
+
/* initialize a dynamic send-buffer */
Curl_dyn_init(&req, DYN_HTTP_REQUEST);
- /* Setup the proxy-authorization header, if any */
- result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE);
-
- free(host_port);
-
+ /* Setup the proxy-authorization header, if any */
+ result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE);
+
+ free(host_port);
+
if(!result) {
char *host = NULL;
const char *proxyconn = "";
@@ -245,28 +245,28 @@ static CURLcode CONNECT(struct connectdata *conn,
ipv6_ip = (strchr(hostname, ':') != NULL);
hostheader = /* host:port with IPv6 support */
aprintf("%s%s%s:%d", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"",
- remote_port);
- if(!hostheader) {
+ remote_port);
+ if(!hostheader) {
Curl_dyn_free(&req);
- return CURLE_OUT_OF_MEMORY;
- }
-
+ return CURLE_OUT_OF_MEMORY;
+ }
+
if(!Curl_checkProxyheaders(conn, "Host")) {
- host = aprintf("Host: %s\r\n", hostheader);
- if(!host) {
- free(hostheader);
+ host = aprintf("Host: %s\r\n", hostheader);
+ if(!host) {
+ free(hostheader);
Curl_dyn_free(&req);
- return CURLE_OUT_OF_MEMORY;
- }
- }
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
if(!Curl_checkProxyheaders(conn, "Proxy-Connection"))
- proxyconn = "Proxy-Connection: Keep-Alive\r\n";
-
+ proxyconn = "Proxy-Connection: Keep-Alive\r\n";
+
if(!Curl_checkProxyheaders(conn, "User-Agent") &&
- data->set.str[STRING_USERAGENT])
+ data->set.str[STRING_USERAGENT])
useragent = data->state.aptr.uagent;
-
- result =
+
+ result =
Curl_dyn_addf(&req,
"CONNECT %s HTTP/%s\r\n"
"%s" /* Host: */
@@ -280,35 +280,35 @@ static CURLcode CONNECT(struct connectdata *conn,
data->state.aptr.proxyuserpwd:"",
useragent,
proxyconn);
-
+
if(host)
- free(host);
- free(hostheader);
-
+ free(host);
+ free(hostheader);
+
if(!result)
result = Curl_add_custom_headers(conn, TRUE, &req);
-
+
if(!result)
- /* CRLF terminate the request */
+ /* CRLF terminate the request */
result = Curl_dyn_add(&req, "\r\n");
-
+
if(!result) {
- /* Send the connect request to the proxy */
- /* BLOCKING */
+ /* Send the connect request to the proxy */
+ /* BLOCKING */
result = Curl_buffer_send(&req, conn, &data->info.request_size, 0,
sockindex);
- }
- if(result)
- failf(data, "Failed sending CONNECT to proxy");
- }
-
+ }
+ if(result)
+ failf(data, "Failed sending CONNECT to proxy");
+ }
+
Curl_dyn_free(&req);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
s->tunnel_state = TUNNEL_CONNECT;
} /* END CONNECT PHASE */
-
+
check = Curl_timeleft(data, NULL, TRUE);
if(check <= 0) {
failf(data, "Proxy CONNECT aborted due to timeout");
@@ -317,31 +317,31 @@ static CURLcode CONNECT(struct connectdata *conn,
if(!Curl_conn_data_pending(conn, sockindex))
/* return so we'll be called again polling-style */
- return CURLE_OK;
-
+ return CURLE_OK;
+
/* at this point, the tunnel_connecting phase is over. */
-
+
{ /* READING RESPONSE PHASE */
int error = SELECT_OK;
-
+
while(s->keepon) {
ssize_t gotbytes;
char byte;
-
+
/* Read one byte at a time to avoid a race condition. Wait at most one
second before looping to ensure continuous pgrsUpdates. */
result = Curl_read(conn, tunnelsocket, &byte, 1, &gotbytes);
if(result == CURLE_AGAIN)
/* socket buffer drained, return */
return CURLE_OK;
-
+
if(Curl_pgrsUpdate(conn))
return CURLE_ABORTED_BY_CALLBACK;
if(result) {
s->keepon = KEEPON_DONE;
- break;
- }
+ break;
+ }
else if(gotbytes <= 0) {
if(data->set.proxyauth && data->state.authproxy.avail) {
/* proxy auth was requested and there was proxy auth available,
@@ -356,7 +356,7 @@ static CURLcode CONNECT(struct connectdata *conn,
s->keepon = KEEPON_DONE;
break;
}
-
+
if(s->keepon == KEEPON_IGNORE) {
/* This means we are currently ignoring a response-body */
@@ -368,15 +368,15 @@ static CURLcode CONNECT(struct connectdata *conn,
s->keepon = KEEPON_DONE;
s->tunnel_state = TUNNEL_COMPLETE;
break;
- }
- }
- else {
+ }
+ }
+ else {
/* chunked-encoded body, so we need to do the chunked dance
properly to know when the end of the body is reached */
CHUNKcode r;
CURLcode extra;
ssize_t tookcareof = 0;
-
+
/* now parse the chunked piece of data so that we can
properly tell when the stream ends */
r = Curl_httpchunk_read(conn, &byte, 1, &tookcareof, &extra);
@@ -390,16 +390,16 @@ static CURLcode CONNECT(struct connectdata *conn,
}
continue;
}
-
+
if(Curl_dyn_addn(&s->rcvbuf, &byte, 1)) {
failf(data, "CONNECT response too large!");
return CURLE_RECV_ERROR;
}
-
+
/* if this is not the end of a header line then continue */
if(byte != 0x0a)
continue;
-
+
linep = Curl_dyn_ptr(&s->rcvbuf);
perline = Curl_dyn_len(&s->rcvbuf); /* amount of bytes in this line */
@@ -408,27 +408,27 @@ static CURLcode CONNECT(struct connectdata *conn,
/* Curl_convert_from_network calls failf if unsuccessful */
if(result)
return result;
-
+
/* output debug if that is requested */
Curl_debug(data, CURLINFO_HEADER_IN, linep, perline);
-
+
if(!data->set.suppress_connect_headers) {
/* send the header to the callback */
int writetype = CLIENTWRITE_HEADER;
if(data->set.include_header)
writetype |= CLIENTWRITE_BODY;
-
+
result = Curl_client_write(conn, writetype, linep, perline);
if(result)
return result;
}
-
+
data->info.header_size += (long)perline;
-
+
/* Newlines are CRLF, so the CR is ignored as the line isn't
really terminated until the LF comes. Treat a following CR
as end-of-headers as well.*/
-
+
if(('\r' == linep[0]) ||
('\n' == linep[0])) {
/* end of response-headers from the proxy */
@@ -438,7 +438,7 @@ static CURLcode CONNECT(struct connectdata *conn,
when we have no auth problem, we must ignore the
whole response-body */
s->keepon = KEEPON_IGNORE;
-
+
if(s->cl) {
infof(data, "Ignore %" CURL_FORMAT_CURL_OFF_T
" bytes of response-body\n", s->cl);
@@ -446,18 +446,18 @@ static CURLcode CONNECT(struct connectdata *conn,
else if(s->chunked_encoding) {
CHUNKcode r;
CURLcode extra;
-
+
infof(data, "Ignore chunked response-body\n");
-
+
/* We set ignorebody true here since the chunked decoder
function will acknowledge that. Pay attention so that this is
cleared again when this function returns! */
k->ignorebody = TRUE;
-
+
if(linep[1] == '\n')
/* this can only be a LF if the letter at index 0 was a CR */
linep++;
-
+
/* now parse the chunked piece of data so that we can properly
tell when the stream ends */
r = Curl_httpchunk_read(conn, linep + 1, 1, &gotbytes,
@@ -484,19 +484,19 @@ static CURLcode CONNECT(struct connectdata *conn,
s->tunnel_state = TUNNEL_COMPLETE;
continue;
}
-
+
if((checkprefix("WWW-Authenticate:", linep) &&
(401 == k->httpcode)) ||
(checkprefix("Proxy-authenticate:", linep) &&
(407 == k->httpcode))) {
-
+
bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
char *auth = Curl_copy_header_value(linep);
if(!auth)
return CURLE_OUT_OF_MEMORY;
-
+
result = Curl_http_input_auth(conn, proxy, auth);
-
+
free(auth);
if(result)
@@ -509,7 +509,7 @@ static CURLcode CONNECT(struct connectdata *conn,
"Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */
infof(data, "Ignoring Content-Length in CONNECT %03d response\n",
k->httpcode);
- }
+ }
else {
(void)curlx_strtoofft(linep +
strlen("Content-Length:"), NULL, 10, &s->cl);
@@ -543,91 +543,91 @@ static CURLcode CONNECT(struct connectdata *conn,
}
Curl_dyn_reset(&s->rcvbuf);
- } /* while there's buffer left and loop is requested */
-
+ } /* while there's buffer left and loop is requested */
+
if(Curl_pgrsUpdate(conn))
return CURLE_ABORTED_BY_CALLBACK;
- if(error)
- return CURLE_RECV_ERROR;
-
+ if(error)
+ return CURLE_RECV_ERROR;
+
if(data->info.httpproxycode/100 != 2) {
- /* Deal with the possibly already received authenticate
- headers. 'newurl' is set to a new URL if we must loop. */
- result = Curl_http_auth_act(conn);
- if(result)
- return result;
-
- if(conn->bits.close)
- /* the connection has been marked for closure, most likely in the
- Curl_http_auth_act() function and thus we can kill it at once
+ /* Deal with the possibly already received authenticate
+ headers. 'newurl' is set to a new URL if we must loop. */
+ result = Curl_http_auth_act(conn);
+ if(result)
+ return result;
+
+ if(conn->bits.close)
+ /* the connection has been marked for closure, most likely in the
+ Curl_http_auth_act() function and thus we can kill it at once
below */
s->close_connection = TRUE;
- }
-
+ }
+
if(s->close_connection && data->req.newurl) {
- /* Connection closed by server. Don't use it anymore */
- Curl_closesocket(conn, conn->sock[sockindex]);
- conn->sock[sockindex] = CURL_SOCKET_BAD;
- break;
- }
+ /* Connection closed by server. Don't use it anymore */
+ Curl_closesocket(conn, conn->sock[sockindex]);
+ conn->sock[sockindex] = CURL_SOCKET_BAD;
+ break;
+ }
} /* END READING RESPONSE PHASE */
-
- /* If we are supposed to continue and request a new URL, which basically
- * means the HTTP authentication is still going on so if the tunnel
- * is complete we start over in INIT state */
+
+ /* If we are supposed to continue and request a new URL, which basically
+ * means the HTTP authentication is still going on so if the tunnel
+ * is complete we start over in INIT state */
if(data->req.newurl && (TUNNEL_COMPLETE == s->tunnel_state)) {
connect_init(conn, TRUE); /* reinit */
- }
-
- } while(data->req.newurl);
-
+ }
+
+ } while(data->req.newurl);
+
if(data->info.httpproxycode/100 != 2) {
if(s->close_connection && data->req.newurl) {
- conn->bits.proxy_connect_closed = TRUE;
+ conn->bits.proxy_connect_closed = TRUE;
infof(data, "Connect me again please\n");
connect_done(conn);
}
else {
- free(data->req.newurl);
- data->req.newurl = NULL;
+ free(data->req.newurl);
+ data->req.newurl = NULL;
/* failure, close this connection to avoid re-use */
streamclose(conn, "proxy CONNECT failure");
Curl_closesocket(conn, conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
- }
-
- /* to back to init state */
+ }
+
+ /* to back to init state */
s->tunnel_state = TUNNEL_INIT;
-
+
if(conn->bits.proxy_connect_closed)
/* this is not an error, just part of the connection negotiation */
return CURLE_OK;
Curl_dyn_free(&s->rcvbuf);
failf(data, "Received HTTP code %d from proxy after CONNECT",
data->req.httpcode);
- return CURLE_RECV_ERROR;
- }
-
+ return CURLE_RECV_ERROR;
+ }
+
s->tunnel_state = TUNNEL_COMPLETE;
-
- /* If a proxy-authorization header was used for the proxy, then we should
- make sure that it isn't accidentally used for the document request
- after we've connected. So let's free and clear it here. */
+
+ /* If a proxy-authorization header was used for the proxy, then we should
+ make sure that it isn't accidentally used for the document request
+ after we've connected. So let's free and clear it here. */
Curl_safefree(data->state.aptr.proxyuserpwd);
data->state.aptr.proxyuserpwd = NULL;
-
- data->state.authproxy.done = TRUE;
+
+ data->state.authproxy.done = TRUE;
data->state.authproxy.multipass = FALSE;
-
+
infof(data, "Proxy replied %d to CONNECT request\n",
data->info.httpproxycode);
- data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
- conn->bits.rewindaftersend = FALSE; /* make sure this isn't set for the
- document request */
+ data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
+ conn->bits.rewindaftersend = FALSE; /* make sure this isn't set for the
+ document request */
Curl_dyn_free(&s->rcvbuf);
- return CURLE_OK;
-}
+ return CURLE_OK;
+}
void Curl_connect_free(struct Curl_easy *data)
{
@@ -670,4 +670,4 @@ void Curl_connect_free(struct Curl_easy *data)
(void)data;
}
-#endif /* CURL_DISABLE_PROXY */
+#endif /* CURL_DISABLE_PROXY */
diff --git a/contrib/libs/curl/lib/http_proxy.h b/contrib/libs/curl/lib/http_proxy.h
index bb09d88a1a..a595e8b553 100644
--- a/contrib/libs/curl/lib/http_proxy.h
+++ b/contrib/libs/curl/lib/http_proxy.h
@@ -1,52 +1,52 @@
-#ifndef HEADER_CURL_HTTP_PROXY_H
-#define HEADER_CURL_HTTP_PROXY_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_HTTP_PROXY_H
+#define HEADER_CURL_HTTP_PROXY_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include "curl_setup.h"
#include "urldata.h"
-#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
-/* ftp can use this as well */
-CURLcode Curl_proxyCONNECT(struct connectdata *conn,
- int tunnelsocket,
+#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
+/* ftp can use this as well */
+CURLcode Curl_proxyCONNECT(struct connectdata *conn,
+ int tunnelsocket,
const char *hostname, int remote_port);
-
-/* Default proxy timeout in milliseconds */
-#define PROXY_TIMEOUT (3600*1000)
-
+
+/* Default proxy timeout in milliseconds */
+#define PROXY_TIMEOUT (3600*1000)
+
CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex);
-
+
bool Curl_connect_complete(struct connectdata *conn);
bool Curl_connect_ongoing(struct connectdata *conn);
-#else
-#define Curl_proxyCONNECT(x,y,z,w) CURLE_NOT_BUILT_IN
+#else
+#define Curl_proxyCONNECT(x,y,z,w) CURLE_NOT_BUILT_IN
#define Curl_proxy_connect(x,y) CURLE_OK
#define Curl_connect_complete(x) CURLE_OK
#define Curl_connect_ongoing(x) FALSE
-#endif
-
+#endif
+
void Curl_connect_free(struct Curl_easy *data);
void Curl_connect_done(struct Curl_easy *data);
-#endif /* HEADER_CURL_HTTP_PROXY_H */
+#endif /* HEADER_CURL_HTTP_PROXY_H */
diff --git a/contrib/libs/curl/lib/idn_win32.c b/contrib/libs/curl/lib/idn_win32.c
index deee38ff5e..1d475a4eff 100644
--- a/contrib/libs/curl/lib/idn_win32.c
+++ b/contrib/libs/curl/lib/idn_win32.c
@@ -1,41 +1,41 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
- /*
- * IDN conversions using Windows kernel32 and normaliz libraries.
- */
-
-#include "curl_setup.h"
-
-#ifdef USE_WIN32_IDN
-
-#include "curl_multibyte.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+ /*
+ * IDN conversions using Windows kernel32 and normaliz libraries.
+ */
+
+#include "curl_setup.h"
+
+#ifdef USE_WIN32_IDN
+
+#include "curl_multibyte.h"
#include "curl_memory.h"
#include "warnless.h"
-
+
/* The last #include file should be: */
-#include "memdebug.h"
-
-#ifdef WANT_IDN_PROTOTYPES
+#include "memdebug.h"
+
+#ifdef WANT_IDN_PROTOTYPES
# if defined(_SAL_VERSION)
WINNORMALIZEAPI int WINAPI
IdnToAscii(_In_ DWORD dwFlags,
@@ -61,36 +61,36 @@ WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags,
WCHAR *lpUnicodeCharStr,
int cchUnicodeChar);
# endif
-#endif
-
-#define IDN_MAX_LENGTH 255
-
+#endif
+
+#define IDN_MAX_LENGTH 255
+
bool curl_win32_idn_to_ascii(const char *in, char **out);
bool curl_win32_ascii_to_idn(const char *in, char **out);
-
+
bool curl_win32_idn_to_ascii(const char *in, char **out)
-{
+{
bool success = FALSE;
wchar_t *in_w = curlx_convert_UTF8_to_wchar(in);
- if(in_w) {
- wchar_t punycode[IDN_MAX_LENGTH];
+ if(in_w) {
+ wchar_t punycode[IDN_MAX_LENGTH];
int chars = IdnToAscii(0, in_w, -1, punycode, IDN_MAX_LENGTH);
free(in_w);
if(chars) {
*out = curlx_convert_wchar_to_UTF8(punycode);
if(*out)
success = TRUE;
- }
+ }
}
-
+
return success;
-}
-
+}
+
bool curl_win32_ascii_to_idn(const char *in, char **out)
-{
+{
bool success = FALSE;
-
+
wchar_t *in_w = curlx_convert_UTF8_to_wchar(in);
if(in_w) {
size_t in_len = wcslen(in_w) + 1;
@@ -102,10 +102,10 @@ bool curl_win32_ascii_to_idn(const char *in, char **out)
*out = curlx_convert_wchar_to_UTF8(unicode);
if(*out)
success = TRUE;
- }
- }
+ }
+ }
return success;
-}
-
-#endif /* USE_WIN32_IDN */
+}
+
+#endif /* USE_WIN32_IDN */
diff --git a/contrib/libs/curl/lib/if2ip.c b/contrib/libs/curl/lib/if2ip.c
index 858c10d73a..bf397aad45 100644
--- a/contrib/libs/curl/lib/if2ip.c
+++ b/contrib/libs/curl/lib/if2ip.c
@@ -1,62 +1,62 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_NETINET_IN_H
-# include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-# include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-# include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-# include <sys/ioctl.h>
-#endif
-#ifdef HAVE_NETDB_H
-# include <netdb.h>
-#endif
-#ifdef HAVE_SYS_SOCKIO_H
-# include <sys/sockio.h>
-#endif
-#ifdef HAVE_IFADDRS_H
-# include <ifaddrs.h>
-#endif
-#ifdef __VMS
-# include <inet.h>
-#endif
-
-#include "inet_ntop.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_NETINET_IN_H
+# include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+# include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+# include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+# include <sys/ioctl.h>
+#endif
+#ifdef HAVE_NETDB_H
+# include <netdb.h>
+#endif
+#ifdef HAVE_SYS_SOCKIO_H
+# include <sys/sockio.h>
+#endif
+#ifdef HAVE_IFADDRS_H
+# include <ifaddrs.h>
+#endif
+#ifdef __VMS
+# include <inet.h>
+#endif
+
+#include "inet_ntop.h"
#include "strcase.h"
-#include "if2ip.h"
+#include "if2ip.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* ------------------------------------------------------------------ */
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* ------------------------------------------------------------------ */
+
/* Return the scope of the given address. */
unsigned int Curl_ipv6_scope(const struct sockaddr *sa)
{
@@ -91,37 +91,37 @@ unsigned int Curl_ipv6_scope(const struct sockaddr *sa)
}
-#if defined(HAVE_GETIFADDRS)
-
-if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
+#if defined(HAVE_GETIFADDRS)
+
+if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
unsigned int local_scope_id, const char *interf,
char *buf, int buf_size)
-{
- struct ifaddrs *iface, *head;
- if2ip_result_t res = IF2IP_NOT_FOUND;
-
-#ifndef ENABLE_IPV6
- (void) remote_scope;
-#endif
-
+{
+ struct ifaddrs *iface, *head;
+ if2ip_result_t res = IF2IP_NOT_FOUND;
+
+#ifndef ENABLE_IPV6
+ (void) remote_scope;
+#endif
+
#if !defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) || \
!defined(ENABLE_IPV6)
(void) local_scope_id;
#endif
- if(getifaddrs(&head) >= 0) {
+ if(getifaddrs(&head) >= 0) {
for(iface = head; iface != NULL; iface = iface->ifa_next) {
- if(iface->ifa_addr != NULL) {
- if(iface->ifa_addr->sa_family == af) {
+ if(iface->ifa_addr != NULL) {
+ if(iface->ifa_addr->sa_family == af) {
if(strcasecompare(iface->ifa_name, interf)) {
- void *addr;
+ void *addr;
const char *ip;
char scope[12] = "";
- char ipstr[64];
-#ifdef ENABLE_IPV6
- if(af == AF_INET6) {
+ char ipstr[64];
+#ifdef ENABLE_IPV6
+ if(af == AF_INET6) {
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
- unsigned int scopeid = 0;
+ unsigned int scopeid = 0;
#endif
unsigned int ifscope = Curl_ipv6_scope(iface->ifa_addr);
@@ -131,8 +131,8 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
for global, link-local for link-local, etc... */
if(res == IF2IP_NOT_FOUND)
res = IF2IP_AF_NOT_SUPPORTED;
- continue;
- }
+ continue;
+ }
addr =
&((struct sockaddr_in6 *)(void *)iface->ifa_addr)->sin6_addr;
@@ -152,92 +152,92 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
if(scopeid)
msnprintf(scope, sizeof(scope), "%%%u", scopeid);
#endif
- }
- else
-#endif
+ }
+ else
+#endif
addr =
&((struct sockaddr_in *)(void *)iface->ifa_addr)->sin_addr;
- res = IF2IP_FOUND;
+ res = IF2IP_FOUND;
ip = Curl_inet_ntop(af, addr, ipstr, sizeof(ipstr));
msnprintf(buf, buf_size, "%s%s", ip, scope);
- break;
- }
- }
- else if((res == IF2IP_NOT_FOUND) &&
+ break;
+ }
+ }
+ else if((res == IF2IP_NOT_FOUND) &&
strcasecompare(iface->ifa_name, interf)) {
- res = IF2IP_AF_NOT_SUPPORTED;
- }
- }
- }
-
- freeifaddrs(head);
- }
-
- return res;
-}
-
-#elif defined(HAVE_IOCTL_SIOCGIFADDR)
-
-if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
+ res = IF2IP_AF_NOT_SUPPORTED;
+ }
+ }
+ }
+
+ freeifaddrs(head);
+ }
+
+ return res;
+}
+
+#elif defined(HAVE_IOCTL_SIOCGIFADDR)
+
+if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
unsigned int local_scope_id, const char *interf,
char *buf, int buf_size)
-{
- struct ifreq req;
- struct in_addr in;
- struct sockaddr_in *s;
- curl_socket_t dummy;
- size_t len;
+{
+ struct ifreq req;
+ struct in_addr in;
+ struct sockaddr_in *s;
+ curl_socket_t dummy;
+ size_t len;
const char *r;
-
- (void)remote_scope;
+
+ (void)remote_scope;
(void)local_scope_id;
-
- if(!interf || (af != AF_INET))
- return IF2IP_NOT_FOUND;
-
- len = strlen(interf);
- if(len >= sizeof(req.ifr_name))
- return IF2IP_NOT_FOUND;
-
- dummy = socket(AF_INET, SOCK_STREAM, 0);
- if(CURL_SOCKET_BAD == dummy)
- return IF2IP_NOT_FOUND;
-
- memset(&req, 0, sizeof(req));
+
+ if(!interf || (af != AF_INET))
+ return IF2IP_NOT_FOUND;
+
+ len = strlen(interf);
+ if(len >= sizeof(req.ifr_name))
+ return IF2IP_NOT_FOUND;
+
+ dummy = socket(AF_INET, SOCK_STREAM, 0);
+ if(CURL_SOCKET_BAD == dummy)
+ return IF2IP_NOT_FOUND;
+
+ memset(&req, 0, sizeof(req));
memcpy(req.ifr_name, interf, len + 1);
- req.ifr_addr.sa_family = AF_INET;
-
- if(ioctl(dummy, SIOCGIFADDR, &req) < 0) {
- sclose(dummy);
- /* With SIOCGIFADDR, we cannot tell the difference between an interface
- that does not exist and an interface that has no address of the
- correct family. Assume the interface does not exist */
- return IF2IP_NOT_FOUND;
- }
-
+ req.ifr_addr.sa_family = AF_INET;
+
+ if(ioctl(dummy, SIOCGIFADDR, &req) < 0) {
+ sclose(dummy);
+ /* With SIOCGIFADDR, we cannot tell the difference between an interface
+ that does not exist and an interface that has no address of the
+ correct family. Assume the interface does not exist */
+ return IF2IP_NOT_FOUND;
+ }
+
s = (struct sockaddr_in *)(void *)&req.ifr_addr;
- memcpy(&in, &s->sin_addr, sizeof(in));
+ memcpy(&in, &s->sin_addr, sizeof(in));
r = Curl_inet_ntop(s->sin_family, &in, buf, buf_size);
-
- sclose(dummy);
+
+ sclose(dummy);
if(!r)
return IF2IP_NOT_FOUND;
- return IF2IP_FOUND;
-}
-
-#else
-
-if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
+ return IF2IP_FOUND;
+}
+
+#else
+
+if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
unsigned int local_scope_id, const char *interf,
char *buf, int buf_size)
-{
- (void) af;
- (void) remote_scope;
+{
+ (void) af;
+ (void) remote_scope;
(void) local_scope_id;
- (void) interf;
- (void) buf;
- (void) buf_size;
- return IF2IP_NOT_FOUND;
-}
-
-#endif
+ (void) interf;
+ (void) buf;
+ (void) buf_size;
+ return IF2IP_NOT_FOUND;
+}
+
+#endif
diff --git a/contrib/libs/curl/lib/if2ip.h b/contrib/libs/curl/lib/if2ip.h
index 156789d0b0..e074e476dc 100644
--- a/contrib/libs/curl/lib/if2ip.h
+++ b/contrib/libs/curl/lib/if2ip.h
@@ -1,28 +1,28 @@
-#ifndef HEADER_CURL_IF2IP_H
-#define HEADER_CURL_IF2IP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_IF2IP_H
+#define HEADER_CURL_IF2IP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
/* IPv6 address scopes. */
#define IPV6_SCOPE_GLOBAL 0 /* Global scope. */
#define IPV6_SCOPE_LINKLOCAL 1 /* Link-local scope. */
@@ -32,51 +32,51 @@
unsigned int Curl_ipv6_scope(const struct sockaddr *sa);
-typedef enum {
- IF2IP_NOT_FOUND = 0, /* Interface not found */
- IF2IP_AF_NOT_SUPPORTED = 1, /* Int. exists but has no address for this af */
- IF2IP_FOUND = 2 /* The address has been stored in "buf" */
-} if2ip_result_t;
-
-if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
+typedef enum {
+ IF2IP_NOT_FOUND = 0, /* Interface not found */
+ IF2IP_AF_NOT_SUPPORTED = 1, /* Int. exists but has no address for this af */
+ IF2IP_FOUND = 2 /* The address has been stored in "buf" */
+} if2ip_result_t;
+
+if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
unsigned int local_scope_id, const char *interf,
char *buf, int buf_size);
-
-#ifdef __INTERIX
-
-/* Nedelcho Stanev's work-around for SFU 3.0 */
-struct ifreq {
-#define IFNAMSIZ 16
-#define IFHWADDRLEN 6
- union {
- char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */
- } ifr_ifrn;
-
- union {
- struct sockaddr ifru_addr;
- struct sockaddr ifru_broadaddr;
- struct sockaddr ifru_netmask;
- struct sockaddr ifru_hwaddr;
- short ifru_flags;
- int ifru_metric;
- int ifru_mtu;
- } ifr_ifru;
-};
-
-/* This define was added by Daniel to avoid an extra #ifdef INTERIX in the
- C code. */
-
-#define ifr_name ifr_ifrn.ifrn_name /* interface name */
-#define ifr_addr ifr_ifru.ifru_addr /* address */
-#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */
-#define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */
-#define ifr_flags ifr_ifru.ifru_flags /* flags */
-#define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */
-#define ifr_metric ifr_ifru.ifru_metric /* metric */
-#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */
-
-#define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */
-
-#endif /* __INTERIX */
-
-#endif /* HEADER_CURL_IF2IP_H */
+
+#ifdef __INTERIX
+
+/* Nedelcho Stanev's work-around for SFU 3.0 */
+struct ifreq {
+#define IFNAMSIZ 16
+#define IFHWADDRLEN 6
+ union {
+ char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */
+ } ifr_ifrn;
+
+ union {
+ struct sockaddr ifru_addr;
+ struct sockaddr ifru_broadaddr;
+ struct sockaddr ifru_netmask;
+ struct sockaddr ifru_hwaddr;
+ short ifru_flags;
+ int ifru_metric;
+ int ifru_mtu;
+ } ifr_ifru;
+};
+
+/* This define was added by Daniel to avoid an extra #ifdef INTERIX in the
+ C code. */
+
+#define ifr_name ifr_ifrn.ifrn_name /* interface name */
+#define ifr_addr ifr_ifru.ifru_addr /* address */
+#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */
+#define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */
+#define ifr_flags ifr_ifru.ifru_flags /* flags */
+#define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */
+#define ifr_metric ifr_ifru.ifru_metric /* metric */
+#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */
+
+#define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */
+
+#endif /* __INTERIX */
+
+#endif /* HEADER_CURL_IF2IP_H */
diff --git a/contrib/libs/curl/lib/imap.c b/contrib/libs/curl/lib/imap.c
index 63c63151cc..c6dd7a2323 100644
--- a/contrib/libs/curl/lib/imap.c
+++ b/contrib/libs/curl/lib/imap.c
@@ -1,175 +1,175 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * RFC2195 CRAM-MD5 authentication
- * RFC2595 Using TLS with IMAP, POP3 and ACAP
- * RFC2831 DIGEST-MD5 authentication
- * RFC3501 IMAPv4 protocol
- * RFC4422 Simple Authentication and Security Layer (SASL)
- * RFC4616 PLAIN authentication
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * RFC2195 CRAM-MD5 authentication
+ * RFC2595 Using TLS with IMAP, POP3 and ACAP
+ * RFC2831 DIGEST-MD5 authentication
+ * RFC3501 IMAPv4 protocol
+ * RFC4422 Simple Authentication and Security Layer (SASL)
+ * RFC4616 PLAIN authentication
* RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
- * RFC4959 IMAP Extension for SASL Initial Client Response
- * RFC5092 IMAP URL Scheme
- * RFC6749 OAuth 2.0 Authorization Framework
+ * RFC4959 IMAP Extension for SASL Initial Client Response
+ * RFC5092 IMAP URL Scheme
+ * RFC6749 OAuth 2.0 Authorization Framework
* RFC8314 Use of TLS for Email Submission and Access
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_IMAP
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_UTSNAME_H
-#include <sys/utsname.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-#include <curl/curl.h>
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "progress.h"
-#include "transfer.h"
-#include "escape.h"
-#include "http.h" /* for HTTP proxy tunnel stuff */
-#include "socks.h"
-#include "imap.h"
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_IMAP
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_UTSNAME_H
+#include <sys/utsname.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "progress.h"
+#include "transfer.h"
+#include "escape.h"
+#include "http.h" /* for HTTP proxy tunnel stuff */
+#include "socks.h"
+#include "imap.h"
#include "mime.h"
-#include "strtoofft.h"
+#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
-#include "connect.h"
-#include "strerror.h"
-#include "select.h"
-#include "multiif.h"
-#include "url.h"
+#include "connect.h"
+#include "strerror.h"
+#include "select.h"
+#include "multiif.h"
+#include "url.h"
#include "strcase.h"
-#include "curl_sasl.h"
-#include "warnless.h"
-
+#include "curl_sasl.h"
+#include "warnless.h"
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* Local API functions */
-static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
-static CURLcode imap_do(struct connectdata *conn, bool *done);
-static CURLcode imap_done(struct connectdata *conn, CURLcode status,
- bool premature);
-static CURLcode imap_connect(struct connectdata *conn, bool *done);
-static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
-static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* Local API functions */
+static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
+static CURLcode imap_do(struct connectdata *conn, bool *done);
+static CURLcode imap_done(struct connectdata *conn, CURLcode status,
+ bool premature);
+static CURLcode imap_connect(struct connectdata *conn, bool *done);
+static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
+static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
static int imap_getsock(struct connectdata *conn, curl_socket_t *socks);
-static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done);
-static CURLcode imap_setup_connection(struct connectdata *conn);
+static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done);
+static CURLcode imap_setup_connection(struct connectdata *conn);
static char *imap_atom(const char *str, bool escape_only);
-static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...);
-static CURLcode imap_parse_url_options(struct connectdata *conn);
-static CURLcode imap_parse_url_path(struct connectdata *conn);
-static CURLcode imap_parse_custom_request(struct connectdata *conn);
+static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...);
+static CURLcode imap_parse_url_options(struct connectdata *conn);
+static CURLcode imap_parse_url_path(struct connectdata *conn);
+static CURLcode imap_parse_custom_request(struct connectdata *conn);
static CURLcode imap_perform_authenticate(struct connectdata *conn,
const char *mech,
const char *initresp);
static CURLcode imap_continue_authenticate(struct connectdata *conn,
const char *resp);
static void imap_get_message(char *buffer, char **outptr);
-
-/*
- * IMAP protocol handler.
- */
-
-const struct Curl_handler Curl_handler_imap = {
- "IMAP", /* scheme */
- imap_setup_connection, /* setup_connection */
- imap_do, /* do_it */
- imap_done, /* done */
- ZERO_NULL, /* do_more */
- imap_connect, /* connect_it */
- imap_multi_statemach, /* connecting */
- imap_doing, /* doing */
- imap_getsock, /* proto_getsock */
- imap_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- imap_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+
+/*
+ * IMAP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_imap = {
+ "IMAP", /* scheme */
+ imap_setup_connection, /* setup_connection */
+ imap_do, /* do_it */
+ imap_done, /* done */
+ ZERO_NULL, /* do_more */
+ imap_connect, /* connect_it */
+ imap_multi_statemach, /* connecting */
+ imap_doing, /* doing */
+ imap_getsock, /* proto_getsock */
+ imap_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ imap_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_IMAP, /* defport */
- CURLPROTO_IMAP, /* protocol */
+ PORT_IMAP, /* defport */
+ CURLPROTO_IMAP, /* protocol */
CURLPROTO_IMAP, /* family */
PROTOPT_CLOSEACTION| /* flags */
PROTOPT_URLOPTIONS
-};
-
-#ifdef USE_SSL
-/*
- * IMAPS protocol handler.
- */
-
-const struct Curl_handler Curl_handler_imaps = {
- "IMAPS", /* scheme */
- imap_setup_connection, /* setup_connection */
- imap_do, /* do_it */
- imap_done, /* done */
- ZERO_NULL, /* do_more */
- imap_connect, /* connect_it */
- imap_multi_statemach, /* connecting */
- imap_doing, /* doing */
- imap_getsock, /* proto_getsock */
- imap_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- imap_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+};
+
+#ifdef USE_SSL
+/*
+ * IMAPS protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_imaps = {
+ "IMAPS", /* scheme */
+ imap_setup_connection, /* setup_connection */
+ imap_do, /* do_it */
+ imap_done, /* done */
+ ZERO_NULL, /* do_more */
+ imap_connect, /* connect_it */
+ imap_multi_statemach, /* connecting */
+ imap_doing, /* doing */
+ imap_getsock, /* proto_getsock */
+ imap_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ imap_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_IMAPS, /* defport */
+ PORT_IMAPS, /* defport */
CURLPROTO_IMAPS, /* protocol */
CURLPROTO_IMAP, /* family */
PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */
PROTOPT_URLOPTIONS
-};
-#endif
-
+};
+#endif
+
#define IMAP_RESP_OK 1
#define IMAP_RESP_NOT_OK 2
#define IMAP_RESP_PREAUTH 3
-
+
/* SASL parameters for the imap protocol */
static const struct SASLproto saslimap = {
"imap", /* The service name */
@@ -179,107 +179,107 @@ static const struct SASLproto saslimap = {
imap_perform_authenticate, /* Send authentication command */
imap_continue_authenticate, /* Send authentication continuation */
imap_get_message /* Get SASL response message */
-};
-
-
-#ifdef USE_SSL
-static void imap_to_imaps(struct connectdata *conn)
-{
+};
+
+
+#ifdef USE_SSL
+static void imap_to_imaps(struct connectdata *conn)
+{
/* Change the connection handler */
- conn->handler = &Curl_handler_imaps;
+ conn->handler = &Curl_handler_imaps;
/* Set the connection's upgraded to TLS flag */
conn->bits.tls_upgraded = TRUE;
-}
-#else
-#define imap_to_imaps(x) Curl_nop_stmt
-#endif
-
-/***********************************************************************
- *
- * imap_matchresp()
- *
- * Determines whether the untagged response is related to the specified
- * command by checking if it is in format "* <command-name> ..." or
- * "* <number> <command-name> ...".
- *
- * The "* " marker is assumed to have already been checked by the caller.
- */
-static bool imap_matchresp(const char *line, size_t len, const char *cmd)
-{
- const char *end = line + len;
- size_t cmd_len = strlen(cmd);
-
- /* Skip the untagged response marker */
- line += 2;
-
- /* Do we have a number after the marker? */
- if(line < end && ISDIGIT(*line)) {
- /* Skip the number */
- do
- line++;
- while(line < end && ISDIGIT(*line));
-
- /* Do we have the space character? */
- if(line == end || *line != ' ')
- return FALSE;
-
- line++;
- }
-
- /* Does the command name match and is it followed by a space character or at
- the end of line? */
+}
+#else
+#define imap_to_imaps(x) Curl_nop_stmt
+#endif
+
+/***********************************************************************
+ *
+ * imap_matchresp()
+ *
+ * Determines whether the untagged response is related to the specified
+ * command by checking if it is in format "* <command-name> ..." or
+ * "* <number> <command-name> ...".
+ *
+ * The "* " marker is assumed to have already been checked by the caller.
+ */
+static bool imap_matchresp(const char *line, size_t len, const char *cmd)
+{
+ const char *end = line + len;
+ size_t cmd_len = strlen(cmd);
+
+ /* Skip the untagged response marker */
+ line += 2;
+
+ /* Do we have a number after the marker? */
+ if(line < end && ISDIGIT(*line)) {
+ /* Skip the number */
+ do
+ line++;
+ while(line < end && ISDIGIT(*line));
+
+ /* Do we have the space character? */
+ if(line == end || *line != ' ')
+ return FALSE;
+
+ line++;
+ }
+
+ /* Does the command name match and is it followed by a space character or at
+ the end of line? */
if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) &&
(line[cmd_len] == ' ' || line + cmd_len + 2 == end))
- return TRUE;
-
- return FALSE;
-}
-
-/***********************************************************************
- *
- * imap_endofresp()
- *
- * Checks whether the given string is a valid tagged, untagged or continuation
- * response which can be processed by the response handler.
- */
-static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
- int *resp)
-{
+ return TRUE;
+
+ return FALSE;
+}
+
+/***********************************************************************
+ *
+ * imap_endofresp()
+ *
+ * Checks whether the given string is a valid tagged, untagged or continuation
+ * response which can be processed by the response handler.
+ */
+static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
+ int *resp)
+{
struct IMAP *imap = conn->data->req.p.imap;
- struct imap_conn *imapc = &conn->proto.imapc;
- const char *id = imapc->resptag;
- size_t id_len = strlen(id);
-
- /* Do we have a tagged command response? */
- if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') {
- line += id_len + 1;
- len -= id_len + 1;
-
- if(len >= 2 && !memcmp(line, "OK", 2))
+ struct imap_conn *imapc = &conn->proto.imapc;
+ const char *id = imapc->resptag;
+ size_t id_len = strlen(id);
+
+ /* Do we have a tagged command response? */
+ if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') {
+ line += id_len + 1;
+ len -= id_len + 1;
+
+ if(len >= 2 && !memcmp(line, "OK", 2))
*resp = IMAP_RESP_OK;
else if(len >= 7 && !memcmp(line, "PREAUTH", 7))
*resp = IMAP_RESP_PREAUTH;
else
*resp = IMAP_RESP_NOT_OK;
-
- return TRUE;
- }
-
- /* Do we have an untagged command response? */
- if(len >= 2 && !memcmp("* ", line, 2)) {
- switch(imapc->state) {
- /* States which are interested in untagged responses */
- case IMAP_CAPABILITY:
- if(!imap_matchresp(line, len, "CAPABILITY"))
- return FALSE;
- break;
-
- case IMAP_LIST:
- if((!imap->custom && !imap_matchresp(line, len, "LIST")) ||
- (imap->custom && !imap_matchresp(line, len, imap->custom) &&
+
+ return TRUE;
+ }
+
+ /* Do we have an untagged command response? */
+ if(len >= 2 && !memcmp("* ", line, 2)) {
+ switch(imapc->state) {
+ /* States which are interested in untagged responses */
+ case IMAP_CAPABILITY:
+ if(!imap_matchresp(line, len, "CAPABILITY"))
+ return FALSE;
+ break;
+
+ case IMAP_LIST:
+ if((!imap->custom && !imap_matchresp(line, len, "LIST")) ||
+ (imap->custom && !imap_matchresp(line, len, imap->custom) &&
(!strcasecompare(imap->custom, "STORE") ||
- !imap_matchresp(line, len, "FETCH")) &&
+ !imap_matchresp(line, len, "FETCH")) &&
!strcasecompare(imap->custom, "SELECT") &&
!strcasecompare(imap->custom, "EXAMINE") &&
!strcasecompare(imap->custom, "SEARCH") &&
@@ -287,60 +287,60 @@ static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
!strcasecompare(imap->custom, "LSUB") &&
!strcasecompare(imap->custom, "UID") &&
!strcasecompare(imap->custom, "NOOP")))
- return FALSE;
- break;
-
- case IMAP_SELECT:
- /* SELECT is special in that its untagged responses do not have a
- common prefix so accept anything! */
- break;
-
- case IMAP_FETCH:
- if(!imap_matchresp(line, len, "FETCH"))
- return FALSE;
- break;
-
+ return FALSE;
+ break;
+
+ case IMAP_SELECT:
+ /* SELECT is special in that its untagged responses do not have a
+ common prefix so accept anything! */
+ break;
+
+ case IMAP_FETCH:
+ if(!imap_matchresp(line, len, "FETCH"))
+ return FALSE;
+ break;
+
case IMAP_SEARCH:
if(!imap_matchresp(line, len, "SEARCH"))
return FALSE;
break;
- /* Ignore other untagged responses */
- default:
- return FALSE;
- }
-
- *resp = '*';
- return TRUE;
- }
-
- /* Do we have a continuation response? This should be a + symbol followed by
- a space and optionally some text as per RFC-3501 for the AUTHENTICATE and
- APPEND commands and as outlined in Section 4. Examples of RFC-4959 but
- some e-mail servers ignore this and only send a single + instead. */
+ /* Ignore other untagged responses */
+ default:
+ return FALSE;
+ }
+
+ *resp = '*';
+ return TRUE;
+ }
+
+ /* Do we have a continuation response? This should be a + symbol followed by
+ a space and optionally some text as per RFC-3501 for the AUTHENTICATE and
+ APPEND commands and as outlined in Section 4. Examples of RFC-4959 but
+ some e-mail servers ignore this and only send a single + instead. */
if(imap && !imap->custom && ((len == 3 && line[0] == '+') ||
(len >= 2 && !memcmp("+ ", line, 2)))) {
- switch(imapc->state) {
- /* States which are interested in continuation responses */
+ switch(imapc->state) {
+ /* States which are interested in continuation responses */
case IMAP_AUTHENTICATE:
- case IMAP_APPEND:
- *resp = '+';
- break;
-
- default:
- failf(conn->data, "Unexpected continuation response");
- *resp = -1;
- break;
- }
-
- return TRUE;
- }
-
- return FALSE; /* Nothing for us */
-}
-
-/***********************************************************************
- *
+ case IMAP_APPEND:
+ *resp = '+';
+ break;
+
+ default:
+ failf(conn->data, "Unexpected continuation response");
+ *resp = -1;
+ break;
+ }
+
+ return TRUE;
+ }
+
+ return FALSE; /* Nothing for us */
+}
+
+/***********************************************************************
+ *
* imap_get_message()
*
* Gets the authentication message from the response buffer.
@@ -377,171 +377,171 @@ static void imap_get_message(char *buffer, char **outptr)
/***********************************************************************
*
- * state()
- *
- * This is the ONLY way to change IMAP state!
- */
-static void state(struct connectdata *conn, imapstate newstate)
-{
- struct imap_conn *imapc = &conn->proto.imapc;
-#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
- /* for debug purposes */
- static const char * const names[]={
- "STOP",
- "SERVERGREET",
- "CAPABILITY",
- "STARTTLS",
- "UPGRADETLS",
+ * state()
+ *
+ * This is the ONLY way to change IMAP state!
+ */
+static void state(struct connectdata *conn, imapstate newstate)
+{
+ struct imap_conn *imapc = &conn->proto.imapc;
+#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
+ /* for debug purposes */
+ static const char * const names[]={
+ "STOP",
+ "SERVERGREET",
+ "CAPABILITY",
+ "STARTTLS",
+ "UPGRADETLS",
"AUTHENTICATE",
- "LOGIN",
- "LIST",
- "SELECT",
- "FETCH",
- "FETCH_FINAL",
- "APPEND",
- "APPEND_FINAL",
+ "LOGIN",
+ "LIST",
+ "SELECT",
+ "FETCH",
+ "FETCH_FINAL",
+ "APPEND",
+ "APPEND_FINAL",
"SEARCH",
- "LOGOUT",
- /* LAST */
- };
-
- if(imapc->state != newstate)
- infof(conn->data, "IMAP %p state change from %s to %s\n",
- (void *)imapc, names[imapc->state], names[newstate]);
-#endif
-
- imapc->state = newstate;
-}
-
-/***********************************************************************
- *
- * imap_perform_capability()
- *
- * Sends the CAPABILITY command in order to obtain a list of server side
- * supported capabilities.
- */
-static CURLcode imap_perform_capability(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct imap_conn *imapc = &conn->proto.imapc;
+ "LOGOUT",
+ /* LAST */
+ };
+
+ if(imapc->state != newstate)
+ infof(conn->data, "IMAP %p state change from %s to %s\n",
+ (void *)imapc, names[imapc->state], names[newstate]);
+#endif
+
+ imapc->state = newstate;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_capability()
+ *
+ * Sends the CAPABILITY command in order to obtain a list of server side
+ * supported capabilities.
+ */
+static CURLcode imap_perform_capability(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct imap_conn *imapc = &conn->proto.imapc;
imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */
imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */
imapc->tls_supported = FALSE; /* Clear the TLS capability */
-
- /* Send the CAPABILITY command */
- result = imap_sendf(conn, "CAPABILITY");
-
- if(!result)
- state(conn, IMAP_CAPABILITY);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_starttls()
- *
- * Sends the STARTTLS command to start the upgrade to TLS.
- */
-static CURLcode imap_perform_starttls(struct connectdata *conn)
-{
- /* Send the STARTTLS command */
+
+ /* Send the CAPABILITY command */
+ result = imap_sendf(conn, "CAPABILITY");
+
+ if(!result)
+ state(conn, IMAP_CAPABILITY);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_starttls()
+ *
+ * Sends the STARTTLS command to start the upgrade to TLS.
+ */
+static CURLcode imap_perform_starttls(struct connectdata *conn)
+{
+ /* Send the STARTTLS command */
CURLcode result = imap_sendf(conn, "STARTTLS");
-
- if(!result)
- state(conn, IMAP_STARTTLS);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_upgrade_tls()
- *
- * Performs the upgrade to TLS.
- */
-static CURLcode imap_perform_upgrade_tls(struct connectdata *conn)
-{
+
+ if(!result)
+ state(conn, IMAP_STARTTLS);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_upgrade_tls()
+ *
+ * Performs the upgrade to TLS.
+ */
+static CURLcode imap_perform_upgrade_tls(struct connectdata *conn)
+{
/* Start the SSL connection */
- struct imap_conn *imapc = &conn->proto.imapc;
+ struct imap_conn *imapc = &conn->proto.imapc;
CURLcode result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET,
&imapc->ssldone);
-
- if(!result) {
- if(imapc->state != IMAP_UPGRADETLS)
- state(conn, IMAP_UPGRADETLS);
-
- if(imapc->ssldone) {
- imap_to_imaps(conn);
- result = imap_perform_capability(conn);
- }
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_login()
- *
- * Sends a clear text LOGIN command to authenticate with.
- */
-static CURLcode imap_perform_login(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- char *user;
- char *passwd;
-
- /* Check we have a username and password to authenticate with and end the
- connect phase if we don't */
- if(!conn->bits.user_passwd) {
- state(conn, IMAP_STOP);
-
- return result;
- }
-
- /* Make sure the username and password are in the correct atom format */
+
+ if(!result) {
+ if(imapc->state != IMAP_UPGRADETLS)
+ state(conn, IMAP_UPGRADETLS);
+
+ if(imapc->ssldone) {
+ imap_to_imaps(conn);
+ result = imap_perform_capability(conn);
+ }
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_login()
+ *
+ * Sends a clear text LOGIN command to authenticate with.
+ */
+static CURLcode imap_perform_login(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ char *user;
+ char *passwd;
+
+ /* Check we have a username and password to authenticate with and end the
+ connect phase if we don't */
+ if(!conn->bits.user_passwd) {
+ state(conn, IMAP_STOP);
+
+ return result;
+ }
+
+ /* Make sure the username and password are in the correct atom format */
user = imap_atom(conn->user, false);
passwd = imap_atom(conn->passwd, false);
-
- /* Send the LOGIN command */
- result = imap_sendf(conn, "LOGIN %s %s", user ? user : "",
- passwd ? passwd : "");
-
+
+ /* Send the LOGIN command */
+ result = imap_sendf(conn, "LOGIN %s %s", user ? user : "",
+ passwd ? passwd : "");
+
free(user);
free(passwd);
-
- if(!result)
- state(conn, IMAP_LOGIN);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_authenticate()
- *
+
+ if(!result)
+ state(conn, IMAP_LOGIN);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_authenticate()
+ *
* Sends an AUTHENTICATE command allowing the client to login with the given
* SASL authentication mechanism.
- */
+ */
static CURLcode imap_perform_authenticate(struct connectdata *conn,
const char *mech,
const char *initresp)
-{
- CURLcode result = CURLE_OK;
-
+{
+ CURLcode result = CURLE_OK;
+
if(initresp) {
/* Send the AUTHENTICATE command with the initial response */
result = imap_sendf(conn, "AUTHENTICATE %s %s", mech, initresp);
- }
+ }
else {
/* Send the AUTHENTICATE command */
result = imap_sendf(conn, "AUTHENTICATE %s", mech);
- }
-
+ }
+
return result;
}
-
+
/***********************************************************************
*
* imap_continue_authenticate()
@@ -552,10 +552,10 @@ static CURLcode imap_continue_authenticate(struct connectdata *conn,
const char *resp)
{
struct imap_conn *imapc = &conn->proto.imapc;
-
+
return Curl_pp_sendf(&imapc->pp, "%s", resp);
}
-
+
/***********************************************************************
*
* imap_perform_authentication()
@@ -576,115 +576,115 @@ static CURLcode imap_perform_authentication(struct connectdata *conn)
!Curl_sasl_can_authenticate(&imapc->sasl, conn)) {
state(conn, IMAP_STOP);
return result;
- }
-
+ }
+
/* Calculate the SASL login details */
result = Curl_sasl_start(&imapc->sasl, conn, imapc->ir_supported, &progress);
- if(!result) {
+ if(!result) {
if(progress == SASL_INPROGRESS)
state(conn, IMAP_AUTHENTICATE);
else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
- /* Perform clear text authentication */
- result = imap_perform_login(conn);
- else {
- /* Other mechanisms not supported */
- infof(conn->data, "No known authentication mechanisms supported!\n");
- result = CURLE_LOGIN_DENIED;
- }
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_list()
- *
- * Sends a LIST command or an alternative custom request.
- */
-static CURLcode imap_perform_list(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ /* Perform clear text authentication */
+ result = imap_perform_login(conn);
+ else {
+ /* Other mechanisms not supported */
+ infof(conn->data, "No known authentication mechanisms supported!\n");
+ result = CURLE_LOGIN_DENIED;
+ }
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_list()
+ *
+ * Sends a LIST command or an alternative custom request.
+ */
+static CURLcode imap_perform_list(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
-
- if(imap->custom)
- /* Send the custom request */
- result = imap_sendf(conn, "%s%s", imap->custom,
- imap->custom_params ? imap->custom_params : "");
- else {
+
+ if(imap->custom)
+ /* Send the custom request */
+ result = imap_sendf(conn, "%s%s", imap->custom,
+ imap->custom_params ? imap->custom_params : "");
+ else {
/* Make sure the mailbox is in the correct atom format if necessary */
char *mailbox = imap->mailbox ? imap_atom(imap->mailbox, true)
: strdup("");
- if(!mailbox)
- return CURLE_OUT_OF_MEMORY;
-
- /* Send the LIST command */
- result = imap_sendf(conn, "LIST \"%s\" *", mailbox);
-
+ if(!mailbox)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Send the LIST command */
+ result = imap_sendf(conn, "LIST \"%s\" *", mailbox);
+
free(mailbox);
- }
-
- if(!result)
- state(conn, IMAP_LIST);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_select()
- *
- * Sends a SELECT command to ask the server to change the selected mailbox.
- */
-static CURLcode imap_perform_select(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ }
+
+ if(!result)
+ state(conn, IMAP_LIST);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_select()
+ *
+ * Sends a SELECT command to ask the server to change the selected mailbox.
+ */
+static CURLcode imap_perform_select(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
- struct imap_conn *imapc = &conn->proto.imapc;
- char *mailbox;
-
- /* Invalidate old information as we are switching mailboxes */
- Curl_safefree(imapc->mailbox);
- Curl_safefree(imapc->mailbox_uidvalidity);
-
- /* Check we have a mailbox */
- if(!imap->mailbox) {
- failf(conn->data, "Cannot SELECT without a mailbox.");
- return CURLE_URL_MALFORMAT;
- }
-
- /* Make sure the mailbox is in the correct atom format */
+ struct imap_conn *imapc = &conn->proto.imapc;
+ char *mailbox;
+
+ /* Invalidate old information as we are switching mailboxes */
+ Curl_safefree(imapc->mailbox);
+ Curl_safefree(imapc->mailbox_uidvalidity);
+
+ /* Check we have a mailbox */
+ if(!imap->mailbox) {
+ failf(conn->data, "Cannot SELECT without a mailbox.");
+ return CURLE_URL_MALFORMAT;
+ }
+
+ /* Make sure the mailbox is in the correct atom format */
mailbox = imap_atom(imap->mailbox, false);
- if(!mailbox)
- return CURLE_OUT_OF_MEMORY;
-
- /* Send the SELECT command */
- result = imap_sendf(conn, "SELECT %s", mailbox);
-
+ if(!mailbox)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Send the SELECT command */
+ result = imap_sendf(conn, "SELECT %s", mailbox);
+
free(mailbox);
-
- if(!result)
- state(conn, IMAP_SELECT);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_fetch()
- *
- * Sends a FETCH command to initiate the download of a message.
- */
-static CURLcode imap_perform_fetch(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+
+ if(!result)
+ state(conn, IMAP_SELECT);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_fetch()
+ *
+ * Sends a FETCH command to initiate the download of a message.
+ */
+static CURLcode imap_perform_fetch(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct IMAP *imap = conn->data->req.p.imap;
/* Check we have a UID */
if(imap->uid) {
-
+
/* Send the FETCH command */
if(imap->partial)
result = imap_sendf(conn, "UID FETCH %s BODY[%s]<%s>",
@@ -695,9 +695,9 @@ static CURLcode imap_perform_fetch(struct connectdata *conn)
result = imap_sendf(conn, "UID FETCH %s BODY[%s]",
imap->uid,
imap->section ? imap->section : "");
- }
+ }
else if(imap->mindex) {
-
+
/* Send the FETCH command */
if(imap->partial)
result = imap_sendf(conn, "FETCH %s BODY[%s]<%s>",
@@ -713,31 +713,31 @@ static CURLcode imap_perform_fetch(struct connectdata *conn)
failf(conn->data, "Cannot FETCH without a UID.");
return CURLE_URL_MALFORMAT;
}
- if(!result)
- state(conn, IMAP_FETCH);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform_append()
- *
- * Sends an APPEND command to initiate the upload of a message.
- */
-static CURLcode imap_perform_append(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ if(!result)
+ state(conn, IMAP_FETCH);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform_append()
+ *
+ * Sends an APPEND command to initiate the upload of a message.
+ */
+static CURLcode imap_perform_append(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
- char *mailbox;
-
- /* Check we have a mailbox */
- if(!imap->mailbox) {
+ char *mailbox;
+
+ /* Check we have a mailbox */
+ if(!imap->mailbox) {
failf(data, "Cannot APPEND without a mailbox.");
- return CURLE_URL_MALFORMAT;
- }
-
+ return CURLE_URL_MALFORMAT;
+ }
+
/* Prepare the mime data if some. */
if(data->set.mimepost.kind != MIMEKIND_NONE) {
/* Use the whole structure as data. */
@@ -767,31 +767,31 @@ static CURLcode imap_perform_append(struct connectdata *conn)
data->state.in = (void *) &data->set.mimepost;
}
- /* Check we know the size of the upload */
+ /* Check we know the size of the upload */
if(data->state.infilesize < 0) {
failf(data, "Cannot APPEND with unknown input file size\n");
- return CURLE_UPLOAD_FAILED;
- }
-
- /* Make sure the mailbox is in the correct atom format */
+ return CURLE_UPLOAD_FAILED;
+ }
+
+ /* Make sure the mailbox is in the correct atom format */
mailbox = imap_atom(imap->mailbox, false);
- if(!mailbox)
- return CURLE_OUT_OF_MEMORY;
-
- /* Send the APPEND command */
+ if(!mailbox)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Send the APPEND command */
result = imap_sendf(conn, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}",
mailbox, data->state.infilesize);
-
+
free(mailbox);
-
- if(!result)
- state(conn, IMAP_APPEND);
-
- return result;
-}
-
-/***********************************************************************
- *
+
+ if(!result)
+ state(conn, IMAP_APPEND);
+
+ return result;
+}
+
+/***********************************************************************
+ *
* imap_perform_search()
*
* Sends a SEARCH command.
@@ -818,29 +818,29 @@ static CURLcode imap_perform_search(struct connectdata *conn)
/***********************************************************************
*
- * imap_perform_logout()
- *
- * Performs the logout action prior to sclose() being called.
- */
-static CURLcode imap_perform_logout(struct connectdata *conn)
-{
- /* Send the LOGOUT command */
+ * imap_perform_logout()
+ *
+ * Performs the logout action prior to sclose() being called.
+ */
+static CURLcode imap_perform_logout(struct connectdata *conn)
+{
+ /* Send the LOGOUT command */
CURLcode result = imap_sendf(conn, "LOGOUT");
-
- if(!result)
- state(conn, IMAP_LOGOUT);
-
- return result;
-}
-
-/* For the initial server greeting */
-static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
- int imapcode,
- imapstate instate)
-{
+
+ if(!result)
+ state(conn, IMAP_LOGOUT);
+
+ return result;
+}
+
+/* For the initial server greeting */
+static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
+ int imapcode,
+ imapstate instate)
+{
struct Curl_easy *data = conn->data;
- (void)instate; /* no use for this yet */
-
+ (void)instate; /* no use for this yet */
+
if(imapcode == IMAP_RESP_PREAUTH) {
/* PREAUTH */
struct imap_conn *imapc = &conn->proto.imapc;
@@ -848,136 +848,136 @@ static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
infof(data, "PREAUTH connection, already authenticated!\n");
}
else if(imapcode != IMAP_RESP_OK) {
- failf(data, "Got unexpected imap-server response");
+ failf(data, "Got unexpected imap-server response");
return CURLE_WEIRD_SERVER_REPLY;
- }
-
+ }
+
return imap_perform_capability(conn);
-}
-
-/* For CAPABILITY responses */
-static CURLcode imap_state_capability_resp(struct connectdata *conn,
- int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
+}
+
+/* For CAPABILITY responses */
+static CURLcode imap_state_capability_resp(struct connectdata *conn,
+ int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct imap_conn *imapc = &conn->proto.imapc;
- const char *line = data->state.buffer;
-
- (void)instate; /* no use for this yet */
-
- /* Do we have a untagged response? */
- if(imapcode == '*') {
- line += 2;
-
- /* Loop through the data line */
- for(;;) {
+ struct imap_conn *imapc = &conn->proto.imapc;
+ const char *line = data->state.buffer;
+
+ (void)instate; /* no use for this yet */
+
+ /* Do we have a untagged response? */
+ if(imapcode == '*') {
+ line += 2;
+
+ /* Loop through the data line */
+ for(;;) {
size_t wordlen;
- while(*line &&
- (*line == ' ' || *line == '\t' ||
- *line == '\r' || *line == '\n')) {
-
- line++;
- }
-
- if(!*line)
- break;
-
- /* Extract the word */
- for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' &&
- line[wordlen] != '\t' && line[wordlen] != '\r' &&
- line[wordlen] != '\n';)
- wordlen++;
-
- /* Does the server support the STARTTLS capability? */
- if(wordlen == 8 && !memcmp(line, "STARTTLS", 8))
- imapc->tls_supported = TRUE;
-
- /* Has the server explicitly disabled clear text authentication? */
- else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13))
- imapc->login_disabled = TRUE;
-
- /* Does the server support the SASL-IR capability? */
- else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7))
- imapc->ir_supported = TRUE;
-
- /* Do we have a SASL based authentication mechanism? */
- else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) {
+ while(*line &&
+ (*line == ' ' || *line == '\t' ||
+ *line == '\r' || *line == '\n')) {
+
+ line++;
+ }
+
+ if(!*line)
+ break;
+
+ /* Extract the word */
+ for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' &&
+ line[wordlen] != '\t' && line[wordlen] != '\r' &&
+ line[wordlen] != '\n';)
+ wordlen++;
+
+ /* Does the server support the STARTTLS capability? */
+ if(wordlen == 8 && !memcmp(line, "STARTTLS", 8))
+ imapc->tls_supported = TRUE;
+
+ /* Has the server explicitly disabled clear text authentication? */
+ else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13))
+ imapc->login_disabled = TRUE;
+
+ /* Does the server support the SASL-IR capability? */
+ else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7))
+ imapc->ir_supported = TRUE;
+
+ /* Do we have a SASL based authentication mechanism? */
+ else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) {
size_t llen;
unsigned int mechbit;
- line += 5;
- wordlen -= 5;
-
- /* Test the word for a matching authentication mechanism */
+ line += 5;
+ wordlen -= 5;
+
+ /* Test the word for a matching authentication mechanism */
mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
if(mechbit && llen == wordlen)
imapc->sasl.authmechs |= mechbit;
- }
-
- line += wordlen;
- }
- }
+ }
+
+ line += wordlen;
+ }
+ }
else if(imapcode == IMAP_RESP_OK) {
- if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
- /* We don't have a SSL/TLS connection yet, but SSL is requested */
- if(imapc->tls_supported)
- /* Switch to TLS connection now */
- result = imap_perform_starttls(conn);
- else if(data->set.use_ssl == CURLUSESSL_TRY)
- /* Fallback and carry on with authentication */
+ if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
+ /* We don't have a SSL/TLS connection yet, but SSL is requested */
+ if(imapc->tls_supported)
+ /* Switch to TLS connection now */
+ result = imap_perform_starttls(conn);
+ else if(data->set.use_ssl == CURLUSESSL_TRY)
+ /* Fallback and carry on with authentication */
result = imap_perform_authentication(conn);
- else {
- failf(data, "STARTTLS not supported.");
- result = CURLE_USE_SSL_FAILED;
- }
- }
- else
+ else {
+ failf(data, "STARTTLS not supported.");
+ result = CURLE_USE_SSL_FAILED;
+ }
+ }
+ else
result = imap_perform_authentication(conn);
- }
- else
+ }
+ else
result = imap_perform_authentication(conn);
-
- return result;
-}
-
-/* For STARTTLS responses */
-static CURLcode imap_state_starttls_resp(struct connectdata *conn,
- int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
+
+ return result;
+}
+
+/* For STARTTLS responses */
+static CURLcode imap_state_starttls_resp(struct connectdata *conn,
+ int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
if(imapcode != IMAP_RESP_OK) {
- if(data->set.use_ssl != CURLUSESSL_TRY) {
+ if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied");
- result = CURLE_USE_SSL_FAILED;
- }
- else
+ result = CURLE_USE_SSL_FAILED;
+ }
+ else
result = imap_perform_authentication(conn);
- }
- else
- result = imap_perform_upgrade_tls(conn);
-
- return result;
-}
-
+ }
+ else
+ result = imap_perform_upgrade_tls(conn);
+
+ return result;
+}
+
/* For SASL authentication responses */
static CURLcode imap_state_auth_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct imap_conn *imapc = &conn->proto.imapc;
saslprogress progress;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
result = Curl_sasl_continue(&imapc->sasl, conn, imapcode, &progress);
if(!result)
switch(progress) {
@@ -991,761 +991,761 @@ static CURLcode imap_state_auth_resp(struct connectdata *conn,
else {
failf(data, "Authentication cancelled");
result = CURLE_LOGIN_DENIED;
- }
+ }
break;
default:
break;
- }
-
- return result;
-}
-
-/* For LOGIN responses */
-static CURLcode imap_state_login_resp(struct connectdata *conn,
- int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+
+ return result;
+}
+
+/* For LOGIN responses */
+static CURLcode imap_state_login_resp(struct connectdata *conn,
+ int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
if(imapcode != IMAP_RESP_OK) {
- failf(data, "Access denied. %c", imapcode);
- result = CURLE_LOGIN_DENIED;
- }
- else
- /* End of connect phase */
- state(conn, IMAP_STOP);
-
- return result;
-}
-
+ failf(data, "Access denied. %c", imapcode);
+ result = CURLE_LOGIN_DENIED;
+ }
+ else
+ /* End of connect phase */
+ state(conn, IMAP_STOP);
+
+ return result;
+}
+
/* For LIST and SEARCH responses */
static CURLcode imap_state_listsearch_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
-{
- CURLcode result = CURLE_OK;
- char *line = conn->data->state.buffer;
- size_t len = strlen(line);
-
- (void)instate; /* No use for this yet */
-
- if(imapcode == '*') {
- /* Temporarily add the LF character back and send as body to the client */
- line[len] = '\n';
- result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
- line[len] = '\0';
- }
+{
+ CURLcode result = CURLE_OK;
+ char *line = conn->data->state.buffer;
+ size_t len = strlen(line);
+
+ (void)instate; /* No use for this yet */
+
+ if(imapcode == '*') {
+ /* Temporarily add the LF character back and send as body to the client */
+ line[len] = '\n';
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
+ line[len] = '\0';
+ }
else if(imapcode != IMAP_RESP_OK)
result = CURLE_QUOTE_ERROR;
- else
- /* End of DO phase */
- state(conn, IMAP_STOP);
-
- return result;
-}
-
-/* For SELECT responses */
-static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
+ else
+ /* End of DO phase */
+ state(conn, IMAP_STOP);
+
+ return result;
+}
+
+/* For SELECT responses */
+static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = conn->data->req.p.imap;
- struct imap_conn *imapc = &conn->proto.imapc;
- const char *line = data->state.buffer;
-
- (void)instate; /* no use for this yet */
-
- if(imapcode == '*') {
- /* See if this is an UIDVALIDITY response */
+ struct imap_conn *imapc = &conn->proto.imapc;
+ const char *line = data->state.buffer;
+
+ (void)instate; /* no use for this yet */
+
+ if(imapcode == '*') {
+ /* See if this is an UIDVALIDITY response */
char tmp[20];
- if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) {
- Curl_safefree(imapc->mailbox_uidvalidity);
- imapc->mailbox_uidvalidity = strdup(tmp);
- }
- }
+ if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) {
+ Curl_safefree(imapc->mailbox_uidvalidity);
+ imapc->mailbox_uidvalidity = strdup(tmp);
+ }
+ }
else if(imapcode == IMAP_RESP_OK) {
- /* Check if the UIDVALIDITY has been specified and matches */
- if(imap->uidvalidity && imapc->mailbox_uidvalidity &&
+ /* Check if the UIDVALIDITY has been specified and matches */
+ if(imap->uidvalidity && imapc->mailbox_uidvalidity &&
!strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity)) {
- failf(conn->data, "Mailbox UIDVALIDITY has changed");
- result = CURLE_REMOTE_FILE_NOT_FOUND;
- }
- else {
- /* Note the currently opened mailbox on this connection */
- imapc->mailbox = strdup(imap->mailbox);
-
- if(imap->custom)
- result = imap_perform_list(conn);
+ failf(conn->data, "Mailbox UIDVALIDITY has changed");
+ result = CURLE_REMOTE_FILE_NOT_FOUND;
+ }
+ else {
+ /* Note the currently opened mailbox on this connection */
+ imapc->mailbox = strdup(imap->mailbox);
+
+ if(imap->custom)
+ result = imap_perform_list(conn);
else if(imap->query)
result = imap_perform_search(conn);
- else
- result = imap_perform_fetch(conn);
- }
- }
- else {
- failf(data, "Select failed");
- result = CURLE_LOGIN_DENIED;
- }
-
- return result;
-}
-
-/* For the (first line of the) FETCH responses */
-static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
+ else
+ result = imap_perform_fetch(conn);
+ }
+ }
+ else {
+ failf(data, "Select failed");
+ result = CURLE_LOGIN_DENIED;
+ }
+
+ return result;
+}
+
+/* For the (first line of the) FETCH responses */
+static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct imap_conn *imapc = &conn->proto.imapc;
- struct pingpong *pp = &imapc->pp;
- const char *ptr = data->state.buffer;
- bool parsed = FALSE;
+ struct imap_conn *imapc = &conn->proto.imapc;
+ struct pingpong *pp = &imapc->pp;
+ const char *ptr = data->state.buffer;
+ bool parsed = FALSE;
curl_off_t size = 0;
-
- (void)instate; /* no use for this yet */
-
- if(imapcode != '*') {
+
+ (void)instate; /* no use for this yet */
+
+ if(imapcode != '*') {
Curl_pgrsSetDownloadSize(data, -1);
- state(conn, IMAP_STOP);
+ state(conn, IMAP_STOP);
return CURLE_REMOTE_FILE_NOT_FOUND;
- }
-
- /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
- the continuation data contained within the curly brackets */
- while(*ptr && (*ptr != '{'))
- ptr++;
-
- if(*ptr == '{') {
- char *endptr;
+ }
+
+ /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
+ the continuation data contained within the curly brackets */
+ while(*ptr && (*ptr != '{'))
+ ptr++;
+
+ if(*ptr == '{') {
+ char *endptr;
if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size)) {
if(endptr - ptr > 1 && endptr[0] == '}' &&
endptr[1] == '\r' && endptr[2] == '\0')
parsed = TRUE;
}
- }
-
- if(parsed) {
+ }
+
+ if(parsed) {
infof(data, "Found %" CURL_FORMAT_CURL_OFF_T " bytes to download\n",
size);
- Curl_pgrsSetDownloadSize(data, size);
-
- if(pp->cache) {
- /* At this point there is a bunch of data in the header "cache" that is
- actually body content, send it as body and then skip it. Do note
- that there may even be additional "headers" after the body. */
- size_t chunk = pp->cache_size;
-
- if(chunk > (size_t)size)
- /* The conversion from curl_off_t to size_t is always fine here */
- chunk = (size_t)size;
-
+ Curl_pgrsSetDownloadSize(data, size);
+
+ if(pp->cache) {
+ /* At this point there is a bunch of data in the header "cache" that is
+ actually body content, send it as body and then skip it. Do note
+ that there may even be additional "headers" after the body. */
+ size_t chunk = pp->cache_size;
+
+ if(chunk > (size_t)size)
+ /* The conversion from curl_off_t to size_t is always fine here */
+ chunk = (size_t)size;
+
if(!chunk) {
/* no size, we're done with the data */
state(conn, IMAP_STOP);
return CURLE_OK;
}
- result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
- if(result)
- return result;
-
- data->req.bytecount += chunk;
-
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
+ if(result)
+ return result;
+
+ data->req.bytecount += chunk;
+
infof(data, "Written %zu bytes, %" CURL_FORMAT_CURL_OFF_TU
" bytes are left for transfer\n", chunk, size - chunk);
-
- /* Have we used the entire cache or just part of it?*/
- if(pp->cache_size > chunk) {
- /* Only part of it so shrink the cache to fit the trailing data */
- memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);
- pp->cache_size -= chunk;
- }
- else {
- /* Free the cache */
- Curl_safefree(pp->cache);
-
- /* Reset the cache size */
- pp->cache_size = 0;
- }
- }
-
- if(data->req.bytecount == size)
- /* The entire data is already transferred! */
+
+ /* Have we used the entire cache or just part of it?*/
+ if(pp->cache_size > chunk) {
+ /* Only part of it so shrink the cache to fit the trailing data */
+ memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);
+ pp->cache_size -= chunk;
+ }
+ else {
+ /* Free the cache */
+ Curl_safefree(pp->cache);
+
+ /* Reset the cache size */
+ pp->cache_size = 0;
+ }
+ }
+
+ if(data->req.bytecount == size)
+ /* The entire data is already transferred! */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
- else {
- /* IMAP download */
- data->req.maxdownload = size;
+ else {
+ /* IMAP download */
+ data->req.maxdownload = size;
/* force a recv/send check of this connection, as the data might've been
read off the socket already */
data->conn->cselect_bits = CURL_CSELECT_IN;
Curl_setup_transfer(data, FIRSTSOCKET, size, FALSE, -1);
- }
- }
- else {
- /* We don't know how to parse this line */
- failf(pp->conn->data, "Failed to parse FETCH response.");
+ }
+ }
+ else {
+ /* We don't know how to parse this line */
+ failf(pp->conn->data, "Failed to parse FETCH response.");
result = CURLE_WEIRD_SERVER_REPLY;
- }
-
- /* End of DO phase */
- state(conn, IMAP_STOP);
-
- return result;
-}
-
-/* For final FETCH responses performed after the download */
-static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
- int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
-
- (void)instate; /* No use for this yet */
-
+ }
+
+ /* End of DO phase */
+ state(conn, IMAP_STOP);
+
+ return result;
+}
+
+/* For final FETCH responses performed after the download */
+static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
+ int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
+
+ (void)instate; /* No use for this yet */
+
if(imapcode != IMAP_RESP_OK)
result = CURLE_WEIRD_SERVER_REPLY;
- else
- /* End of DONE phase */
- state(conn, IMAP_STOP);
-
- return result;
-}
-
-/* For APPEND responses */
-static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
+ else
+ /* End of DONE phase */
+ state(conn, IMAP_STOP);
+
+ return result;
+}
+
+/* For APPEND responses */
+static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* No use for this yet */
-
- if(imapcode != '+') {
- result = CURLE_UPLOAD_FAILED;
- }
- else {
- /* Set the progress upload size */
+
+ (void)instate; /* No use for this yet */
+
+ if(imapcode != '+') {
+ result = CURLE_UPLOAD_FAILED;
+ }
+ else {
+ /* Set the progress upload size */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
-
- /* IMAP upload */
+
+ /* IMAP upload */
Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET);
-
- /* End of DO phase */
- state(conn, IMAP_STOP);
- }
-
- return result;
-}
-
-/* For final APPEND responses performed after the upload */
-static CURLcode imap_state_append_final_resp(struct connectdata *conn,
- int imapcode,
- imapstate instate)
-{
- CURLcode result = CURLE_OK;
-
- (void)instate; /* No use for this yet */
-
+
+ /* End of DO phase */
+ state(conn, IMAP_STOP);
+ }
+
+ return result;
+}
+
+/* For final APPEND responses performed after the upload */
+static CURLcode imap_state_append_final_resp(struct connectdata *conn,
+ int imapcode,
+ imapstate instate)
+{
+ CURLcode result = CURLE_OK;
+
+ (void)instate; /* No use for this yet */
+
if(imapcode != IMAP_RESP_OK)
- result = CURLE_UPLOAD_FAILED;
- else
- /* End of DONE phase */
- state(conn, IMAP_STOP);
-
- return result;
-}
-
-static CURLcode imap_statemach_act(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- curl_socket_t sock = conn->sock[FIRSTSOCKET];
- int imapcode;
- struct imap_conn *imapc = &conn->proto.imapc;
- struct pingpong *pp = &imapc->pp;
- size_t nread = 0;
-
- /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
- if(imapc->state == IMAP_UPGRADETLS)
- return imap_perform_upgrade_tls(conn);
-
- /* Flush any data that needs to be sent */
- if(pp->sendleft)
- return Curl_pp_flushsend(pp);
-
- do {
- /* Read the response from the server */
- result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
- if(result)
- return result;
-
- /* Was there an error parsing the response line? */
- if(imapcode == -1)
+ result = CURLE_UPLOAD_FAILED;
+ else
+ /* End of DONE phase */
+ state(conn, IMAP_STOP);
+
+ return result;
+}
+
+static CURLcode imap_statemach_act(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
+ int imapcode;
+ struct imap_conn *imapc = &conn->proto.imapc;
+ struct pingpong *pp = &imapc->pp;
+ size_t nread = 0;
+
+ /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
+ if(imapc->state == IMAP_UPGRADETLS)
+ return imap_perform_upgrade_tls(conn);
+
+ /* Flush any data that needs to be sent */
+ if(pp->sendleft)
+ return Curl_pp_flushsend(pp);
+
+ do {
+ /* Read the response from the server */
+ result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
+ if(result)
+ return result;
+
+ /* Was there an error parsing the response line? */
+ if(imapcode == -1)
return CURLE_WEIRD_SERVER_REPLY;
-
- if(!imapcode)
- break;
-
- /* We have now received a full IMAP server response */
- switch(imapc->state) {
- case IMAP_SERVERGREET:
- result = imap_state_servergreet_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_CAPABILITY:
- result = imap_state_capability_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_STARTTLS:
- result = imap_state_starttls_resp(conn, imapcode, imapc->state);
- break;
-
+
+ if(!imapcode)
+ break;
+
+ /* We have now received a full IMAP server response */
+ switch(imapc->state) {
+ case IMAP_SERVERGREET:
+ result = imap_state_servergreet_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_CAPABILITY:
+ result = imap_state_capability_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_STARTTLS:
+ result = imap_state_starttls_resp(conn, imapcode, imapc->state);
+ break;
+
case IMAP_AUTHENTICATE:
result = imap_state_auth_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_LOGIN:
- result = imap_state_login_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_LIST:
+ break;
+
+ case IMAP_LOGIN:
+ result = imap_state_login_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_LIST:
case IMAP_SEARCH:
result = imap_state_listsearch_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_SELECT:
- result = imap_state_select_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_FETCH:
- result = imap_state_fetch_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_FETCH_FINAL:
- result = imap_state_fetch_final_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_APPEND:
- result = imap_state_append_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_APPEND_FINAL:
- result = imap_state_append_final_resp(conn, imapcode, imapc->state);
- break;
-
- case IMAP_LOGOUT:
- /* fallthrough, just stop! */
- default:
- /* internal error */
- state(conn, IMAP_STOP);
- break;
- }
- } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp));
-
- return result;
-}
-
-/* Called repeatedly until done from multi.c */
-static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
- struct imap_conn *imapc = &conn->proto.imapc;
-
- if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) {
- result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
- if(result || !imapc->ssldone)
- return result;
- }
-
+ break;
+
+ case IMAP_SELECT:
+ result = imap_state_select_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_FETCH:
+ result = imap_state_fetch_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_FETCH_FINAL:
+ result = imap_state_fetch_final_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_APPEND:
+ result = imap_state_append_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_APPEND_FINAL:
+ result = imap_state_append_final_resp(conn, imapcode, imapc->state);
+ break;
+
+ case IMAP_LOGOUT:
+ /* fallthrough, just stop! */
+ default:
+ /* internal error */
+ state(conn, IMAP_STOP);
+ break;
+ }
+ } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp));
+
+ return result;
+}
+
+/* Called repeatedly until done from multi.c */
+static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+ struct imap_conn *imapc = &conn->proto.imapc;
+
+ if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) {
+ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
+ if(result || !imapc->ssldone)
+ return result;
+ }
+
result = Curl_pp_statemach(&imapc->pp, FALSE, FALSE);
- *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
-
- return result;
-}
-
+ *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
+
+ return result;
+}
+
static CURLcode imap_block_statemach(struct connectdata *conn,
bool disconnecting)
-{
- CURLcode result = CURLE_OK;
- struct imap_conn *imapc = &conn->proto.imapc;
-
- while(imapc->state != IMAP_STOP && !result)
+{
+ CURLcode result = CURLE_OK;
+ struct imap_conn *imapc = &conn->proto.imapc;
+
+ while(imapc->state != IMAP_STOP && !result)
result = Curl_pp_statemach(&imapc->pp, TRUE, disconnecting);
-
- return result;
-}
-
+
+ return result;
+}
+
/* Allocate and initialize the struct IMAP for the current Curl_easy if
- required */
-static CURLcode imap_init(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ required */
+static CURLcode imap_init(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct IMAP *imap;
-
+ struct IMAP *imap;
+
imap = data->req.p.imap = calloc(sizeof(struct IMAP), 1);
- if(!imap)
- result = CURLE_OUT_OF_MEMORY;
-
- return result;
-}
-
-/* For the IMAP "protocol connect" and "doing" phases only */
+ if(!imap)
+ result = CURLE_OUT_OF_MEMORY;
+
+ return result;
+}
+
+/* For the IMAP "protocol connect" and "doing" phases only */
static int imap_getsock(struct connectdata *conn, curl_socket_t *socks)
-{
+{
return Curl_pp_getsock(&conn->proto.imapc.pp, socks);
-}
-
-/***********************************************************************
- *
- * imap_connect()
- *
- * This function should do everything that is to be considered a part of the
- * connection phase.
- *
- * The variable 'done' points to will be TRUE if the protocol-layer connect
- * phase is done when this function returns, or FALSE if not.
- */
-static CURLcode imap_connect(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
- struct imap_conn *imapc = &conn->proto.imapc;
- struct pingpong *pp = &imapc->pp;
-
- *done = FALSE; /* default to not done yet */
-
- /* We always support persistent connections in IMAP */
+}
+
+/***********************************************************************
+ *
+ * imap_connect()
+ *
+ * This function should do everything that is to be considered a part of the
+ * connection phase.
+ *
+ * The variable 'done' points to will be TRUE if the protocol-layer connect
+ * phase is done when this function returns, or FALSE if not.
+ */
+static CURLcode imap_connect(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+ struct imap_conn *imapc = &conn->proto.imapc;
+ struct pingpong *pp = &imapc->pp;
+
+ *done = FALSE; /* default to not done yet */
+
+ /* We always support persistent connections in IMAP */
connkeep(conn, "IMAP default");
-
- /* Set the default response time-out */
- pp->response_time = RESP_TIMEOUT;
- pp->statemach_act = imap_statemach_act;
- pp->endofresp = imap_endofresp;
- pp->conn = conn;
-
+
+ /* Set the default response time-out */
+ pp->response_time = RESP_TIMEOUT;
+ pp->statemach_act = imap_statemach_act;
+ pp->endofresp = imap_endofresp;
+ pp->conn = conn;
+
/* Set the default preferred authentication type and mechanism */
imapc->preftype = IMAP_TYPE_ANY;
Curl_sasl_init(&imapc->sasl, &saslimap);
-
+
Curl_dyn_init(&imapc->dyn, DYN_IMAP_CMD);
- /* Initialise the pingpong layer */
+ /* Initialise the pingpong layer */
Curl_pp_setup(pp);
- Curl_pp_init(pp);
-
- /* Parse the URL options */
- result = imap_parse_url_options(conn);
- if(result)
- return result;
-
- /* Start off waiting for the server greeting response */
- state(conn, IMAP_SERVERGREET);
-
- /* Start off with an response id of '*' */
- strcpy(imapc->resptag, "*");
-
- result = imap_multi_statemach(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_done()
- *
- * The DONE function. This does what needs to be done after a single DO has
- * performed.
- *
- * Input argument is already checked for validity.
- */
-static CURLcode imap_done(struct connectdata *conn, CURLcode status,
- bool premature)
-{
- CURLcode result = CURLE_OK;
+ Curl_pp_init(pp);
+
+ /* Parse the URL options */
+ result = imap_parse_url_options(conn);
+ if(result)
+ return result;
+
+ /* Start off waiting for the server greeting response */
+ state(conn, IMAP_SERVERGREET);
+
+ /* Start off with an response id of '*' */
+ strcpy(imapc->resptag, "*");
+
+ result = imap_multi_statemach(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_done()
+ *
+ * The DONE function. This does what needs to be done after a single DO has
+ * performed.
+ *
+ * Input argument is already checked for validity.
+ */
+static CURLcode imap_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
-
- (void)premature;
-
- if(!imap)
- return CURLE_OK;
-
- if(status) {
+
+ (void)premature;
+
+ if(!imap)
+ return CURLE_OK;
+
+ if(status) {
connclose(conn, "IMAP done with bad status"); /* marked for closure */
- result = status; /* use the already set error code */
- }
- else if(!data->set.connect_only && !imap->custom &&
+ result = status; /* use the already set error code */
+ }
+ else if(!data->set.connect_only && !imap->custom &&
(imap->uid || imap->mindex || data->set.upload ||
data->set.mimepost.kind != MIMEKIND_NONE)) {
- /* Handle responses after FETCH or APPEND transfer has finished */
+ /* Handle responses after FETCH or APPEND transfer has finished */
if(!data->set.upload && data->set.mimepost.kind == MIMEKIND_NONE)
- state(conn, IMAP_FETCH_FINAL);
- else {
- /* End the APPEND command first by sending an empty line */
- result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "");
- if(!result)
- state(conn, IMAP_APPEND_FINAL);
- }
-
+ state(conn, IMAP_FETCH_FINAL);
+ else {
+ /* End the APPEND command first by sending an empty line */
+ result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "");
+ if(!result)
+ state(conn, IMAP_APPEND_FINAL);
+ }
+
/* Run the state-machine */
- if(!result)
+ if(!result)
result = imap_block_statemach(conn, FALSE);
- }
-
- /* Cleanup our per-request based variables */
- Curl_safefree(imap->mailbox);
- Curl_safefree(imap->uidvalidity);
- Curl_safefree(imap->uid);
+ }
+
+ /* Cleanup our per-request based variables */
+ Curl_safefree(imap->mailbox);
+ Curl_safefree(imap->uidvalidity);
+ Curl_safefree(imap->uid);
Curl_safefree(imap->mindex);
- Curl_safefree(imap->section);
+ Curl_safefree(imap->section);
Curl_safefree(imap->partial);
Curl_safefree(imap->query);
- Curl_safefree(imap->custom);
- Curl_safefree(imap->custom_params);
-
- /* Clear the transfer mode for the next request */
- imap->transfer = FTPTRANSFER_BODY;
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_perform()
- *
- * This is the actual DO function for IMAP. Fetch or append a message, or do
- * other things according to the options previously setup.
- */
-static CURLcode imap_perform(struct connectdata *conn, bool *connected,
- bool *dophase_done)
-{
- /* This is IMAP and no proxy */
- CURLcode result = CURLE_OK;
+ Curl_safefree(imap->custom);
+ Curl_safefree(imap->custom_params);
+
+ /* Clear the transfer mode for the next request */
+ imap->transfer = FTPTRANSFER_BODY;
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_perform()
+ *
+ * This is the actual DO function for IMAP. Fetch or append a message, or do
+ * other things according to the options previously setup.
+ */
+static CURLcode imap_perform(struct connectdata *conn, bool *connected,
+ bool *dophase_done)
+{
+ /* This is IMAP and no proxy */
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
- struct imap_conn *imapc = &conn->proto.imapc;
- bool selected = FALSE;
-
- DEBUGF(infof(conn->data, "DO phase starts\n"));
-
- if(conn->data->set.opt_no_body) {
- /* Requested no body means no transfer */
- imap->transfer = FTPTRANSFER_INFO;
- }
-
- *dophase_done = FALSE; /* not done yet */
-
- /* Determine if the requested mailbox (with the same UIDVALIDITY if set)
- has already been selected on this connection */
- if(imap->mailbox && imapc->mailbox &&
+ struct imap_conn *imapc = &conn->proto.imapc;
+ bool selected = FALSE;
+
+ DEBUGF(infof(conn->data, "DO phase starts\n"));
+
+ if(conn->data->set.opt_no_body) {
+ /* Requested no body means no transfer */
+ imap->transfer = FTPTRANSFER_INFO;
+ }
+
+ *dophase_done = FALSE; /* not done yet */
+
+ /* Determine if the requested mailbox (with the same UIDVALIDITY if set)
+ has already been selected on this connection */
+ if(imap->mailbox && imapc->mailbox &&
strcasecompare(imap->mailbox, imapc->mailbox) &&
- (!imap->uidvalidity || !imapc->mailbox_uidvalidity ||
+ (!imap->uidvalidity || !imapc->mailbox_uidvalidity ||
strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity)))
- selected = TRUE;
-
- /* Start the first command in the DO phase */
+ selected = TRUE;
+
+ /* Start the first command in the DO phase */
if(conn->data->set.upload || data->set.mimepost.kind != MIMEKIND_NONE)
- /* APPEND can be executed directly */
- result = imap_perform_append(conn);
- else if(imap->custom && (selected || !imap->mailbox))
- /* Custom command using the same mailbox or no mailbox */
- result = imap_perform_list(conn);
+ /* APPEND can be executed directly */
+ result = imap_perform_append(conn);
+ else if(imap->custom && (selected || !imap->mailbox))
+ /* Custom command using the same mailbox or no mailbox */
+ result = imap_perform_list(conn);
else if(!imap->custom && selected && (imap->uid || imap->mindex))
- /* FETCH from the same mailbox */
- result = imap_perform_fetch(conn);
+ /* FETCH from the same mailbox */
+ result = imap_perform_fetch(conn);
else if(!imap->custom && selected && imap->query)
/* SEARCH the current mailbox */
result = imap_perform_search(conn);
else if(imap->mailbox && !selected &&
(imap->custom || imap->uid || imap->mindex || imap->query))
- /* SELECT the mailbox */
- result = imap_perform_select(conn);
- else
- /* LIST */
- result = imap_perform_list(conn);
-
- if(result)
- return result;
-
- /* Run the state-machine */
- result = imap_multi_statemach(conn, dophase_done);
-
- *connected = conn->bits.tcpconnect[FIRSTSOCKET];
-
- if(*dophase_done)
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_do()
- *
- * This function is registered as 'curl_do' function. It decodes the path
- * parts etc as a wrapper to the actual DO function (imap_perform).
- *
- * The input argument is already checked for validity.
- */
-static CURLcode imap_do(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
-
- *done = FALSE; /* default to false */
-
- /* Parse the URL path */
- result = imap_parse_url_path(conn);
- if(result)
- return result;
-
- /* Parse the custom request */
- result = imap_parse_custom_request(conn);
- if(result)
- return result;
-
- result = imap_regular_transfer(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_disconnect()
- *
- * Disconnect from an IMAP server. Cleanup protocol-specific per-connection
- * resources. BLOCKING.
- */
-static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
-{
- struct imap_conn *imapc = &conn->proto.imapc;
-
- /* We cannot send quit unconditionally. If this connection is stale or
- bad in any way, sending quit and waiting around here will make the
- disconnect wait in vain and cause more problems than we need to. */
-
- /* The IMAP session may or may not have been allocated/setup at this
- point! */
+ /* SELECT the mailbox */
+ result = imap_perform_select(conn);
+ else
+ /* LIST */
+ result = imap_perform_list(conn);
+
+ if(result)
+ return result;
+
+ /* Run the state-machine */
+ result = imap_multi_statemach(conn, dophase_done);
+
+ *connected = conn->bits.tcpconnect[FIRSTSOCKET];
+
+ if(*dophase_done)
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_do()
+ *
+ * This function is registered as 'curl_do' function. It decodes the path
+ * parts etc as a wrapper to the actual DO function (imap_perform).
+ *
+ * The input argument is already checked for validity.
+ */
+static CURLcode imap_do(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+
+ *done = FALSE; /* default to false */
+
+ /* Parse the URL path */
+ result = imap_parse_url_path(conn);
+ if(result)
+ return result;
+
+ /* Parse the custom request */
+ result = imap_parse_custom_request(conn);
+ if(result)
+ return result;
+
+ result = imap_regular_transfer(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_disconnect()
+ *
+ * Disconnect from an IMAP server. Cleanup protocol-specific per-connection
+ * resources. BLOCKING.
+ */
+static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
+{
+ struct imap_conn *imapc = &conn->proto.imapc;
+
+ /* We cannot send quit unconditionally. If this connection is stale or
+ bad in any way, sending quit and waiting around here will make the
+ disconnect wait in vain and cause more problems than we need to. */
+
+ /* The IMAP session may or may not have been allocated/setup at this
+ point! */
if(!dead_connection && imapc->pp.conn && imapc->pp.conn->bits.protoconnstart)
- if(!imap_perform_logout(conn))
+ if(!imap_perform_logout(conn))
(void)imap_block_statemach(conn, TRUE); /* ignore errors on LOGOUT */
-
- /* Disconnect from the server */
- Curl_pp_disconnect(&imapc->pp);
+
+ /* Disconnect from the server */
+ Curl_pp_disconnect(&imapc->pp);
Curl_dyn_free(&imapc->dyn);
-
- /* Cleanup the SASL module */
+
+ /* Cleanup the SASL module */
Curl_sasl_cleanup(conn, imapc->sasl.authused);
-
- /* Cleanup our connection based variables */
- Curl_safefree(imapc->mailbox);
- Curl_safefree(imapc->mailbox_uidvalidity);
-
- return CURLE_OK;
-}
-
-/* Call this when the DO phase has completed */
-static CURLcode imap_dophase_done(struct connectdata *conn, bool connected)
-{
+
+ /* Cleanup our connection based variables */
+ Curl_safefree(imapc->mailbox);
+ Curl_safefree(imapc->mailbox_uidvalidity);
+
+ return CURLE_OK;
+}
+
+/* Call this when the DO phase has completed */
+static CURLcode imap_dophase_done(struct connectdata *conn, bool connected)
+{
struct IMAP *imap = conn->data->req.p.imap;
-
- (void)connected;
-
- if(imap->transfer != FTPTRANSFER_BODY)
- /* no data to transfer */
+
+ (void)connected;
+
+ if(imap->transfer != FTPTRANSFER_BODY)
+ /* no data to transfer */
Curl_setup_transfer(conn->data, -1, -1, FALSE, -1);
-
- return CURLE_OK;
-}
-
-/* Called from multi.c while DOing */
-static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done)
-{
- CURLcode result = imap_multi_statemach(conn, dophase_done);
-
- if(result)
- DEBUGF(infof(conn->data, "DO phase failed\n"));
- else if(*dophase_done) {
- result = imap_dophase_done(conn, FALSE /* not connected */);
-
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * imap_regular_transfer()
- *
- * The input argument is already checked for validity.
- *
- * Performs all commands done before a regular transfer between a local and a
- * remote host.
- */
-static CURLcode imap_regular_transfer(struct connectdata *conn,
- bool *dophase_done)
-{
- CURLcode result = CURLE_OK;
- bool connected = FALSE;
+
+ return CURLE_OK;
+}
+
+/* Called from multi.c while DOing */
+static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done)
+{
+ CURLcode result = imap_multi_statemach(conn, dophase_done);
+
+ if(result)
+ DEBUGF(infof(conn->data, "DO phase failed\n"));
+ else if(*dophase_done) {
+ result = imap_dophase_done(conn, FALSE /* not connected */);
+
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_regular_transfer()
+ *
+ * The input argument is already checked for validity.
+ *
+ * Performs all commands done before a regular transfer between a local and a
+ * remote host.
+ */
+static CURLcode imap_regular_transfer(struct connectdata *conn,
+ bool *dophase_done)
+{
+ CURLcode result = CURLE_OK;
+ bool connected = FALSE;
struct Curl_easy *data = conn->data;
-
- /* Make sure size is unknown at this point */
- data->req.size = -1;
-
- /* Set the progress data */
- Curl_pgrsSetUploadCounter(data, 0);
- Curl_pgrsSetDownloadCounter(data, 0);
+
+ /* Make sure size is unknown at this point */
+ data->req.size = -1;
+
+ /* Set the progress data */
+ Curl_pgrsSetUploadCounter(data, 0);
+ Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, -1);
Curl_pgrsSetDownloadSize(data, -1);
-
- /* Carry out the perform */
- result = imap_perform(conn, &connected, dophase_done);
-
- /* Perform post DO phase operations if necessary */
- if(!result && *dophase_done)
- result = imap_dophase_done(conn, connected);
-
- return result;
-}
-
-static CURLcode imap_setup_connection(struct connectdata *conn)
-{
- /* Initialise the IMAP layer */
- CURLcode result = imap_init(conn);
- if(result)
- return result;
-
+
+ /* Carry out the perform */
+ result = imap_perform(conn, &connected, dophase_done);
+
+ /* Perform post DO phase operations if necessary */
+ if(!result && *dophase_done)
+ result = imap_dophase_done(conn, connected);
+
+ return result;
+}
+
+static CURLcode imap_setup_connection(struct connectdata *conn)
+{
+ /* Initialise the IMAP layer */
+ CURLcode result = imap_init(conn);
+ if(result)
+ return result;
+
/* Clear the TLS upgraded flag */
conn->bits.tls_upgraded = FALSE;
-
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * imap_sendf()
- *
+
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * imap_sendf()
+ *
* Sends the formatted string as an IMAP command to the server.
- *
- * Designed to never block.
- */
-static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
-{
- CURLcode result = CURLE_OK;
- struct imap_conn *imapc = &conn->proto.imapc;
-
- DEBUGASSERT(fmt);
-
- /* Calculate the tag based on the connection ID and command ID */
+ *
+ * Designed to never block.
+ */
+static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
+{
+ CURLcode result = CURLE_OK;
+ struct imap_conn *imapc = &conn->proto.imapc;
+
+ DEBUGASSERT(fmt);
+
+ /* Calculate the tag based on the connection ID and command ID */
msnprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d",
'A' + curlx_sltosi(conn->connection_id % 26),
(++imapc->cmdid)%1000);
-
+
/* start with a blank buffer */
Curl_dyn_reset(&imapc->dyn);
-
+
/* append tag + space + fmt */
result = Curl_dyn_addf(&imapc->dyn, "%s %s", imapc->resptag, fmt);
if(!result) {
@@ -1754,45 +1754,45 @@ static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
result = Curl_pp_vsendf(&imapc->pp, Curl_dyn_ptr(&imapc->dyn), ap);
va_end(ap);
}
- return result;
-}
-
-/***********************************************************************
- *
- * imap_atom()
- *
- * Checks the input string for characters that need escaping and returns an
- * atom ready for sending to the server.
- *
- * The returned string needs to be freed.
- *
- */
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_atom()
+ *
+ * Checks the input string for characters that need escaping and returns an
+ * atom ready for sending to the server.
+ *
+ * The returned string needs to be freed.
+ *
+ */
static char *imap_atom(const char *str, bool escape_only)
-{
+{
/* !checksrc! disable PARENBRACE 1 */
const char atom_specials[] = "(){ %*]";
- const char *p1;
- char *p2;
- size_t backsp_count = 0;
- size_t quote_count = 0;
+ const char *p1;
+ char *p2;
+ size_t backsp_count = 0;
+ size_t quote_count = 0;
bool others_exists = FALSE;
- size_t newlen = 0;
- char *newstr = NULL;
-
- if(!str)
- return NULL;
-
+ size_t newlen = 0;
+ char *newstr = NULL;
+
+ if(!str)
+ return NULL;
+
/* Look for "atom-specials", counting the backslash and quote characters as
these will need escaping */
- p1 = str;
- while(*p1) {
- if(*p1 == '\\')
- backsp_count++;
- else if(*p1 == '"')
- quote_count++;
+ p1 = str;
+ while(*p1) {
+ if(*p1 == '\\')
+ backsp_count++;
+ else if(*p1 == '"')
+ quote_count++;
else if(!escape_only) {
const char *p3 = atom_specials;
-
+
while(*p3 && !others_exists) {
if(*p1 == *p3)
others_exists = TRUE;
@@ -1801,123 +1801,123 @@ static char *imap_atom(const char *str, bool escape_only)
}
}
- p1++;
- }
-
+ p1++;
+ }
+
/* Does the input contain any "atom-special" characters? */
if(!backsp_count && !quote_count && !others_exists)
- return strdup(str);
-
- /* Calculate the new string length */
+ return strdup(str);
+
+ /* Calculate the new string length */
newlen = strlen(str) + backsp_count + quote_count + (escape_only ? 0 : 2);
-
- /* Allocate the new string */
- newstr = (char *) malloc((newlen + 1) * sizeof(char));
- if(!newstr)
- return NULL;
-
- /* Surround the string in quotes if necessary */
- p2 = newstr;
+
+ /* Allocate the new string */
+ newstr = (char *) malloc((newlen + 1) * sizeof(char));
+ if(!newstr)
+ return NULL;
+
+ /* Surround the string in quotes if necessary */
+ p2 = newstr;
if(!escape_only) {
- newstr[0] = '"';
- newstr[newlen - 1] = '"';
- p2++;
- }
-
- /* Copy the string, escaping backslash and quote characters along the way */
- p1 = str;
- while(*p1) {
- if(*p1 == '\\' || *p1 == '"') {
- *p2 = '\\';
- p2++;
- }
-
- *p2 = *p1;
-
- p1++;
- p2++;
- }
-
- /* Terminate the string */
- newstr[newlen] = '\0';
-
- return newstr;
-}
-
-/***********************************************************************
- *
- * imap_is_bchar()
- *
- * Portable test of whether the specified char is a "bchar" as defined in the
- * grammar of RFC-5092.
- */
-static bool imap_is_bchar(char ch)
-{
- switch(ch) {
- /* bchar */
- case ':': case '@': case '/':
- /* bchar -> achar */
- case '&': case '=':
- /* bchar -> achar -> uchar -> unreserved */
- case '0': case '1': case '2': case '3': case '4': case '5': case '6':
- case '7': case '8': case '9':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
- case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
- case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
- case 'V': case 'W': case 'X': case 'Y': case 'Z':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
- case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
- case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
- case 'v': case 'w': case 'x': case 'y': case 'z':
- case '-': case '.': case '_': case '~':
- /* bchar -> achar -> uchar -> sub-delims-sh */
- case '!': case '$': case '\'': case '(': case ')': case '*':
- case '+': case ',':
- /* bchar -> achar -> uchar -> pct-encoded */
- case '%': /* HEXDIG chars are already included above */
- return true;
-
- default:
- return false;
- }
-}
-
-/***********************************************************************
- *
- * imap_parse_url_options()
- *
- * Parse the URL login options.
- */
-static CURLcode imap_parse_url_options(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct imap_conn *imapc = &conn->proto.imapc;
+ newstr[0] = '"';
+ newstr[newlen - 1] = '"';
+ p2++;
+ }
+
+ /* Copy the string, escaping backslash and quote characters along the way */
+ p1 = str;
+ while(*p1) {
+ if(*p1 == '\\' || *p1 == '"') {
+ *p2 = '\\';
+ p2++;
+ }
+
+ *p2 = *p1;
+
+ p1++;
+ p2++;
+ }
+
+ /* Terminate the string */
+ newstr[newlen] = '\0';
+
+ return newstr;
+}
+
+/***********************************************************************
+ *
+ * imap_is_bchar()
+ *
+ * Portable test of whether the specified char is a "bchar" as defined in the
+ * grammar of RFC-5092.
+ */
+static bool imap_is_bchar(char ch)
+{
+ switch(ch) {
+ /* bchar */
+ case ':': case '@': case '/':
+ /* bchar -> achar */
+ case '&': case '=':
+ /* bchar -> achar -> uchar -> unreserved */
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6':
+ case '7': case '8': case '9':
+ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
+ case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
+ case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
+ case 'V': case 'W': case 'X': case 'Y': case 'Z':
+ case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
+ case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
+ case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
+ case 'v': case 'w': case 'x': case 'y': case 'z':
+ case '-': case '.': case '_': case '~':
+ /* bchar -> achar -> uchar -> sub-delims-sh */
+ case '!': case '$': case '\'': case '(': case ')': case '*':
+ case '+': case ',':
+ /* bchar -> achar -> uchar -> pct-encoded */
+ case '%': /* HEXDIG chars are already included above */
+ return true;
+
+ default:
+ return false;
+ }
+}
+
+/***********************************************************************
+ *
+ * imap_parse_url_options()
+ *
+ * Parse the URL login options.
+ */
+static CURLcode imap_parse_url_options(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct imap_conn *imapc = &conn->proto.imapc;
const char *ptr = conn->options;
-
+
imapc->sasl.resetprefs = TRUE;
while(!result && ptr && *ptr) {
- const char *key = ptr;
+ const char *key = ptr;
const char *value;
-
- while(*ptr && *ptr != '=')
- ptr++;
-
+
+ while(*ptr && *ptr != '=')
+ ptr++;
+
value = ptr + 1;
-
+
while(*ptr && *ptr != ';')
ptr++;
if(strncasecompare(key, "AUTH=", 5))
result = Curl_sasl_parse_url_auth_option(&imapc->sasl,
value, ptr - value);
- else
- result = CURLE_URL_MALFORMAT;
+ else
+ result = CURLE_URL_MALFORMAT;
if(*ptr == ';')
ptr++;
- }
-
+ }
+
switch(imapc->sasl.prefmech) {
case SASL_AUTH_NONE:
imapc->preftype = IMAP_TYPE_NONE;
@@ -1930,100 +1930,100 @@ static CURLcode imap_parse_url_options(struct connectdata *conn)
break;
}
- return result;
-}
-
-/***********************************************************************
- *
- * imap_parse_url_path()
- *
- * Parse the URL path into separate path components.
- *
- */
-static CURLcode imap_parse_url_path(struct connectdata *conn)
-{
- /* The imap struct is already initialised in imap_connect() */
- CURLcode result = CURLE_OK;
+ return result;
+}
+
+/***********************************************************************
+ *
+ * imap_parse_url_path()
+ *
+ * Parse the URL path into separate path components.
+ *
+ */
+static CURLcode imap_parse_url_path(struct connectdata *conn)
+{
+ /* The imap struct is already initialised in imap_connect() */
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
const char *begin = &data->state.up.path[1]; /* skip leading slash */
- const char *ptr = begin;
-
- /* See how much of the URL is a valid path and decode it */
- while(imap_is_bchar(*ptr))
- ptr++;
-
- if(ptr != begin) {
- /* Remove the trailing slash if present */
- const char *end = ptr;
- if(end > begin && end[-1] == '/')
- end--;
-
- result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL,
+ const char *ptr = begin;
+
+ /* See how much of the URL is a valid path and decode it */
+ while(imap_is_bchar(*ptr))
+ ptr++;
+
+ if(ptr != begin) {
+ /* Remove the trailing slash if present */
+ const char *end = ptr;
+ if(end > begin && end[-1] == '/')
+ end--;
+
+ result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL,
REJECT_CTRL);
- if(result)
- return result;
- }
- else
- imap->mailbox = NULL;
-
- /* There can be any number of parameters in the form ";NAME=VALUE" */
- while(*ptr == ';') {
- char *name;
- char *value;
- size_t valuelen;
-
- /* Find the length of the name parameter */
- begin = ++ptr;
- while(*ptr && *ptr != '=')
- ptr++;
-
- if(!*ptr)
- return CURLE_URL_MALFORMAT;
-
- /* Decode the name parameter */
+ if(result)
+ return result;
+ }
+ else
+ imap->mailbox = NULL;
+
+ /* There can be any number of parameters in the form ";NAME=VALUE" */
+ while(*ptr == ';') {
+ char *name;
+ char *value;
+ size_t valuelen;
+
+ /* Find the length of the name parameter */
+ begin = ++ptr;
+ while(*ptr && *ptr != '=')
+ ptr++;
+
+ if(!*ptr)
+ return CURLE_URL_MALFORMAT;
+
+ /* Decode the name parameter */
result = Curl_urldecode(data, begin, ptr - begin, &name, NULL,
REJECT_CTRL);
- if(result)
- return result;
-
- /* Find the length of the value parameter */
- begin = ++ptr;
- while(imap_is_bchar(*ptr))
- ptr++;
-
- /* Decode the value parameter */
+ if(result)
+ return result;
+
+ /* Find the length of the value parameter */
+ begin = ++ptr;
+ while(imap_is_bchar(*ptr))
+ ptr++;
+
+ /* Decode the value parameter */
result = Curl_urldecode(data, begin, ptr - begin, &value, &valuelen,
REJECT_CTRL);
- if(result) {
+ if(result) {
free(name);
- return result;
- }
-
- DEBUGF(infof(conn->data, "IMAP URL parameter '%s' = '%s'\n", name, value));
-
+ return result;
+ }
+
+ DEBUGF(infof(conn->data, "IMAP URL parameter '%s' = '%s'\n", name, value));
+
/* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and
PARTIAL) stripping of the trailing slash character if it is present.
-
- Note: Unknown parameters trigger a URL_MALFORMAT error. */
+
+ Note: Unknown parameters trigger a URL_MALFORMAT error. */
if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) {
- if(valuelen > 0 && value[valuelen - 1] == '/')
- value[valuelen - 1] = '\0';
-
- imap->uidvalidity = value;
- value = NULL;
- }
+ if(valuelen > 0 && value[valuelen - 1] == '/')
+ value[valuelen - 1] = '\0';
+
+ imap->uidvalidity = value;
+ value = NULL;
+ }
else if(strcasecompare(name, "UID") && !imap->uid) {
- if(valuelen > 0 && value[valuelen - 1] == '/')
- value[valuelen - 1] = '\0';
-
- imap->uid = value;
- value = NULL;
- }
+ if(valuelen > 0 && value[valuelen - 1] == '/')
+ value[valuelen - 1] = '\0';
+
+ imap->uid = value;
+ value = NULL;
+ }
else if(strcasecompare(name, "MAILINDEX") && !imap->mindex) {
- if(valuelen > 0 && value[valuelen - 1] == '/')
- value[valuelen - 1] = '\0';
-
+ if(valuelen > 0 && value[valuelen - 1] == '/')
+ value[valuelen - 1] = '\0';
+
imap->mindex = value;
value = NULL;
}
@@ -2031,9 +2031,9 @@ static CURLcode imap_parse_url_path(struct connectdata *conn)
if(valuelen > 0 && value[valuelen - 1] == '/')
value[valuelen - 1] = '\0';
- imap->section = value;
- value = NULL;
- }
+ imap->section = value;
+ value = NULL;
+ }
else if(strcasecompare(name, "PARTIAL") && !imap->partial) {
if(valuelen > 0 && value[valuelen - 1] == '/')
value[valuelen - 1] = '\0';
@@ -2041,17 +2041,17 @@ static CURLcode imap_parse_url_path(struct connectdata *conn)
imap->partial = value;
value = NULL;
}
- else {
+ else {
free(name);
free(value);
-
- return CURLE_URL_MALFORMAT;
- }
-
+
+ return CURLE_URL_MALFORMAT;
+ }
+
free(name);
free(value);
- }
-
+ }
+
/* Does the URL contain a query parameter? Only valid when we have a mailbox
and no UID as per RFC-5092 */
if(imap->mailbox && !imap->uid && !imap->mindex) {
@@ -2060,48 +2060,48 @@ static CURLcode imap_parse_url_path(struct connectdata *conn)
CURLU_URLDECODE);
}
- /* Any extra stuff at the end of the URL is an error */
- if(*ptr)
- return CURLE_URL_MALFORMAT;
-
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * imap_parse_custom_request()
- *
- * Parse the custom request.
- */
-static CURLcode imap_parse_custom_request(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ /* Any extra stuff at the end of the URL is an error */
+ if(*ptr)
+ return CURLE_URL_MALFORMAT;
+
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * imap_parse_custom_request()
+ *
+ * Parse the custom request.
+ */
+static CURLcode imap_parse_custom_request(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.p.imap;
- const char *custom = data->set.str[STRING_CUSTOMREQUEST];
-
- if(custom) {
- /* URL decode the custom request */
+ const char *custom = data->set.str[STRING_CUSTOMREQUEST];
+
+ if(custom) {
+ /* URL decode the custom request */
result = Curl_urldecode(data, custom, 0, &imap->custom, NULL, REJECT_CTRL);
-
- /* Extract the parameters if specified */
- if(!result) {
- const char *params = imap->custom;
-
- while(*params && *params != ' ')
- params++;
-
- if(*params) {
- imap->custom_params = strdup(params);
- imap->custom[params - imap->custom] = '\0';
-
- if(!imap->custom_params)
- result = CURLE_OUT_OF_MEMORY;
- }
- }
- }
-
- return result;
-}
-
-#endif /* CURL_DISABLE_IMAP */
+
+ /* Extract the parameters if specified */
+ if(!result) {
+ const char *params = imap->custom;
+
+ while(*params && *params != ' ')
+ params++;
+
+ if(*params) {
+ imap->custom_params = strdup(params);
+ imap->custom[params - imap->custom] = '\0';
+
+ if(!imap->custom_params)
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ }
+ }
+
+ return result;
+}
+
+#endif /* CURL_DISABLE_IMAP */
diff --git a/contrib/libs/curl/lib/imap.h b/contrib/libs/curl/lib/imap.h
index 159edbf660..ef6515d8c2 100644
--- a/contrib/libs/curl/lib/imap.h
+++ b/contrib/libs/curl/lib/imap.h
@@ -1,93 +1,93 @@
-#ifndef HEADER_CURL_IMAP_H
-#define HEADER_CURL_IMAP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_IMAP_H
+#define HEADER_CURL_IMAP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2009 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "pingpong.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "pingpong.h"
#include "curl_sasl.h"
-
-/****************************************************************************
- * IMAP unique setup
- ***************************************************************************/
-typedef enum {
- IMAP_STOP, /* do nothing state, stops the state machine */
- IMAP_SERVERGREET, /* waiting for the initial greeting immediately after
- a connect */
- IMAP_CAPABILITY,
- IMAP_STARTTLS,
- IMAP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
- (multi mode only) */
+
+/****************************************************************************
+ * IMAP unique setup
+ ***************************************************************************/
+typedef enum {
+ IMAP_STOP, /* do nothing state, stops the state machine */
+ IMAP_SERVERGREET, /* waiting for the initial greeting immediately after
+ a connect */
+ IMAP_CAPABILITY,
+ IMAP_STARTTLS,
+ IMAP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
+ (multi mode only) */
IMAP_AUTHENTICATE,
- IMAP_LOGIN,
- IMAP_LIST,
- IMAP_SELECT,
- IMAP_FETCH,
- IMAP_FETCH_FINAL,
- IMAP_APPEND,
- IMAP_APPEND_FINAL,
+ IMAP_LOGIN,
+ IMAP_LIST,
+ IMAP_SELECT,
+ IMAP_FETCH,
+ IMAP_FETCH_FINAL,
+ IMAP_APPEND,
+ IMAP_APPEND_FINAL,
IMAP_SEARCH,
- IMAP_LOGOUT,
- IMAP_LAST /* never used */
-} imapstate;
-
+ IMAP_LOGOUT,
+ IMAP_LAST /* never used */
+} imapstate;
+
/* This IMAP struct is used in the Curl_easy. All IMAP data that is
- connection-oriented must be in imap_conn to properly deal with the fact that
+ connection-oriented must be in imap_conn to properly deal with the fact that
perhaps the Curl_easy is changed between the times the connection is
- used. */
-struct IMAP {
- curl_pp_transfer transfer;
- char *mailbox; /* Mailbox to select */
- char *uidvalidity; /* UIDVALIDITY to check in select */
- char *uid; /* Message UID to fetch */
+ used. */
+struct IMAP {
+ curl_pp_transfer transfer;
+ char *mailbox; /* Mailbox to select */
+ char *uidvalidity; /* UIDVALIDITY to check in select */
+ char *uid; /* Message UID to fetch */
char *mindex; /* Index in mail box of mail to fetch */
- char *section; /* Message SECTION to fetch */
+ char *section; /* Message SECTION to fetch */
char *partial; /* Message PARTIAL to fetch */
char *query; /* Query to search for */
- char *custom; /* Custom request */
- char *custom_params; /* Parameters for the custom request */
-};
-
-/* imap_conn is used for struct connection-oriented data in the connectdata
- struct */
-struct imap_conn {
- struct pingpong pp;
- imapstate state; /* Always use imap.c:state() to change state! */
- bool ssldone; /* Is connect() over SSL done? */
+ char *custom; /* Custom request */
+ char *custom_params; /* Parameters for the custom request */
+};
+
+/* imap_conn is used for struct connection-oriented data in the connectdata
+ struct */
+struct imap_conn {
+ struct pingpong pp;
+ imapstate state; /* Always use imap.c:state() to change state! */
+ bool ssldone; /* Is connect() over SSL done? */
bool preauth; /* Is this connection PREAUTH? */
struct SASL sasl; /* SASL-related parameters */
unsigned int preftype; /* Preferred authentication type */
unsigned int cmdid; /* Last used command ID */
- char resptag[5]; /* Response tag to wait for */
- bool tls_supported; /* StartTLS capability supported by server */
- bool login_disabled; /* LOGIN command disabled by server */
- bool ir_supported; /* Initial response supported by server */
- char *mailbox; /* The last selected mailbox */
- char *mailbox_uidvalidity; /* UIDVALIDITY parsed from select response */
+ char resptag[5]; /* Response tag to wait for */
+ bool tls_supported; /* StartTLS capability supported by server */
+ bool login_disabled; /* LOGIN command disabled by server */
+ bool ir_supported; /* Initial response supported by server */
+ char *mailbox; /* The last selected mailbox */
+ char *mailbox_uidvalidity; /* UIDVALIDITY parsed from select response */
struct dynbuf dyn; /* for the IMAP commands */
-};
-
-extern const struct Curl_handler Curl_handler_imap;
-extern const struct Curl_handler Curl_handler_imaps;
-
+};
+
+extern const struct Curl_handler Curl_handler_imap;
+extern const struct Curl_handler Curl_handler_imaps;
+
/* Authentication type flags */
#define IMAP_TYPE_CLEARTEXT (1 << 0)
#define IMAP_TYPE_SASL (1 << 1)
@@ -96,4 +96,4 @@ extern const struct Curl_handler Curl_handler_imaps;
#define IMAP_TYPE_NONE 0
#define IMAP_TYPE_ANY ~0U
-#endif /* HEADER_CURL_IMAP_H */
+#endif /* HEADER_CURL_IMAP_H */
diff --git a/contrib/libs/curl/lib/inet_ntop.c b/contrib/libs/curl/lib/inet_ntop.c
index bddbf0db27..9a5af7f421 100644
--- a/contrib/libs/curl/lib/inet_ntop.c
+++ b/contrib/libs/curl/lib/inet_ntop.c
@@ -1,197 +1,197 @@
-/*
+/*
* Copyright (C) 1996-2019 Internet Software Consortium.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM
- * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
- * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
- * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
- * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
- * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
- * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-/*
- * Original code by Paul Vixie. "curlified" by Gisle Vanem.
- */
-
-#include "curl_setup.h"
-
-#ifndef HAVE_INET_NTOP
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#include "inet_ntop.h"
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM
+ * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
+ * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+/*
+ * Original code by Paul Vixie. "curlified" by Gisle Vanem.
+ */
+
+#include "curl_setup.h"
+
+#ifndef HAVE_INET_NTOP
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#include "inet_ntop.h"
#include "curl_printf.h"
-
-#define IN6ADDRSZ 16
-#define INADDRSZ 4
-#define INT16SZ 2
-
-/*
- * Format an IPv4 address, more or less like inet_ntoa().
- *
- * Returns `dst' (as a const)
- * Note:
- * - uses no statics
- * - takes a unsigned char* not an in_addr as input
- */
-static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size)
-{
+
+#define IN6ADDRSZ 16
+#define INADDRSZ 4
+#define INT16SZ 2
+
+/*
+ * Format an IPv4 address, more or less like inet_ntoa().
+ *
+ * Returns `dst' (as a const)
+ * Note:
+ * - uses no statics
+ * - takes a unsigned char* not an in_addr as input
+ */
+static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size)
+{
char tmp[sizeof("255.255.255.255")];
- size_t len;
-
- DEBUGASSERT(size >= 16);
-
- tmp[0] = '\0';
+ size_t len;
+
+ DEBUGASSERT(size >= 16);
+
+ tmp[0] = '\0';
(void)msnprintf(tmp, sizeof(tmp), "%d.%d.%d.%d",
((int)((unsigned char)src[0])) & 0xff,
((int)((unsigned char)src[1])) & 0xff,
((int)((unsigned char)src[2])) & 0xff,
((int)((unsigned char)src[3])) & 0xff);
-
- len = strlen(tmp);
- if(len == 0 || len >= size) {
+
+ len = strlen(tmp);
+ if(len == 0 || len >= size) {
errno = ENOSPC;
- return (NULL);
- }
- strcpy(dst, tmp);
- return dst;
-}
-
-#ifdef ENABLE_IPV6
-/*
- * Convert IPv6 binary address into presentation (printable) format.
- */
-static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size)
-{
- /*
- * Note that int32_t and int16_t need only be "at least" large enough
- * to contain a value of the specified size. On some systems, like
- * Crays, there is no such thing as an integer variable with 16 bits.
- * Keep this in mind if you think this function should have been coded
- * to use pointer overlays. All the world's not a VAX.
- */
- char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
- char *tp;
- struct {
- long base;
- long len;
- } best, cur;
- unsigned long words[IN6ADDRSZ / INT16SZ];
- int i;
-
- /* Preprocess:
- * Copy the input (bytewise) array into a wordwise array.
- * Find the longest run of 0x00's in src[] for :: shorthanding.
- */
- memset(words, '\0', sizeof(words));
- for(i = 0; i < IN6ADDRSZ; i++)
- words[i/2] |= (src[i] << ((1 - (i % 2)) << 3));
-
- best.base = -1;
- cur.base = -1;
- best.len = 0;
- cur.len = 0;
-
- for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) {
- if(words[i] == 0) {
- if(cur.base == -1)
- cur.base = i, cur.len = 1;
- else
- cur.len++;
- }
- else if(cur.base != -1) {
- if(best.base == -1 || cur.len > best.len)
- best = cur;
- cur.base = -1;
- }
- }
- if((cur.base != -1) && (best.base == -1 || cur.len > best.len))
- best = cur;
- if(best.base != -1 && best.len < 2)
- best.base = -1;
- /* Format the result. */
- tp = tmp;
- for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) {
- /* Are we inside the best run of 0x00's? */
- if(best.base != -1 && i >= best.base && i < (best.base + best.len)) {
- if(i == best.base)
- *tp++ = ':';
- continue;
- }
-
- /* Are we following an initial run of 0x00s or any real hex?
- */
- if(i != 0)
- *tp++ = ':';
-
- /* Is this address an encapsulated IPv4?
- */
- if(i == 6 && best.base == 0 &&
- (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
+ return (NULL);
+ }
+ strcpy(dst, tmp);
+ return dst;
+}
+
+#ifdef ENABLE_IPV6
+/*
+ * Convert IPv6 binary address into presentation (printable) format.
+ */
+static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size)
+{
+ /*
+ * Note that int32_t and int16_t need only be "at least" large enough
+ * to contain a value of the specified size. On some systems, like
+ * Crays, there is no such thing as an integer variable with 16 bits.
+ * Keep this in mind if you think this function should have been coded
+ * to use pointer overlays. All the world's not a VAX.
+ */
+ char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
+ char *tp;
+ struct {
+ long base;
+ long len;
+ } best, cur;
+ unsigned long words[IN6ADDRSZ / INT16SZ];
+ int i;
+
+ /* Preprocess:
+ * Copy the input (bytewise) array into a wordwise array.
+ * Find the longest run of 0x00's in src[] for :: shorthanding.
+ */
+ memset(words, '\0', sizeof(words));
+ for(i = 0; i < IN6ADDRSZ; i++)
+ words[i/2] |= (src[i] << ((1 - (i % 2)) << 3));
+
+ best.base = -1;
+ cur.base = -1;
+ best.len = 0;
+ cur.len = 0;
+
+ for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) {
+ if(words[i] == 0) {
+ if(cur.base == -1)
+ cur.base = i, cur.len = 1;
+ else
+ cur.len++;
+ }
+ else if(cur.base != -1) {
+ if(best.base == -1 || cur.len > best.len)
+ best = cur;
+ cur.base = -1;
+ }
+ }
+ if((cur.base != -1) && (best.base == -1 || cur.len > best.len))
+ best = cur;
+ if(best.base != -1 && best.len < 2)
+ best.base = -1;
+ /* Format the result. */
+ tp = tmp;
+ for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) {
+ /* Are we inside the best run of 0x00's? */
+ if(best.base != -1 && i >= best.base && i < (best.base + best.len)) {
+ if(i == best.base)
+ *tp++ = ':';
+ continue;
+ }
+
+ /* Are we following an initial run of 0x00s or any real hex?
+ */
+ if(i != 0)
+ *tp++ = ':';
+
+ /* Is this address an encapsulated IPv4?
+ */
+ if(i == 6 && best.base == 0 &&
+ (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
if(!inet_ntop4(src + 12, tp, sizeof(tmp) - (tp - tmp))) {
errno = ENOSPC;
- return (NULL);
- }
- tp += strlen(tp);
- break;
- }
+ return (NULL);
+ }
+ tp += strlen(tp);
+ break;
+ }
tp += msnprintf(tp, 5, "%lx", words[i]);
- }
-
- /* Was it a trailing run of 0x00's?
- */
- if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ))
- *tp++ = ':';
- *tp++ = '\0';
-
- /* Check for overflow, copy, and we're done.
- */
- if((size_t)(tp - tmp) > size) {
+ }
+
+ /* Was it a trailing run of 0x00's?
+ */
+ if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ))
+ *tp++ = ':';
+ *tp++ = '\0';
+
+ /* Check for overflow, copy, and we're done.
+ */
+ if((size_t)(tp - tmp) > size) {
errno = ENOSPC;
- return (NULL);
- }
- strcpy(dst, tmp);
- return dst;
-}
-#endif /* ENABLE_IPV6 */
-
-/*
- * Convert a network format address to presentation format.
- *
- * Returns pointer to presentation format address (`buf').
- * Returns NULL on error and errno set with the specific
- * error, EAFNOSUPPORT or ENOSPC.
- *
- * On Windows we store the error in the thread errno, not
- * in the winsock error code. This is to avoid losing the
+ return (NULL);
+ }
+ strcpy(dst, tmp);
+ return dst;
+}
+#endif /* ENABLE_IPV6 */
+
+/*
+ * Convert a network format address to presentation format.
+ *
+ * Returns pointer to presentation format address (`buf').
+ * Returns NULL on error and errno set with the specific
+ * error, EAFNOSUPPORT or ENOSPC.
+ *
+ * On Windows we store the error in the thread errno, not
+ * in the winsock error code. This is to avoid losing the
* actual last winsock error. So when this function returns
* NULL, check errno not SOCKERRNO.
- */
-char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size)
-{
+ */
+char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size)
+{
switch(af) {
- case AF_INET:
+ case AF_INET:
return inet_ntop4((const unsigned char *)src, buf, size);
-#ifdef ENABLE_IPV6
- case AF_INET6:
+#ifdef ENABLE_IPV6
+ case AF_INET6:
return inet_ntop6((const unsigned char *)src, buf, size);
-#endif
- default:
+#endif
+ default:
errno = EAFNOSUPPORT;
- return NULL;
- }
-}
-#endif /* HAVE_INET_NTOP */
+ return NULL;
+ }
+}
+#endif /* HAVE_INET_NTOP */
diff --git a/contrib/libs/curl/lib/inet_ntop.h b/contrib/libs/curl/lib/inet_ntop.h
index 82083d4eab..067632aaee 100644
--- a/contrib/libs/curl/lib/inet_ntop.h
+++ b/contrib/libs/curl/lib/inet_ntop.h
@@ -1,37 +1,37 @@
-#ifndef HEADER_CURL_INET_NTOP_H
-#define HEADER_CURL_INET_NTOP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_INET_NTOP_H
+#define HEADER_CURL_INET_NTOP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-char *Curl_inet_ntop(int af, const void *addr, char *buf, size_t size);
-
-#ifdef HAVE_INET_NTOP
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#define Curl_inet_ntop(af,addr,buf,size) \
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+char *Curl_inet_ntop(int af, const void *addr, char *buf, size_t size);
+
+#ifdef HAVE_INET_NTOP
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#define Curl_inet_ntop(af,addr,buf,size) \
inet_ntop(af, addr, buf, (curl_socklen_t)size)
-#endif
-
-#endif /* HEADER_CURL_INET_NTOP_H */
+#endif
+
+#endif /* HEADER_CURL_INET_NTOP_H */
diff --git a/contrib/libs/curl/lib/inet_pton.c b/contrib/libs/curl/lib/inet_pton.c
index 3ee71c50e9..4923cae245 100644
--- a/contrib/libs/curl/lib/inet_pton.c
+++ b/contrib/libs/curl/lib/inet_pton.c
@@ -1,237 +1,237 @@
-/* This is from the BIND 4.9.4 release, modified to compile by itself */
-
+/* This is from the BIND 4.9.4 release, modified to compile by itself */
+
/* Copyright (c) 1996 - 2020 by Internet Software Consortium.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
- * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
- * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
- * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
- * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
- * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
- * SOFTWARE.
- */
-
-#include "curl_setup.h"
-
-#ifndef HAVE_INET_PTON
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#include "inet_pton.h"
-
-#define IN6ADDRSZ 16
-#define INADDRSZ 4
-#define INT16SZ 2
-
-/*
- * WARNING: Don't even consider trying to compile this on a system where
- * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
- */
-
-static int inet_pton4(const char *src, unsigned char *dst);
-#ifdef ENABLE_IPV6
-static int inet_pton6(const char *src, unsigned char *dst);
-#endif
-
-/* int
- * inet_pton(af, src, dst)
- * convert from presentation format (which usually means ASCII printable)
- * to network format (which is usually some kind of binary format).
- * return:
- * 1 if the address was valid for the specified address family
- * 0 if the address wasn't valid (`dst' is untouched in this case)
- * -1 if some other error occurred (`dst' is untouched in this case, too)
- * notice:
- * On Windows we store the error in the thread errno, not
- * in the winsock error code. This is to avoid losing the
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
+ * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
+ * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
+ * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
+ * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+ * SOFTWARE.
+ */
+
+#include "curl_setup.h"
+
+#ifndef HAVE_INET_PTON
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#include "inet_pton.h"
+
+#define IN6ADDRSZ 16
+#define INADDRSZ 4
+#define INT16SZ 2
+
+/*
+ * WARNING: Don't even consider trying to compile this on a system where
+ * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
+ */
+
+static int inet_pton4(const char *src, unsigned char *dst);
+#ifdef ENABLE_IPV6
+static int inet_pton6(const char *src, unsigned char *dst);
+#endif
+
+/* int
+ * inet_pton(af, src, dst)
+ * convert from presentation format (which usually means ASCII printable)
+ * to network format (which is usually some kind of binary format).
+ * return:
+ * 1 if the address was valid for the specified address family
+ * 0 if the address wasn't valid (`dst' is untouched in this case)
+ * -1 if some other error occurred (`dst' is untouched in this case, too)
+ * notice:
+ * On Windows we store the error in the thread errno, not
+ * in the winsock error code. This is to avoid losing the
* actual last winsock error. So when this function returns
* -1, check errno not SOCKERRNO.
- * author:
- * Paul Vixie, 1996.
- */
-int
-Curl_inet_pton(int af, const char *src, void *dst)
-{
+ * author:
+ * Paul Vixie, 1996.
+ */
+int
+Curl_inet_pton(int af, const char *src, void *dst)
+{
switch(af) {
- case AF_INET:
- return (inet_pton4(src, (unsigned char *)dst));
-#ifdef ENABLE_IPV6
- case AF_INET6:
- return (inet_pton6(src, (unsigned char *)dst));
-#endif
- default:
+ case AF_INET:
+ return (inet_pton4(src, (unsigned char *)dst));
+#ifdef ENABLE_IPV6
+ case AF_INET6:
+ return (inet_pton6(src, (unsigned char *)dst));
+#endif
+ default:
errno = EAFNOSUPPORT;
- return (-1);
- }
- /* NOTREACHED */
-}
-
-/* int
- * inet_pton4(src, dst)
- * like inet_aton() but without all the hexadecimal and shorthand.
- * return:
- * 1 if `src' is a valid dotted quad, else 0.
- * notice:
- * does not touch `dst' unless it's returning 1.
- * author:
- * Paul Vixie, 1996.
- */
-static int
-inet_pton4(const char *src, unsigned char *dst)
-{
- static const char digits[] = "0123456789";
- int saw_digit, octets, ch;
- unsigned char tmp[INADDRSZ], *tp;
-
- saw_digit = 0;
- octets = 0;
- tp = tmp;
- *tp = 0;
- while((ch = *src++) != '\0') {
- const char *pch;
-
+ return (-1);
+ }
+ /* NOTREACHED */
+}
+
+/* int
+ * inet_pton4(src, dst)
+ * like inet_aton() but without all the hexadecimal and shorthand.
+ * return:
+ * 1 if `src' is a valid dotted quad, else 0.
+ * notice:
+ * does not touch `dst' unless it's returning 1.
+ * author:
+ * Paul Vixie, 1996.
+ */
+static int
+inet_pton4(const char *src, unsigned char *dst)
+{
+ static const char digits[] = "0123456789";
+ int saw_digit, octets, ch;
+ unsigned char tmp[INADDRSZ], *tp;
+
+ saw_digit = 0;
+ octets = 0;
+ tp = tmp;
+ *tp = 0;
+ while((ch = *src++) != '\0') {
+ const char *pch;
+
pch = strchr(digits, ch);
if(pch) {
- unsigned int val = *tp * 10 + (unsigned int)(pch - digits);
-
- if(saw_digit && *tp == 0)
- return (0);
- if(val > 255)
- return (0);
- *tp = (unsigned char)val;
+ unsigned int val = *tp * 10 + (unsigned int)(pch - digits);
+
+ if(saw_digit && *tp == 0)
+ return (0);
+ if(val > 255)
+ return (0);
+ *tp = (unsigned char)val;
if(!saw_digit) {
- if(++octets > 4)
- return (0);
- saw_digit = 1;
- }
- }
- else if(ch == '.' && saw_digit) {
- if(octets == 4)
- return (0);
- *++tp = 0;
- saw_digit = 0;
- }
- else
- return (0);
- }
- if(octets < 4)
- return (0);
- memcpy(dst, tmp, INADDRSZ);
- return (1);
-}
-
-#ifdef ENABLE_IPV6
-/* int
- * inet_pton6(src, dst)
- * convert presentation level address to network order binary form.
- * return:
- * 1 if `src' is a valid [RFC1884 2.2] address, else 0.
- * notice:
- * (1) does not touch `dst' unless it's returning 1.
- * (2) :: in a full address is silently ignored.
- * credit:
- * inspired by Mark Andrews.
- * author:
- * Paul Vixie, 1996.
- */
-static int
-inet_pton6(const char *src, unsigned char *dst)
-{
- static const char xdigits_l[] = "0123456789abcdef",
- xdigits_u[] = "0123456789ABCDEF";
- unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp;
+ if(++octets > 4)
+ return (0);
+ saw_digit = 1;
+ }
+ }
+ else if(ch == '.' && saw_digit) {
+ if(octets == 4)
+ return (0);
+ *++tp = 0;
+ saw_digit = 0;
+ }
+ else
+ return (0);
+ }
+ if(octets < 4)
+ return (0);
+ memcpy(dst, tmp, INADDRSZ);
+ return (1);
+}
+
+#ifdef ENABLE_IPV6
+/* int
+ * inet_pton6(src, dst)
+ * convert presentation level address to network order binary form.
+ * return:
+ * 1 if `src' is a valid [RFC1884 2.2] address, else 0.
+ * notice:
+ * (1) does not touch `dst' unless it's returning 1.
+ * (2) :: in a full address is silently ignored.
+ * credit:
+ * inspired by Mark Andrews.
+ * author:
+ * Paul Vixie, 1996.
+ */
+static int
+inet_pton6(const char *src, unsigned char *dst)
+{
+ static const char xdigits_l[] = "0123456789abcdef",
+ xdigits_u[] = "0123456789ABCDEF";
+ unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp;
const char *curtok;
- int ch, saw_xdigit;
- size_t val;
-
- memset((tp = tmp), 0, IN6ADDRSZ);
- endp = tp + IN6ADDRSZ;
- colonp = NULL;
- /* Leading :: requires some special handling. */
- if(*src == ':')
- if(*++src != ':')
- return (0);
- curtok = src;
- saw_xdigit = 0;
- val = 0;
- while((ch = *src++) != '\0') {
+ int ch, saw_xdigit;
+ size_t val;
+
+ memset((tp = tmp), 0, IN6ADDRSZ);
+ endp = tp + IN6ADDRSZ;
+ colonp = NULL;
+ /* Leading :: requires some special handling. */
+ if(*src == ':')
+ if(*++src != ':')
+ return (0);
+ curtok = src;
+ saw_xdigit = 0;
+ val = 0;
+ while((ch = *src++) != '\0') {
const char *xdigits;
- const char *pch;
-
+ const char *pch;
+
pch = strchr((xdigits = xdigits_l), ch);
if(!pch)
- pch = strchr((xdigits = xdigits_u), ch);
- if(pch != NULL) {
- val <<= 4;
- val |= (pch - xdigits);
- if(++saw_xdigit > 4)
- return (0);
- continue;
- }
- if(ch == ':') {
- curtok = src;
- if(!saw_xdigit) {
- if(colonp)
- return (0);
- colonp = tp;
- continue;
- }
- if(tp + INT16SZ > endp)
- return (0);
+ pch = strchr((xdigits = xdigits_u), ch);
+ if(pch != NULL) {
+ val <<= 4;
+ val |= (pch - xdigits);
+ if(++saw_xdigit > 4)
+ return (0);
+ continue;
+ }
+ if(ch == ':') {
+ curtok = src;
+ if(!saw_xdigit) {
+ if(colonp)
+ return (0);
+ colonp = tp;
+ continue;
+ }
+ if(tp + INT16SZ > endp)
+ return (0);
*tp++ = (unsigned char) ((val >> 8) & 0xff);
*tp++ = (unsigned char) (val & 0xff);
- saw_xdigit = 0;
- val = 0;
- continue;
- }
- if(ch == '.' && ((tp + INADDRSZ) <= endp) &&
- inet_pton4(curtok, tp) > 0) {
- tp += INADDRSZ;
- saw_xdigit = 0;
- break; /* '\0' was seen by inet_pton4(). */
- }
- return (0);
- }
- if(saw_xdigit) {
- if(tp + INT16SZ > endp)
- return (0);
+ saw_xdigit = 0;
+ val = 0;
+ continue;
+ }
+ if(ch == '.' && ((tp + INADDRSZ) <= endp) &&
+ inet_pton4(curtok, tp) > 0) {
+ tp += INADDRSZ;
+ saw_xdigit = 0;
+ break; /* '\0' was seen by inet_pton4(). */
+ }
+ return (0);
+ }
+ if(saw_xdigit) {
+ if(tp + INT16SZ > endp)
+ return (0);
*tp++ = (unsigned char) ((val >> 8) & 0xff);
*tp++ = (unsigned char) (val & 0xff);
- }
- if(colonp != NULL) {
- /*
- * Since some memmove()'s erroneously fail to handle
- * overlapping regions, we'll do the shift by hand.
- */
- const ssize_t n = tp - colonp;
- ssize_t i;
-
- if(tp == endp)
- return (0);
- for(i = 1; i <= n; i++) {
- *(endp - i) = *(colonp + n - i);
- *(colonp + n - i) = 0;
- }
- tp = endp;
- }
- if(tp != endp)
- return (0);
- memcpy(dst, tmp, IN6ADDRSZ);
- return (1);
-}
-#endif /* ENABLE_IPV6 */
-
-#endif /* HAVE_INET_PTON */
+ }
+ if(colonp != NULL) {
+ /*
+ * Since some memmove()'s erroneously fail to handle
+ * overlapping regions, we'll do the shift by hand.
+ */
+ const ssize_t n = tp - colonp;
+ ssize_t i;
+
+ if(tp == endp)
+ return (0);
+ for(i = 1; i <= n; i++) {
+ *(endp - i) = *(colonp + n - i);
+ *(colonp + n - i) = 0;
+ }
+ tp = endp;
+ }
+ if(tp != endp)
+ return (0);
+ memcpy(dst, tmp, IN6ADDRSZ);
+ return (1);
+}
+#endif /* ENABLE_IPV6 */
+
+#endif /* HAVE_INET_PTON */
diff --git a/contrib/libs/curl/lib/inet_pton.h b/contrib/libs/curl/lib/inet_pton.h
index 7577eeb630..ec1237309f 100644
--- a/contrib/libs/curl/lib/inet_pton.h
+++ b/contrib/libs/curl/lib/inet_pton.h
@@ -1,39 +1,39 @@
-#ifndef HEADER_CURL_INET_PTON_H
-#define HEADER_CURL_INET_PTON_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_INET_PTON_H
+#define HEADER_CURL_INET_PTON_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-int Curl_inet_pton(int, const char *, void *);
-
-#ifdef HAVE_INET_PTON
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+int Curl_inet_pton(int, const char *, void *);
+
+#ifdef HAVE_INET_PTON
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
#elif defined(HAVE_WS2TCPIP_H)
/* inet_pton() exists in Vista or later */
#include <ws2tcpip.h>
-#endif
-#define Curl_inet_pton(x,y,z) inet_pton(x,y,z)
-#endif
-
-#endif /* HEADER_CURL_INET_PTON_H */
+#endif
+#define Curl_inet_pton(x,y,z) inet_pton(x,y,z)
+#endif
+
+#endif /* HEADER_CURL_INET_PTON_H */
diff --git a/contrib/libs/curl/lib/krb5.c b/contrib/libs/curl/lib/krb5.c
index 280f364189..66394f4f30 100644
--- a/contrib/libs/curl/lib/krb5.c
+++ b/contrib/libs/curl/lib/krb5.c
@@ -1,61 +1,61 @@
-/* GSSAPI/krb5 support for FTP - loosely based on old krb4.c
- *
+/* GSSAPI/krb5 support for FTP - loosely based on old krb4.c
+ *
* Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
- * (Royal Institute of Technology, Stockholm, Sweden).
+ * (Royal Institute of Technology, Stockholm, Sweden).
* Copyright (c) 2004 - 2020 Daniel Stenberg
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * 3. Neither the name of the Institute nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE. */
-
-#include "curl_setup.h"
-
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE. */
+
+#include "curl_setup.h"
+
#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP)
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-
-#include "urldata.h"
-#include "curl_base64.h"
-#include "ftp.h"
-#include "curl_gssapi.h"
-#include "sendf.h"
+
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+#include "urldata.h"
+#include "curl_base64.h"
+#include "ftp.h"
+#include "curl_gssapi.h"
+#include "sendf.h"
#include "curl_krb5.h"
-#include "warnless.h"
+#include "warnless.h"
#include "non-ascii.h"
#include "strcase.h"
#include "strdup.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "memdebug.h"
+
static CURLcode ftpsend(struct connectdata *conn, const char *cmd)
{
ssize_t bytes_written;
@@ -112,279 +112,279 @@ static CURLcode ftpsend(struct connectdata *conn, const char *cmd)
return result;
}
-static int
-krb5_init(void *app_data)
-{
- gss_ctx_id_t *context = app_data;
- /* Make sure our context is initialized for krb5_end. */
- *context = GSS_C_NO_CONTEXT;
- return 0;
-}
-
-static int
-krb5_check_prot(void *app_data, int level)
-{
- (void)app_data; /* unused */
- if(level == PROT_CONFIDENTIAL)
- return -1;
- return 0;
-}
-
-static int
-krb5_decode(void *app_data, void *buf, int len,
- int level UNUSED_PARAM,
- struct connectdata *conn UNUSED_PARAM)
-{
- gss_ctx_id_t *context = app_data;
- OM_uint32 maj, min;
- gss_buffer_desc enc, dec;
-
- (void)level;
- (void)conn;
-
- enc.value = buf;
- enc.length = len;
+static int
+krb5_init(void *app_data)
+{
+ gss_ctx_id_t *context = app_data;
+ /* Make sure our context is initialized for krb5_end. */
+ *context = GSS_C_NO_CONTEXT;
+ return 0;
+}
+
+static int
+krb5_check_prot(void *app_data, int level)
+{
+ (void)app_data; /* unused */
+ if(level == PROT_CONFIDENTIAL)
+ return -1;
+ return 0;
+}
+
+static int
+krb5_decode(void *app_data, void *buf, int len,
+ int level UNUSED_PARAM,
+ struct connectdata *conn UNUSED_PARAM)
+{
+ gss_ctx_id_t *context = app_data;
+ OM_uint32 maj, min;
+ gss_buffer_desc enc, dec;
+
+ (void)level;
+ (void)conn;
+
+ enc.value = buf;
+ enc.length = len;
maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL);
- if(maj != GSS_S_COMPLETE) {
- if(len >= 4)
- strcpy(buf, "599 ");
- return -1;
- }
-
- memcpy(buf, dec.value, dec.length);
- len = curlx_uztosi(dec.length);
- gss_release_buffer(&min, &dec);
-
- return len;
-}
-
-static int
-krb5_overhead(void *app_data, int level, int len)
-{
- /* no arguments are used */
- (void)app_data;
- (void)level;
- (void)len;
- return 0;
-}
-
-static int
+ if(maj != GSS_S_COMPLETE) {
+ if(len >= 4)
+ strcpy(buf, "599 ");
+ return -1;
+ }
+
+ memcpy(buf, dec.value, dec.length);
+ len = curlx_uztosi(dec.length);
+ gss_release_buffer(&min, &dec);
+
+ return len;
+}
+
+static int
+krb5_overhead(void *app_data, int level, int len)
+{
+ /* no arguments are used */
+ (void)app_data;
+ (void)level;
+ (void)len;
+ return 0;
+}
+
+static int
krb5_encode(void *app_data, const void *from, int length, int level, void **to)
-{
- gss_ctx_id_t *context = app_data;
- gss_buffer_desc dec, enc;
- OM_uint32 maj, min;
- int state;
- int len;
-
- /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal
+{
+ gss_ctx_id_t *context = app_data;
+ gss_buffer_desc dec, enc;
+ OM_uint32 maj, min;
+ int state;
+ int len;
+
+ /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal
* libraries modify the input buffer in gss_wrap()
- */
+ */
dec.value = (void *)from;
- dec.length = length;
+ dec.length = length;
maj = gss_wrap(&min, *context,
- level == PROT_PRIVATE,
- GSS_C_QOP_DEFAULT,
- &dec, &state, &enc);
-
- if(maj != GSS_S_COMPLETE)
- return -1;
-
- /* malloc a new buffer, in case gss_release_buffer doesn't work as
- expected */
- *to = malloc(enc.length);
- if(!*to)
- return -1;
- memcpy(*to, enc.value, enc.length);
- len = curlx_uztosi(enc.length);
- gss_release_buffer(&min, &enc);
- return len;
-}
-
-static int
-krb5_auth(void *app_data, struct connectdata *conn)
-{
- int ret = AUTH_OK;
- char *p;
- const char *host = conn->host.name;
- ssize_t nread;
- curl_socklen_t l = sizeof(conn->local_addr);
+ level == PROT_PRIVATE,
+ GSS_C_QOP_DEFAULT,
+ &dec, &state, &enc);
+
+ if(maj != GSS_S_COMPLETE)
+ return -1;
+
+ /* malloc a new buffer, in case gss_release_buffer doesn't work as
+ expected */
+ *to = malloc(enc.length);
+ if(!*to)
+ return -1;
+ memcpy(*to, enc.value, enc.length);
+ len = curlx_uztosi(enc.length);
+ gss_release_buffer(&min, &enc);
+ return len;
+}
+
+static int
+krb5_auth(void *app_data, struct connectdata *conn)
+{
+ int ret = AUTH_OK;
+ char *p;
+ const char *host = conn->host.name;
+ ssize_t nread;
+ curl_socklen_t l = sizeof(conn->local_addr);
struct Curl_easy *data = conn->data;
- CURLcode result;
+ CURLcode result;
const char *service = data->set.str[STRING_SERVICE_NAME] ?
data->set.str[STRING_SERVICE_NAME] :
"ftp";
const char *srv_host = "host";
- gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp;
- OM_uint32 maj, min;
- gss_name_t gssname;
- gss_ctx_id_t *context = app_data;
- struct gss_channel_bindings_struct chan;
- size_t base64_sz = 0;
+ gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp;
+ OM_uint32 maj, min;
+ gss_name_t gssname;
+ gss_ctx_id_t *context = app_data;
+ struct gss_channel_bindings_struct chan;
+ size_t base64_sz = 0;
struct sockaddr_in **remote_addr =
(struct sockaddr_in **)&conn->ip_addr->ai_addr;
char *stringp;
-
- if(getsockname(conn->sock[FIRSTSOCKET],
+
+ if(getsockname(conn->sock[FIRSTSOCKET],
(struct sockaddr *)&conn->local_addr, &l) < 0)
- perror("getsockname()");
-
- chan.initiator_addrtype = GSS_C_AF_INET;
- chan.initiator_address.length = l - 4;
+ perror("getsockname()");
+
+ chan.initiator_addrtype = GSS_C_AF_INET;
+ chan.initiator_address.length = l - 4;
chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr;
- chan.acceptor_addrtype = GSS_C_AF_INET;
- chan.acceptor_address.length = l - 4;
+ chan.acceptor_addrtype = GSS_C_AF_INET;
+ chan.acceptor_address.length = l - 4;
chan.acceptor_address.value = &(*remote_addr)->sin_addr.s_addr;
- chan.application_data.length = 0;
- chan.application_data.value = NULL;
-
- /* this loop will execute twice (once for service, once for host) */
- for(;;) {
- /* this really shouldn't be repeated here, but can't help it */
- if(service == srv_host) {
+ chan.application_data.length = 0;
+ chan.application_data.value = NULL;
+
+ /* this loop will execute twice (once for service, once for host) */
+ for(;;) {
+ /* this really shouldn't be repeated here, but can't help it */
+ if(service == srv_host) {
result = ftpsend(conn, "AUTH GSSAPI");
- if(result)
- return -2;
-
- if(Curl_GetFTPResponse(&nread, conn, NULL))
- return -1;
-
- if(data->state.buffer[0] != '3')
- return -1;
- }
-
+ if(result)
+ return -2;
+
+ if(Curl_GetFTPResponse(&nread, conn, NULL))
+ return -1;
+
+ if(data->state.buffer[0] != '3')
+ return -1;
+ }
+
stringp = aprintf("%s@%s", service, host);
if(!stringp)
return -2;
input_buffer.value = stringp;
input_buffer.length = strlen(stringp);
- maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE,
- &gssname);
+ maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE,
+ &gssname);
free(stringp);
- if(maj != GSS_S_COMPLETE) {
- gss_release_name(&min, &gssname);
- if(service == srv_host) {
+ if(maj != GSS_S_COMPLETE) {
+ gss_release_name(&min, &gssname);
+ if(service == srv_host) {
failf(data, "Error importing service name %s@%s", service, host);
- return AUTH_ERROR;
- }
- service = srv_host;
- continue;
- }
- /* We pass NULL as |output_name_type| to avoid a leak. */
- gss_display_name(&min, gssname, &output_buffer, NULL);
- Curl_infof(data, "Trying against %s\n", output_buffer.value);
- gssresp = GSS_C_NO_BUFFER;
- *context = GSS_C_NO_CONTEXT;
-
- do {
- /* Release the buffer at each iteration to avoid leaking: the first time
- we are releasing the memory from gss_display_name. The last item is
- taken care by a final gss_release_buffer. */
- gss_release_buffer(&min, &output_buffer);
- ret = AUTH_OK;
- maj = Curl_gss_init_sec_context(data,
- &min,
- context,
- gssname,
+ return AUTH_ERROR;
+ }
+ service = srv_host;
+ continue;
+ }
+ /* We pass NULL as |output_name_type| to avoid a leak. */
+ gss_display_name(&min, gssname, &output_buffer, NULL);
+ Curl_infof(data, "Trying against %s\n", output_buffer.value);
+ gssresp = GSS_C_NO_BUFFER;
+ *context = GSS_C_NO_CONTEXT;
+
+ do {
+ /* Release the buffer at each iteration to avoid leaking: the first time
+ we are releasing the memory from gss_display_name. The last item is
+ taken care by a final gss_release_buffer. */
+ gss_release_buffer(&min, &output_buffer);
+ ret = AUTH_OK;
+ maj = Curl_gss_init_sec_context(data,
+ &min,
+ context,
+ gssname,
&Curl_krb5_mech_oid,
- &chan,
- gssresp,
- &output_buffer,
+ &chan,
+ gssresp,
+ &output_buffer,
TRUE,
- NULL);
-
- if(gssresp) {
- free(_gssresp.value);
- gssresp = NULL;
- }
-
- if(GSS_ERROR(maj)) {
- Curl_infof(data, "Error creating security context\n");
- ret = AUTH_ERROR;
- break;
- }
-
- if(output_buffer.length != 0) {
+ NULL);
+
+ if(gssresp) {
+ free(_gssresp.value);
+ gssresp = NULL;
+ }
+
+ if(GSS_ERROR(maj)) {
+ Curl_infof(data, "Error creating security context\n");
+ ret = AUTH_ERROR;
+ break;
+ }
+
+ if(output_buffer.length != 0) {
char *cmd;
- result = Curl_base64_encode(data, (char *)output_buffer.value,
- output_buffer.length, &p, &base64_sz);
- if(result) {
+ result = Curl_base64_encode(data, (char *)output_buffer.value,
+ output_buffer.length, &p, &base64_sz);
+ if(result) {
Curl_infof(data, "base64-encoding: %s\n",
curl_easy_strerror(result));
ret = AUTH_ERROR;
- break;
- }
-
+ break;
+ }
+
cmd = aprintf("ADAT %s", p);
if(cmd)
result = ftpsend(conn, cmd);
else
result = CURLE_OUT_OF_MEMORY;
-
- free(p);
+
+ free(p);
free(cmd);
-
- if(result) {
- ret = -2;
- break;
- }
-
- if(Curl_GetFTPResponse(&nread, conn, NULL)) {
- ret = -1;
- break;
- }
-
- if(data->state.buffer[0] != '2' && data->state.buffer[0] != '3') {
- Curl_infof(data, "Server didn't accept auth data\n");
- ret = AUTH_ERROR;
- break;
- }
-
+
+ if(result) {
+ ret = -2;
+ break;
+ }
+
+ if(Curl_GetFTPResponse(&nread, conn, NULL)) {
+ ret = -1;
+ break;
+ }
+
+ if(data->state.buffer[0] != '2' && data->state.buffer[0] != '3') {
+ Curl_infof(data, "Server didn't accept auth data\n");
+ ret = AUTH_ERROR;
+ break;
+ }
+
_gssresp.value = NULL; /* make sure it is initialized */
- p = data->state.buffer + 4;
- p = strstr(p, "ADAT=");
- if(p) {
- result = Curl_base64_decode(p + 5,
- (unsigned char **)&_gssresp.value,
- &_gssresp.length);
- if(result) {
+ p = data->state.buffer + 4;
+ p = strstr(p, "ADAT=");
+ if(p) {
+ result = Curl_base64_decode(p + 5,
+ (unsigned char **)&_gssresp.value,
+ &_gssresp.length);
+ if(result) {
failf(data, "base64-decoding: %s", curl_easy_strerror(result));
- ret = AUTH_CONTINUE;
- break;
- }
- }
-
- gssresp = &_gssresp;
- }
- } while(maj == GSS_S_CONTINUE_NEEDED);
-
- gss_release_name(&min, &gssname);
- gss_release_buffer(&min, &output_buffer);
-
- if(gssresp)
- free(_gssresp.value);
-
- if(ret == AUTH_OK || service == srv_host)
- return ret;
-
- service = srv_host;
- }
- return ret;
-}
-
-static void krb5_end(void *app_data)
-{
- OM_uint32 min;
- gss_ctx_id_t *context = app_data;
- if(*context != GSS_C_NO_CONTEXT) {
+ ret = AUTH_CONTINUE;
+ break;
+ }
+ }
+
+ gssresp = &_gssresp;
+ }
+ } while(maj == GSS_S_CONTINUE_NEEDED);
+
+ gss_release_name(&min, &gssname);
+ gss_release_buffer(&min, &output_buffer);
+
+ if(gssresp)
+ free(_gssresp.value);
+
+ if(ret == AUTH_OK || service == srv_host)
+ return ret;
+
+ service = srv_host;
+ }
+ return ret;
+}
+
+static void krb5_end(void *app_data)
+{
+ OM_uint32 min;
+ gss_ctx_id_t *context = app_data;
+ if(*context != GSS_C_NO_CONTEXT) {
OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER);
(void)maj;
- DEBUGASSERT(maj == GSS_S_COMPLETE);
- }
-}
-
+ DEBUGASSERT(maj == GSS_S_COMPLETE);
+ }
+}
+
static struct Curl_sec_client_mech Curl_krb5_client_mech = {
"GSSAPI",
sizeof(gss_ctx_id_t),
@@ -395,8 +395,8 @@ static struct Curl_sec_client_mech Curl_krb5_client_mech = {
krb5_overhead,
krb5_encode,
krb5_decode
-};
-
+};
+
static const struct {
enum protection_level level;
const char *name;
diff --git a/contrib/libs/curl/lib/ldap.c b/contrib/libs/curl/lib/ldap.c
index 99af8e5e8f..ab60704225 100644
--- a/contrib/libs/curl/lib/ldap.c
+++ b/contrib/libs/curl/lib/ldap.c
@@ -1,189 +1,189 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP)
-
-/*
- * Notice that USE_OPENLDAP is only a source code selection switch. When
- * libcurl is built with USE_OPENLDAP defined the libcurl source code that
- * gets compiled is the code from openldap.c, otherwise the code that gets
- * compiled is the code from ldap.c.
- *
- * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
- * might be required for compilation and runtime. In order to use ancient
- * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
- */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP)
+
+/*
+ * Notice that USE_OPENLDAP is only a source code selection switch. When
+ * libcurl is built with USE_OPENLDAP defined the libcurl source code that
+ * gets compiled is the code from openldap.c, otherwise the code that gets
+ * compiled is the code from ldap.c.
+ *
+ * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
+ * might be required for compilation and runtime. In order to use ancient
+ * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
+ */
+
#ifdef USE_WIN32_LDAP /* Use Windows LDAP implementation. */
-# include <winldap.h>
-# ifndef LDAP_VENDOR_NAME
-# error Your Platform SDK is NOT sufficient for LDAP support! \
- Update your Platform SDK, or disable LDAP support!
-# else
-# include <winber.h>
-# endif
-#else
-# define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */
-# ifdef HAVE_LBER_H
+# include <winldap.h>
+# ifndef LDAP_VENDOR_NAME
+# error Your Platform SDK is NOT sufficient for LDAP support! \
+ Update your Platform SDK, or disable LDAP support!
+# else
+# include <winber.h>
+# endif
+#else
+# define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */
+# ifdef HAVE_LBER_H
# error #include <lber.h>
-# endif
+# endif
# error #include <ldap.h>
-# if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H))
-# include <ldap_ssl.h>
-# endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "sendf.h"
-#include "escape.h"
-#include "progress.h"
-#include "transfer.h"
+# if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H))
+# include <ldap_ssl.h>
+# endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "sendf.h"
+#include "escape.h"
+#include "progress.h"
+#include "transfer.h"
#include "strcase.h"
-#include "strtok.h"
-#include "curl_ldap.h"
+#include "strtok.h"
+#include "curl_ldap.h"
#include "curl_multibyte.h"
#include "curl_base64.h"
#include "connect.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-#ifndef HAVE_LDAP_URL_PARSE
-
-/* Use our own implementation. */
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#ifndef HAVE_LDAP_URL_PARSE
+
+/* Use our own implementation. */
+
struct ldap_urldesc {
- char *lud_host;
- int lud_port;
+ char *lud_host;
+ int lud_port;
#if defined(USE_WIN32_LDAP)
TCHAR *lud_dn;
TCHAR **lud_attrs;
#else
- char *lud_dn;
- char **lud_attrs;
+ char *lud_dn;
+ char **lud_attrs;
#endif
- int lud_scope;
+ int lud_scope;
#if defined(USE_WIN32_LDAP)
TCHAR *lud_filter;
#else
- char *lud_filter;
+ char *lud_filter;
#endif
- char **lud_exts;
- size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the
- "real" struct so can only be used in code
- without HAVE_LDAP_URL_PARSE defined */
+ char **lud_exts;
+ size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the
+ "real" struct so can only be used in code
+ without HAVE_LDAP_URL_PARSE defined */
};
-
-#undef LDAPURLDesc
+
+#undef LDAPURLDesc
#define LDAPURLDesc struct ldap_urldesc
-
+
static int _ldap_url_parse(const struct connectdata *conn,
LDAPURLDesc **ludp);
static void _ldap_free_urldesc(LDAPURLDesc *ludp);
-
-#undef ldap_free_urldesc
-#define ldap_free_urldesc _ldap_free_urldesc
-#endif
-
-#ifdef DEBUG_LDAP
- #define LDAP_TRACE(x) do { \
+
+#undef ldap_free_urldesc
+#define ldap_free_urldesc _ldap_free_urldesc
+#endif
+
+#ifdef DEBUG_LDAP
+ #define LDAP_TRACE(x) do { \
_ldap_trace("%u: ", __LINE__); \
- _ldap_trace x; \
+ _ldap_trace x; \
} while(0)
-
+
static void _ldap_trace(const char *fmt, ...);
-#else
- #define LDAP_TRACE(x) Curl_nop_stmt
-#endif
-
+#else
+ #define LDAP_TRACE(x) Curl_nop_stmt
+#endif
+
#if defined(USE_WIN32_LDAP) && defined(ldap_err2string)
/* Use ansi error strings in UNICODE builds */
#undef ldap_err2string
#define ldap_err2string ldap_err2stringA
#endif
-
-
-static CURLcode Curl_ldap(struct connectdata *conn, bool *done);
-
-/*
- * LDAP protocol handler.
- */
-
-const struct Curl_handler Curl_handler_ldap = {
- "LDAP", /* scheme */
- ZERO_NULL, /* setup_connection */
- Curl_ldap, /* do_it */
- ZERO_NULL, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+
+
+static CURLcode Curl_ldap(struct connectdata *conn, bool *done);
+
+/*
+ * LDAP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_ldap = {
+ "LDAP", /* scheme */
+ ZERO_NULL, /* setup_connection */
+ Curl_ldap, /* do_it */
+ ZERO_NULL, /* done */
+ ZERO_NULL, /* do_more */
+ ZERO_NULL, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_LDAP, /* defport */
- CURLPROTO_LDAP, /* protocol */
+ PORT_LDAP, /* defport */
+ CURLPROTO_LDAP, /* protocol */
CURLPROTO_LDAP, /* family */
- PROTOPT_NONE /* flags */
-};
-
-#ifdef HAVE_LDAP_SSL
-/*
- * LDAPS protocol handler.
- */
-
-const struct Curl_handler Curl_handler_ldaps = {
- "LDAPS", /* scheme */
- ZERO_NULL, /* setup_connection */
- Curl_ldap, /* do_it */
- ZERO_NULL, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+ PROTOPT_NONE /* flags */
+};
+
+#ifdef HAVE_LDAP_SSL
+/*
+ * LDAPS protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_ldaps = {
+ "LDAPS", /* scheme */
+ ZERO_NULL, /* setup_connection */
+ Curl_ldap, /* do_it */
+ ZERO_NULL, /* done */
+ ZERO_NULL, /* do_more */
+ ZERO_NULL, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_LDAPS, /* defport */
+ PORT_LDAPS, /* defport */
CURLPROTO_LDAPS, /* protocol */
CURLPROTO_LDAP, /* family */
- PROTOPT_SSL /* flags */
-};
-#endif
-
+ PROTOPT_SSL /* flags */
+};
+#endif
+
#if defined(USE_WIN32_LDAP)
-
+
#if defined(USE_WINDOWS_SSPI)
static int ldap_win_bind_auth(LDAP *server, const char *user,
const char *passwd, unsigned long authflags)
@@ -266,24 +266,24 @@ static int ldap_win_bind(struct connectdata *conn, LDAP *server,
#endif
-static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
-{
+static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
+{
CURLcode result = CURLE_OK;
- int rc = 0;
- LDAP *server = NULL;
- LDAPURLDesc *ludp = NULL;
+ int rc = 0;
+ LDAP *server = NULL;
+ LDAPURLDesc *ludp = NULL;
LDAPMessage *ldapmsg = NULL;
- LDAPMessage *entryIterator;
- int num = 0;
+ LDAPMessage *entryIterator;
+ int num = 0;
struct Curl_easy *data = conn->data;
- int ldap_proto = LDAP_VERSION3;
- int ldap_ssl = 0;
- char *val_b64 = NULL;
- size_t val_b64_sz = 0;
- curl_off_t dlsize = 0;
-#ifdef LDAP_OPT_NETWORK_TIMEOUT
+ int ldap_proto = LDAP_VERSION3;
+ int ldap_ssl = 0;
+ char *val_b64 = NULL;
+ size_t val_b64_sz = 0;
+ curl_off_t dlsize = 0;
+#ifdef LDAP_OPT_NETWORK_TIMEOUT
struct timeval ldap_timeout = {10, 0}; /* 10 sec connection/search timeout */
-#endif
+#endif
#if defined(USE_WIN32_LDAP)
TCHAR *host = NULL;
#else
@@ -291,29 +291,29 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
#endif
char *user = NULL;
char *passwd = NULL;
-
- *done = TRUE; /* unconditionally */
- infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d\n",
- LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION);
- infof(data, "LDAP local: %s\n", data->change.url);
-
-#ifdef HAVE_LDAP_URL_PARSE
- rc = ldap_url_parse(data->change.url, &ludp);
-#else
- rc = _ldap_url_parse(conn, &ludp);
-#endif
- if(rc != 0) {
- failf(data, "LDAP local: %s", ldap_err2string(rc));
+
+ *done = TRUE; /* unconditionally */
+ infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d\n",
+ LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION);
+ infof(data, "LDAP local: %s\n", data->change.url);
+
+#ifdef HAVE_LDAP_URL_PARSE
+ rc = ldap_url_parse(data->change.url, &ludp);
+#else
+ rc = _ldap_url_parse(conn, &ludp);
+#endif
+ if(rc != 0) {
+ failf(data, "LDAP local: %s", ldap_err2string(rc));
result = CURLE_LDAP_INVALID_URL;
- goto quit;
- }
-
+ goto quit;
+ }
+
/* Get the URL scheme (either ldap or ldaps) */
- if(conn->given->flags & PROTOPT_SSL)
- ldap_ssl = 1;
- infof(data, "LDAP local: trying to establish %s connection\n",
- ldap_ssl ? "encrypted" : "cleartext");
-
+ if(conn->given->flags & PROTOPT_SSL)
+ ldap_ssl = 1;
+ infof(data, "LDAP local: trying to establish %s connection\n",
+ ldap_ssl ? "encrypted" : "cleartext");
+
#if defined(USE_WIN32_LDAP)
host = curlx_convert_UTF8_to_tchar(conn->host.name);
if(!host) {
@@ -330,162 +330,162 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
passwd = conn->passwd;
}
-#ifdef LDAP_OPT_NETWORK_TIMEOUT
- ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout);
-#endif
- ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
-
- if(ldap_ssl) {
-#ifdef HAVE_LDAP_SSL
+#ifdef LDAP_OPT_NETWORK_TIMEOUT
+ ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout);
+#endif
+ ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
+
+ if(ldap_ssl) {
+#ifdef HAVE_LDAP_SSL
#ifdef USE_WIN32_LDAP
- /* Win32 LDAP SDK doesn't support insecure mode without CA! */
+ /* Win32 LDAP SDK doesn't support insecure mode without CA! */
server = ldap_sslinit(host, (int)conn->port, 1);
- ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON);
-#else
- int ldap_option;
+ ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON);
+#else
+ int ldap_option;
char *ldap_ca = conn->ssl_config.CAfile;
-#if defined(CURL_HAS_NOVELL_LDAPSDK)
- rc = ldapssl_client_init(NULL, NULL);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc));
+#if defined(CURL_HAS_NOVELL_LDAPSDK)
+ rc = ldapssl_client_init(NULL, NULL);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
+ goto quit;
+ }
if(conn->ssl_config.verifypeer) {
- /* Novell SDK supports DER or BASE64 files. */
- int cert_type = LDAPSSL_CERT_FILETYPE_B64;
+ /* Novell SDK supports DER or BASE64 files. */
+ int cert_type = LDAPSSL_CERT_FILETYPE_B64;
if((data->set.ssl.cert_type) &&
(strcasecompare(data->set.ssl.cert_type, "DER")))
- cert_type = LDAPSSL_CERT_FILETYPE_DER;
- if(!ldap_ca) {
- failf(data, "LDAP local: ERROR %s CA cert not set!",
- (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"));
+ cert_type = LDAPSSL_CERT_FILETYPE_DER;
+ if(!ldap_ca) {
+ failf(data, "LDAP local: ERROR %s CA cert not set!",
+ (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
- infof(data, "LDAP local: using %s CA cert '%s'\n",
- (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
- ldap_ca);
- rc = ldapssl_add_trusted_cert(ldap_ca, cert_type);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ERROR setting %s CA cert: %s",
- (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
- ldap_err2string(rc));
+ goto quit;
+ }
+ infof(data, "LDAP local: using %s CA cert '%s'\n",
+ (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
+ ldap_ca);
+ rc = ldapssl_add_trusted_cert(ldap_ca, cert_type);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ERROR setting %s CA cert: %s",
+ (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
+ ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
- ldap_option = LDAPSSL_VERIFY_SERVER;
- }
- else
- ldap_option = LDAPSSL_VERIFY_NONE;
- rc = ldapssl_set_verify_mode(ldap_option);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ERROR setting cert verify mode: %s",
- ldap_err2string(rc));
+ goto quit;
+ }
+ ldap_option = LDAPSSL_VERIFY_SERVER;
+ }
+ else
+ ldap_option = LDAPSSL_VERIFY_NONE;
+ rc = ldapssl_set_verify_mode(ldap_option);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ERROR setting cert verify mode: %s",
+ ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
+ goto quit;
+ }
server = ldapssl_init(host, (int)conn->port, 1);
- if(server == NULL) {
- failf(data, "LDAP local: Cannot connect to %s:%ld",
+ if(server == NULL) {
+ failf(data, "LDAP local: Cannot connect to %s:%ld",
conn->host.dispname, conn->port);
result = CURLE_COULDNT_CONNECT;
- goto quit;
- }
-#elif defined(LDAP_OPT_X_TLS)
+ goto quit;
+ }
+#elif defined(LDAP_OPT_X_TLS)
if(conn->ssl_config.verifypeer) {
- /* OpenLDAP SDK supports BASE64 files. */
+ /* OpenLDAP SDK supports BASE64 files. */
if((data->set.ssl.cert_type) &&
(!strcasecompare(data->set.ssl.cert_type, "PEM"))) {
- failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!");
+ failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!");
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
- if(!ldap_ca) {
- failf(data, "LDAP local: ERROR PEM CA cert not set!");
+ goto quit;
+ }
+ if(!ldap_ca) {
+ failf(data, "LDAP local: ERROR PEM CA cert not set!");
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
- infof(data, "LDAP local: using PEM CA cert: %s\n", ldap_ca);
- rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ERROR setting PEM CA cert: %s",
- ldap_err2string(rc));
+ goto quit;
+ }
+ infof(data, "LDAP local: using PEM CA cert: %s\n", ldap_ca);
+ rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ERROR setting PEM CA cert: %s",
+ ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
- ldap_option = LDAP_OPT_X_TLS_DEMAND;
- }
- else
- ldap_option = LDAP_OPT_X_TLS_NEVER;
-
- rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ERROR setting cert verify mode: %s",
- ldap_err2string(rc));
+ goto quit;
+ }
+ ldap_option = LDAP_OPT_X_TLS_DEMAND;
+ }
+ else
+ ldap_option = LDAP_OPT_X_TLS_NEVER;
+
+ rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ERROR setting cert verify mode: %s",
+ ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
+ goto quit;
+ }
server = ldap_init(host, (int)conn->port);
- if(server == NULL) {
- failf(data, "LDAP local: Cannot connect to %s:%ld",
+ if(server == NULL) {
+ failf(data, "LDAP local: Cannot connect to %s:%ld",
conn->host.dispname, conn->port);
result = CURLE_COULDNT_CONNECT;
- goto quit;
- }
- ldap_option = LDAP_OPT_X_TLS_HARD;
- rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s",
- ldap_err2string(rc));
+ goto quit;
+ }
+ ldap_option = LDAP_OPT_X_TLS_HARD;
+ rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s",
+ ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
-/*
- rc = ldap_start_tls_s(server, NULL, NULL);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s",
- ldap_err2string(rc));
+ goto quit;
+ }
+/*
+ rc = ldap_start_tls_s(server, NULL, NULL);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s",
+ ldap_err2string(rc));
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
- }
-*/
-#else
- /* we should probably never come up to here since configure
- should check in first place if we can support LDAP SSL/TLS */
- failf(data, "LDAP local: SSL/TLS not supported with this version "
- "of the OpenLDAP toolkit\n");
+ goto quit;
+ }
+*/
+#else
+ /* we should probably never come up to here since configure
+ should check in first place if we can support LDAP SSL/TLS */
+ failf(data, "LDAP local: SSL/TLS not supported with this version "
+ "of the OpenLDAP toolkit\n");
result = CURLE_SSL_CERTPROBLEM;
- goto quit;
-#endif
-#endif
-#endif /* CURL_LDAP_USE_SSL */
- }
- else {
+ goto quit;
+#endif
+#endif
+#endif /* CURL_LDAP_USE_SSL */
+ }
+ else {
server = ldap_init(host, (int)conn->port);
- if(server == NULL) {
- failf(data, "LDAP local: Cannot connect to %s:%ld",
+ if(server == NULL) {
+ failf(data, "LDAP local: Cannot connect to %s:%ld",
conn->host.dispname, conn->port);
result = CURLE_COULDNT_CONNECT;
- goto quit;
- }
- }
+ goto quit;
+ }
+ }
#ifdef USE_WIN32_LDAP
- ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
+ ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
rc = ldap_win_bind(conn, server, user, passwd);
#else
rc = ldap_simple_bind_s(server, user, passwd);
#endif
- if(!ldap_ssl && rc != 0) {
- ldap_proto = LDAP_VERSION2;
- ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
+ if(!ldap_ssl && rc != 0) {
+ ldap_proto = LDAP_VERSION2;
+ ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
#ifdef USE_WIN32_LDAP
rc = ldap_win_bind(conn, server, user, passwd);
#else
rc = ldap_simple_bind_s(server, user, passwd);
#endif
- }
- if(rc != 0) {
+ }
+ if(rc != 0) {
#ifdef USE_WIN32_LDAP
failf(data, "LDAP local: bind via ldap_win_bind %s",
ldap_err2string(rc));
@@ -494,29 +494,29 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
ldap_err2string(rc));
#endif
result = CURLE_LDAP_CANNOT_BIND;
- goto quit;
- }
-
- rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope,
+ goto quit;
+ }
+
+ rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope,
ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg);
-
- if(rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) {
- failf(data, "LDAP remote: %s", ldap_err2string(rc));
+
+ if(rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) {
+ failf(data, "LDAP remote: %s", ldap_err2string(rc));
result = CURLE_LDAP_SEARCH_FAILED;
- goto quit;
- }
-
+ goto quit;
+ }
+
for(num = 0, entryIterator = ldap_first_entry(server, ldapmsg);
- entryIterator;
- entryIterator = ldap_next_entry(server, entryIterator), num++) {
- BerElement *ber = NULL;
+ entryIterator;
+ entryIterator = ldap_next_entry(server, entryIterator), num++) {
+ BerElement *ber = NULL;
#if defined(USE_WIN32_LDAP)
TCHAR *attribute;
#else
char *attribute;
#endif
- int i;
-
+ int i;
+
/* Get the DN and write it to the client */
{
char *name;
@@ -526,9 +526,9 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
name = curlx_convert_tchar_to_UTF8(dn);
if(!name) {
ldap_memfree(dn);
-
+
result = CURLE_OUT_OF_MEMORY;
-
+
goto quit;
}
#else
@@ -566,9 +566,9 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
}
/* Get the attributes and write them to the client */
- for(attribute = ldap_first_attribute(server, entryIterator, &ber);
- attribute;
- attribute = ldap_next_attribute(server, entryIterator, ber)) {
+ for(attribute = ldap_first_attribute(server, entryIterator, &ber);
+ attribute;
+ attribute = ldap_next_attribute(server, entryIterator, ber)) {
BerValue **vals;
size_t attr_len;
#if defined(USE_WIN32_LDAP)
@@ -576,7 +576,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
if(!attr) {
if(ber)
ber_free(ber, 0);
-
+
result = CURLE_OUT_OF_MEMORY;
goto quit;
@@ -587,8 +587,8 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
attr_len = strlen(attr);
vals = ldap_get_values_len(server, entryIterator, attribute);
- if(vals != NULL) {
- for(i = 0; (vals[i] != NULL); i++) {
+ if(vals != NULL) {
+ for(i = 0; (vals[i] != NULL); i++) {
result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1);
if(result) {
ldap_value_free_len(vals);
@@ -596,7 +596,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
ldap_memfree(attribute);
if(ber)
ber_free(ber, 0);
-
+
goto quit;
}
@@ -627,26 +627,26 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
if((attr_len > 7) &&
(strcmp(";binary", (char *) attr + (attr_len - 7)) == 0)) {
- /* Binary attribute, encode to base64. */
+ /* Binary attribute, encode to base64. */
result = Curl_base64_encode(data,
vals[i]->bv_val,
vals[i]->bv_len,
&val_b64,
&val_b64_sz);
if(result) {
- ldap_value_free_len(vals);
+ ldap_value_free_len(vals);
FREE_ON_WINLDAP(attr);
- ldap_memfree(attribute);
- if(ber)
- ber_free(ber, 0);
+ ldap_memfree(attribute);
+ if(ber)
+ ber_free(ber, 0);
- goto quit;
- }
+ goto quit;
+ }
- if(val_b64_sz > 0) {
+ if(val_b64_sz > 0) {
result = Curl_client_write(conn, CLIENTWRITE_BODY, val_b64,
val_b64_sz);
- free(val_b64);
+ free(val_b64);
if(result) {
ldap_value_free_len(vals);
FREE_ON_WINLDAP(attr);
@@ -657,10 +657,10 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
goto quit;
}
- dlsize += val_b64_sz;
- }
- }
- else {
+ dlsize += val_b64_sz;
+ }
+ }
+ else {
result = Curl_client_write(conn, CLIENTWRITE_BODY, vals[i]->bv_val,
vals[i]->bv_len);
if(result) {
@@ -673,8 +673,8 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
goto quit;
}
- dlsize += vals[i]->bv_len;
- }
+ dlsize += vals[i]->bv_len;
+ }
result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1);
if(result) {
@@ -687,12 +687,12 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
goto quit;
}
- dlsize++;
- }
-
- /* Free memory used to store values */
- ldap_value_free_len(vals);
- }
+ dlsize++;
+ }
+
+ /* Free memory used to store values */
+ ldap_value_free_len(vals);
+ }
/* Free the attribute as we are done with it */
FREE_ON_WINLDAP(attr);
@@ -701,65 +701,65 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1);
if(result)
goto quit;
- dlsize++;
- Curl_pgrsSetDownloadCounter(data, dlsize);
- }
-
- if(ber)
- ber_free(ber, 0);
- }
-
-quit:
+ dlsize++;
+ Curl_pgrsSetDownloadCounter(data, dlsize);
+ }
+
+ if(ber)
+ ber_free(ber, 0);
+ }
+
+quit:
if(ldapmsg) {
ldap_msgfree(ldapmsg);
LDAP_TRACE(("Received %d entries\n", num));
- }
- if(rc == LDAP_SIZELIMIT_EXCEEDED)
- infof(data, "There are more than %d entries\n", num);
- if(ludp)
- ldap_free_urldesc(ludp);
- if(server)
- ldap_unbind_s(server);
-#if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK)
- if(ldap_ssl)
- ldapssl_client_deinit();
-#endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */
-
+ }
+ if(rc == LDAP_SIZELIMIT_EXCEEDED)
+ infof(data, "There are more than %d entries\n", num);
+ if(ludp)
+ ldap_free_urldesc(ludp);
+ if(server)
+ ldap_unbind_s(server);
+#if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK)
+ if(ldap_ssl)
+ ldapssl_client_deinit();
+#endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */
+
FREE_ON_WINLDAP(host);
- /* no data to transfer */
+ /* no data to transfer */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
connclose(conn, "LDAP connection always disable re-use");
-
+
return result;
-}
-
-#ifdef DEBUG_LDAP
+}
+
+#ifdef DEBUG_LDAP
static void _ldap_trace(const char *fmt, ...)
-{
- static int do_trace = -1;
- va_list args;
-
- if(do_trace == -1) {
- const char *env = getenv("CURL_TRACE");
- do_trace = (env && strtol(env, NULL, 10) > 0);
- }
- if(!do_trace)
- return;
-
+{
+ static int do_trace = -1;
+ va_list args;
+
+ if(do_trace == -1) {
+ const char *env = getenv("CURL_TRACE");
+ do_trace = (env && strtol(env, NULL, 10) > 0);
+ }
+ if(!do_trace)
+ return;
+
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
-}
-#endif
-
-#ifndef HAVE_LDAP_URL_PARSE
-
-/*
- * Return scope-value for a scope-string.
- */
+}
+#endif
+
+#ifndef HAVE_LDAP_URL_PARSE
+
+/*
+ * Return scope-value for a scope-string.
+ */
static int str2scope(const char *p)
-{
+{
if(strcasecompare(p, "one"))
return LDAP_SCOPE_ONELEVEL;
if(strcasecompare(p, "onetree"))
@@ -770,79 +770,79 @@ static int str2scope(const char *p)
return LDAP_SCOPE_SUBTREE;
if(strcasecompare(p, "subtree"))
return LDAP_SCOPE_SUBTREE;
- return (-1);
-}
-
-/*
- * Split 'str' into strings separated by commas.
+ return (-1);
+}
+
+/*
+ * Split 'str' into strings separated by commas.
* Note: out[] points into 'str'.
- */
+ */
static bool split_str(char *str, char ***out, size_t *count)
-{
+{
char **res;
char *lasts;
char *s;
size_t i;
size_t items = 1;
-
+
s = strchr(str, ',');
while(s) {
items++;
s = strchr(++s, ',');
}
-
+
res = calloc(items, sizeof(char *));
- if(!res)
+ if(!res)
return FALSE;
-
+
for(i = 0, s = strtok_r(str, ",", &lasts); s && i < items;
- s = strtok_r(NULL, ",", &lasts), i++)
- res[i] = s;
-
+ s = strtok_r(NULL, ",", &lasts), i++)
+ res[i] = s;
+
*out = res;
*count = items;
-
+
return TRUE;
-}
-
-/*
- * Break apart the pieces of an LDAP URL.
- * Syntax:
- * ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
- *
- * <hostname> already known from 'conn->host.name'.
- * <port> already known from 'conn->remote_port'.
- * extract the rest from 'conn->data->state.path+1'. All fields are optional.
- * e.g.
- * ldap://<hostname>:<port>/?<attributes>?<scope>?<filter>
- * yields ludp->lud_dn = "".
- *
- * Defined in RFC4516 section 2.
- */
+}
+
+/*
+ * Break apart the pieces of an LDAP URL.
+ * Syntax:
+ * ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
+ *
+ * <hostname> already known from 'conn->host.name'.
+ * <port> already known from 'conn->remote_port'.
+ * extract the rest from 'conn->data->state.path+1'. All fields are optional.
+ * e.g.
+ * ldap://<hostname>:<port>/?<attributes>?<scope>?<filter>
+ * yields ludp->lud_dn = "".
+ *
+ * Defined in RFC4516 section 2.
+ */
static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp)
-{
+{
int rc = LDAP_SUCCESS;
char *p;
char *path;
char *q = NULL;
char *query = NULL;
size_t i;
-
- if(!conn->data ||
+
+ if(!conn->data ||
!conn->data->state.up.path ||
conn->data->state.up.path[0] != '/' ||
!strncasecompare("LDAP", conn->data->state.up.scheme, 4))
- return LDAP_INVALID_SYNTAX;
-
- ludp->lud_scope = LDAP_SCOPE_BASE;
- ludp->lud_port = conn->remote_port;
- ludp->lud_host = conn->host.name;
-
+ return LDAP_INVALID_SYNTAX;
+
+ ludp->lud_scope = LDAP_SCOPE_BASE;
+ ludp->lud_port = conn->remote_port;
+ ludp->lud_host = conn->host.name;
+
/* Duplicate the path */
p = path = strdup(conn->data->state.up.path + 1);
if(!path)
- return LDAP_NO_MEMORY;
-
+ return LDAP_NO_MEMORY;
+
/* Duplicate the query if present */
if(conn->data->state.up.query) {
q = query = strdup(conn->data->state.up.query);
@@ -851,7 +851,7 @@ static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp)
return LDAP_NO_MEMORY;
}
}
-
+
/* Parse the DN (Distinguished Name) */
if(*p) {
char *dn = p;
@@ -886,18 +886,18 @@ static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp)
}
p = q;
- if(!p)
+ if(!p)
goto quit;
-
+
/* Parse the attributes. skip "??" */
- q = strchr(p, '?');
- if(q)
- *q++ = '\0';
-
+ q = strchr(p, '?');
+ if(q)
+ *q++ = '\0';
+
if(*p) {
char **attributes;
size_t count = 0;
-
+
/* Split the string into an array of attributes */
if(!split_str(p, &attributes, &count)) {
rc = LDAP_NO_MEMORY;
@@ -958,35 +958,35 @@ static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp)
}
free(attributes);
- }
-
- p = q;
- if(!p)
+ }
+
+ p = q;
+ if(!p)
goto quit;
-
+
/* Parse the scope. skip "??" */
- q = strchr(p, '?');
- if(q)
- *q++ = '\0';
-
+ q = strchr(p, '?');
+ if(q)
+ *q++ = '\0';
+
if(*p) {
- ludp->lud_scope = str2scope(p);
- if(ludp->lud_scope == -1) {
+ ludp->lud_scope = str2scope(p);
+ if(ludp->lud_scope == -1) {
rc = LDAP_INVALID_SYNTAX;
goto quit;
- }
+ }
LDAP_TRACE(("scope %d\n", ludp->lud_scope));
- }
-
- p = q;
- if(!p)
+ }
+
+ p = q;
+ if(!p)
goto quit;
-
+
/* Parse the filter */
- q = strchr(p, '?');
- if(q)
- *q++ = '\0';
+ q = strchr(p, '?');
+ if(q)
+ *q++ = '\0';
if(*p) {
char *filter = p;
@@ -1019,12 +1019,12 @@ static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp)
#else
ludp->lud_filter = unescaped;
#endif
- }
-
+ }
+
p = q;
if(p && !*p) {
rc = LDAP_INVALID_SYNTAX;
-
+
goto quit;
}
@@ -1033,43 +1033,43 @@ quit:
free(query);
return rc;
-}
-
+}
+
static int _ldap_url_parse(const struct connectdata *conn,
LDAPURLDesc **ludpp)
-{
- LDAPURLDesc *ludp = calloc(1, sizeof(*ludp));
- int rc;
-
- *ludpp = NULL;
- if(!ludp)
- return LDAP_NO_MEMORY;
-
+{
+ LDAPURLDesc *ludp = calloc(1, sizeof(*ludp));
+ int rc;
+
+ *ludpp = NULL;
+ if(!ludp)
+ return LDAP_NO_MEMORY;
+
rc = _ldap_url_parse2(conn, ludp);
- if(rc != LDAP_SUCCESS) {
- _ldap_free_urldesc(ludp);
- ludp = NULL;
- }
- *ludpp = ludp;
- return (rc);
-}
-
+ if(rc != LDAP_SUCCESS) {
+ _ldap_free_urldesc(ludp);
+ ludp = NULL;
+ }
+ *ludpp = ludp;
+ return (rc);
+}
+
static void _ldap_free_urldesc(LDAPURLDesc *ludp)
-{
- if(!ludp)
- return;
-
+{
+ if(!ludp)
+ return;
+
free(ludp->lud_dn);
free(ludp->lud_filter);
-
- if(ludp->lud_attrs) {
+
+ if(ludp->lud_attrs) {
size_t i;
- for(i = 0; i < ludp->lud_attrs_dups; i++)
- free(ludp->lud_attrs[i]);
- free(ludp->lud_attrs);
- }
-
+ for(i = 0; i < ludp->lud_attrs_dups; i++)
+ free(ludp->lud_attrs[i]);
+ free(ludp->lud_attrs);
+ }
+
free(ludp);
-}
-#endif /* !HAVE_LDAP_URL_PARSE */
-#endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */
+}
+#endif /* !HAVE_LDAP_URL_PARSE */
+#endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */
diff --git a/contrib/libs/curl/lib/llist.c b/contrib/libs/curl/lib/llist.c
index 65d21e5572..17a7be1667 100644
--- a/contrib/libs/curl/lib/llist.c
+++ b/contrib/libs/curl/lib/llist.c
@@ -1,146 +1,146 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <curl/curl.h>
-#include "llist.h"
-#include "curl_memory.h"
-
-/* this must be the last include file */
-#include "memdebug.h"
-
-/*
- * @unittest: 1300
- */
+#include "llist.h"
+#include "curl_memory.h"
+
+/* this must be the last include file */
+#include "memdebug.h"
+
+/*
+ * @unittest: 1300
+ */
void
Curl_llist_init(struct Curl_llist *l, Curl_llist_dtor dtor)
-{
- l->size = 0;
- l->dtor = dtor;
- l->head = NULL;
- l->tail = NULL;
-}
-
-/*
- * Curl_llist_insert_next()
- *
- * Inserts a new list element after the given one 'e'. If the given existing
- * entry is NULL and the list already has elements, the new one will be
- * inserted first in the list.
- *
+{
+ l->size = 0;
+ l->dtor = dtor;
+ l->head = NULL;
+ l->tail = NULL;
+}
+
+/*
+ * Curl_llist_insert_next()
+ *
+ * Inserts a new list element after the given one 'e'. If the given existing
+ * entry is NULL and the list already has elements, the new one will be
+ * inserted first in the list.
+ *
* The 'ne' argument should be a pointer into the object to store.
- *
- * @unittest: 1300
- */
+ *
+ * @unittest: 1300
+ */
void
Curl_llist_insert_next(struct Curl_llist *list, struct Curl_llist_element *e,
const void *p,
struct Curl_llist_element *ne)
-{
- ne->ptr = (void *) p;
- if(list->size == 0) {
- list->head = ne;
- list->head->prev = NULL;
- list->head->next = NULL;
- list->tail = ne;
- }
- else {
- /* if 'e' is NULL here, we insert the new element first in the list */
- ne->next = e?e->next:list->head;
- ne->prev = e;
- if(!e) {
- list->head->prev = ne;
- list->head = ne;
- }
- else if(e->next) {
- e->next->prev = ne;
- }
- else {
- list->tail = ne;
- }
- if(e)
- e->next = ne;
- }
-
- ++list->size;
-}
-
-/*
- * @unittest: 1300
- */
+{
+ ne->ptr = (void *) p;
+ if(list->size == 0) {
+ list->head = ne;
+ list->head->prev = NULL;
+ list->head->next = NULL;
+ list->tail = ne;
+ }
+ else {
+ /* if 'e' is NULL here, we insert the new element first in the list */
+ ne->next = e?e->next:list->head;
+ ne->prev = e;
+ if(!e) {
+ list->head->prev = ne;
+ list->head = ne;
+ }
+ else if(e->next) {
+ e->next->prev = ne;
+ }
+ else {
+ list->tail = ne;
+ }
+ if(e)
+ e->next = ne;
+ }
+
+ ++list->size;
+}
+
+/*
+ * @unittest: 1300
+ */
void
Curl_llist_remove(struct Curl_llist *list, struct Curl_llist_element *e,
- void *user)
-{
+ void *user)
+{
void *ptr;
- if(e == NULL || list->size == 0)
+ if(e == NULL || list->size == 0)
return;
-
- if(e == list->head) {
- list->head = e->next;
-
- if(list->head == NULL)
- list->tail = NULL;
- else
- e->next->prev = NULL;
- }
- else {
+
+ if(e == list->head) {
+ list->head = e->next;
+
+ if(list->head == NULL)
+ list->tail = NULL;
+ else
+ e->next->prev = NULL;
+ }
+ else {
if(!e->prev)
list->head = e->next;
else
e->prev->next = e->next;
- if(!e->next)
- list->tail = e->prev;
- else
- e->next->prev = e->prev;
- }
-
+ if(!e->next)
+ list->tail = e->prev;
+ else
+ e->next->prev = e->prev;
+ }
+
ptr = e->ptr;
-
- e->ptr = NULL;
- e->prev = NULL;
- e->next = NULL;
-
- --list->size;
-
+
+ e->ptr = NULL;
+ e->prev = NULL;
+ e->next = NULL;
+
+ --list->size;
+
/* call the dtor() last for when it actually frees the 'e' memory itself */
if(list->dtor)
list->dtor(user, ptr);
-}
-
-void
+}
+
+void
Curl_llist_destroy(struct Curl_llist *list, void *user)
-{
- if(list) {
- while(list->size > 0)
- Curl_llist_remove(list, list->tail, user);
- }
-}
-
-size_t
+{
+ if(list) {
+ while(list->size > 0)
+ Curl_llist_remove(list, list->tail, user);
+ }
+}
+
+size_t
Curl_llist_count(struct Curl_llist *list)
-{
- return list->size;
-}
+{
+ return list->size;
+}
diff --git a/contrib/libs/curl/lib/llist.h b/contrib/libs/curl/lib/llist.h
index 03a87374ee..ceae2dd1b7 100644
--- a/contrib/libs/curl/lib/llist.h
+++ b/contrib/libs/curl/lib/llist.h
@@ -1,45 +1,45 @@
-#ifndef HEADER_CURL_LLIST_H
-#define HEADER_CURL_LLIST_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_LLIST_H
+#define HEADER_CURL_LLIST_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-#include <stddef.h>
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+#include <stddef.h>
+
typedef void (*Curl_llist_dtor)(void *, void *);
-
+
struct Curl_llist_element {
- void *ptr;
+ void *ptr;
struct Curl_llist_element *prev;
struct Curl_llist_element *next;
-};
-
+};
+
struct Curl_llist {
struct Curl_llist_element *head;
struct Curl_llist_element *tail;
Curl_llist_dtor dtor;
- size_t size;
-};
-
+ size_t size;
+};
+
void Curl_llist_init(struct Curl_llist *, Curl_llist_dtor);
void Curl_llist_insert_next(struct Curl_llist *, struct Curl_llist_element *,
const void *, struct Curl_llist_element *node);
@@ -47,4 +47,4 @@ void Curl_llist_remove(struct Curl_llist *, struct Curl_llist_element *,
void *);
size_t Curl_llist_count(struct Curl_llist *);
void Curl_llist_destroy(struct Curl_llist *, void *);
-#endif /* HEADER_CURL_LLIST_H */
+#endif /* HEADER_CURL_LLIST_H */
diff --git a/contrib/libs/curl/lib/md4.c b/contrib/libs/curl/lib/md4.c
index fedbf4e882..d3355ad929 100644
--- a/contrib/libs/curl/lib/md4.c
+++ b/contrib/libs/curl/lib/md4.c
@@ -262,14 +262,14 @@ static void MD4_Final(unsigned char *result, MD4_CTX *ctx)
* It is meant to be fast, but not as fast as possible. Some known
* optimizations are not included to reduce source code size and avoid
* compile-time configuration.
- */
-
-
+ */
+
+
#include <string.h>
-
+
/* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned int MD4_u32plus;
-
+
struct md4_ctx {
MD4_u32plus lo, hi;
MD4_u32plus a, b, c, d;
@@ -277,28 +277,28 @@ struct md4_ctx {
MD4_u32plus block[16];
};
typedef struct md4_ctx MD4_CTX;
-
+
static void MD4_Init(MD4_CTX *ctx);
static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size);
static void MD4_Final(unsigned char *result, MD4_CTX *ctx);
-
+
/*
* The basic MD4 functions.
*
* F and G are optimized compared to their RFC 1320 definitions, with the
* optimization for F borrowed from Colin Plumb's MD5 implementation.
- */
+ */
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z) (((x) & ((y) | (z))) | ((y) & (z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
-
+
/*
* The MD4 transformation for all three rounds.
- */
+ */
#define STEP(f, a, b, c, d, x, s) \
(a) += f((b), (c), (d)) + (x); \
(a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s))));
-
+
/*
* SET reads 4 input bytes in little-endian byte order and stores them
* in a properly aligned word in host byte order.
@@ -322,23 +322,23 @@ static void MD4_Final(unsigned char *result, MD4_CTX *ctx);
#define GET(n) \
(ctx->block[(n)])
#endif
-
+
/*
* This processes one or more 64-byte data blocks, but does NOT update
* the bit counters. There are no alignment requirements.
- */
+ */
static const void *body(MD4_CTX *ctx, const void *data, unsigned long size)
-{
+{
const unsigned char *ptr;
MD4_u32plus a, b, c, d;
-
+
ptr = (const unsigned char *)data;
-
+
a = ctx->a;
b = ctx->b;
c = ctx->c;
d = ctx->d;
-
+
do {
MD4_u32plus saved_a, saved_b, saved_c, saved_d;
@@ -346,7 +346,7 @@ static const void *body(MD4_CTX *ctx, const void *data, unsigned long size)
saved_b = b;
saved_c = c;
saved_d = d;
-
+
/* Round 1 */
STEP(F, a, b, c, d, SET(0), 3)
STEP(F, d, a, b, c, SET(1), 7)
@@ -364,7 +364,7 @@ static const void *body(MD4_CTX *ctx, const void *data, unsigned long size)
STEP(F, d, a, b, c, SET(13), 7)
STEP(F, c, d, a, b, SET(14), 11)
STEP(F, b, c, d, a, SET(15), 19)
-
+
/* Round 2 */
STEP(G, a, b, c, d, GET(0) + 0x5a827999, 3)
STEP(G, d, a, b, c, GET(4) + 0x5a827999, 5)
@@ -382,7 +382,7 @@ static const void *body(MD4_CTX *ctx, const void *data, unsigned long size)
STEP(G, d, a, b, c, GET(7) + 0x5a827999, 5)
STEP(G, c, d, a, b, GET(11) + 0x5a827999, 9)
STEP(G, b, c, d, a, GET(15) + 0x5a827999, 13)
-
+
/* Round 3 */
STEP(H, a, b, c, d, GET(0) + 0x6ed9eba1, 3)
STEP(H, d, a, b, c, GET(8) + 0x6ed9eba1, 9)
@@ -400,73 +400,73 @@ static const void *body(MD4_CTX *ctx, const void *data, unsigned long size)
STEP(H, d, a, b, c, GET(11) + 0x6ed9eba1, 9)
STEP(H, c, d, a, b, GET(7) + 0x6ed9eba1, 11)
STEP(H, b, c, d, a, GET(15) + 0x6ed9eba1, 15)
-
+
a += saved_a;
b += saved_b;
c += saved_c;
d += saved_d;
-
+
ptr += 64;
} while(size -= 64);
-
+
ctx->a = a;
ctx->b = b;
ctx->c = c;
ctx->d = d;
-
+
return ptr;
-}
-
+}
+
static void MD4_Init(MD4_CTX *ctx)
-{
+{
ctx->a = 0x67452301;
ctx->b = 0xefcdab89;
ctx->c = 0x98badcfe;
ctx->d = 0x10325476;
-
+
ctx->lo = 0;
ctx->hi = 0;
-}
-
+}
+
static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size)
-{
+{
MD4_u32plus saved_lo;
unsigned long used;
-
+
saved_lo = ctx->lo;
ctx->lo = (saved_lo + size) & 0x1fffffff;
if(ctx->lo < saved_lo)
ctx->hi++;
ctx->hi += (MD4_u32plus)size >> 29;
-
+
used = saved_lo & 0x3f;
-
+
if(used) {
unsigned long available = 64 - used;
-
+
if(size < available) {
memcpy(&ctx->buffer[used], data, size);
return;
}
-
+
memcpy(&ctx->buffer[used], data, available);
data = (const unsigned char *)data + available;
size -= available;
body(ctx, ctx->buffer, 64);
}
-
+
if(size >= 64) {
data = body(ctx, data, size & ~(unsigned long)0x3f);
size &= 0x3f;
}
memcpy(ctx->buffer, data, size);
-}
-
+}
+
static void MD4_Final(unsigned char *result, MD4_CTX *ctx)
-{
+{
unsigned long used, available;
-
+
used = ctx->lo & 0x3f;
ctx->buffer[used++] = 0x80;
@@ -478,10 +478,10 @@ static void MD4_Final(unsigned char *result, MD4_CTX *ctx)
body(ctx, ctx->buffer, 64);
used = 0;
available = 64;
- }
-
+ }
+
memset(&ctx->buffer[used], 0, available - 8);
-
+
ctx->lo <<= 3;
ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff);
ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff);
@@ -512,18 +512,18 @@ static void MD4_Final(unsigned char *result, MD4_CTX *ctx)
result[15] = curlx_ultouc(ctx->d >> 24);
memset(ctx, 0, sizeof(*ctx));
-}
-
+}
+
#endif /* CRYPTO LIBS */
void Curl_md4it(unsigned char *output, const unsigned char *input,
const size_t len)
-{
- MD4_CTX ctx;
+{
+ MD4_CTX ctx;
MD4_Init(&ctx);
MD4_Update(&ctx, input, curlx_uztoui(len));
MD4_Final(output, &ctx);
-}
+}
#endif /* CURL_DISABLE_CRYPTO_AUTH */
diff --git a/contrib/libs/curl/lib/md5.c b/contrib/libs/curl/lib/md5.c
index 7165f04388..ff0b369f02 100644
--- a/contrib/libs/curl/lib/md5.c
+++ b/contrib/libs/curl/lib/md5.c
@@ -1,35 +1,35 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+
#include <curl/curl.h>
-#include "curl_md5.h"
-#include "curl_hmac.h"
-#include "warnless.h"
-
+#include "curl_md5.h"
+#include "curl_hmac.h"
+#include "warnless.h"
+
#ifdef USE_MBEDTLS
#error #include <mbedtls/version.h>
@@ -38,66 +38,66 @@
#endif
#endif /* USE_MBEDTLS */
-#if defined(USE_GNUTLS_NETTLE)
-
-#include <nettle/md5.h>
+#if defined(USE_GNUTLS_NETTLE)
+
+#include <nettle/md5.h>
#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-typedef struct md5_ctx MD5_CTX;
-
+/* The last #include file should be: */
+#include "memdebug.h"
+
+typedef struct md5_ctx MD5_CTX;
+
static void MD5_Init(MD5_CTX *ctx)
-{
- md5_init(ctx);
-}
-
+{
+ md5_init(ctx);
+}
+
static void MD5_Update(MD5_CTX *ctx,
const unsigned char *input,
- unsigned int inputLen)
-{
- md5_update(ctx, inputLen, input);
-}
-
+ unsigned int inputLen)
+{
+ md5_update(ctx, inputLen, input);
+}
+
static void MD5_Final(unsigned char *digest, MD5_CTX *ctx)
-{
- md5_digest(ctx, 16, digest);
-}
-
-#elif defined(USE_GNUTLS)
-
-#include <gcrypt.h>
+{
+ md5_digest(ctx, 16, digest);
+}
+
+#elif defined(USE_GNUTLS)
+
+#include <gcrypt.h>
#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-typedef gcry_md_hd_t MD5_CTX;
-
+/* The last #include file should be: */
+#include "memdebug.h"
+
+typedef gcry_md_hd_t MD5_CTX;
+
static void MD5_Init(MD5_CTX *ctx)
-{
- gcry_md_open(ctx, GCRY_MD_MD5, 0);
-}
-
+{
+ gcry_md_open(ctx, GCRY_MD_MD5, 0);
+}
+
static void MD5_Update(MD5_CTX *ctx,
const unsigned char *input,
- unsigned int inputLen)
-{
- gcry_md_write(*ctx, input, inputLen);
-}
-
+ unsigned int inputLen)
+{
+ gcry_md_write(*ctx, input, inputLen);
+}
+
static void MD5_Final(unsigned char *digest, MD5_CTX *ctx)
-{
- memcpy(digest, gcry_md_read(*ctx, 0), 16);
- gcry_md_close(*ctx);
-}
-
+{
+ memcpy(digest, gcry_md_read(*ctx, 0), 16);
+ gcry_md_close(*ctx);
+}
+
#elif defined(USE_OPENSSL) && !defined(USE_AMISSL)
-/* When OpenSSL is available we use the MD5-function from OpenSSL */
+/* When OpenSSL is available we use the MD5-function from OpenSSL */
#include <openssl/md5.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
-
+
#elif defined(USE_MBEDTLS)
#error #include <mbedtls/md5.h>
@@ -138,85 +138,85 @@ static void MD5_Final(unsigned char *digest, MD5_CTX *ctx)
#endif
}
-#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \
+#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \
(__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \
defined(__MAC_OS_X_VERSION_MIN_ALLOWED) && \
(__MAC_OS_X_VERSION_MIN_ALLOWED < 101500)) || \
- (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \
- (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000))
-
-/* For Apple operating systems: CommonCrypto has the functions we need.
- These functions are available on Tiger and later, as well as iOS 2.0
- and later. If you're building for an older cat, well, sorry.
-
- Declaring the functions as static like this seems to be a bit more
- reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */
-# include <CommonCrypto/CommonDigest.h>
-# define MD5_CTX CC_MD5_CTX
+ (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \
+ (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000))
+
+/* For Apple operating systems: CommonCrypto has the functions we need.
+ These functions are available on Tiger and later, as well as iOS 2.0
+ and later. If you're building for an older cat, well, sorry.
+
+ Declaring the functions as static like this seems to be a bit more
+ reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */
+# include <CommonCrypto/CommonDigest.h>
+# define MD5_CTX CC_MD5_CTX
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
-
-static void MD5_Init(MD5_CTX *ctx)
-{
- CC_MD5_Init(ctx);
-}
-
-static void MD5_Update(MD5_CTX *ctx,
- const unsigned char *input,
- unsigned int inputLen)
-{
- CC_MD5_Update(ctx, input, inputLen);
-}
-
+
+static void MD5_Init(MD5_CTX *ctx)
+{
+ CC_MD5_Init(ctx);
+}
+
+static void MD5_Update(MD5_CTX *ctx,
+ const unsigned char *input,
+ unsigned int inputLen)
+{
+ CC_MD5_Update(ctx, input, inputLen);
+}
+
static void MD5_Final(unsigned char *digest, MD5_CTX *ctx)
-{
- CC_MD5_Final(digest, ctx);
-}
-
+{
+ CC_MD5_Final(digest, ctx);
+}
+
#elif defined(USE_WIN32_CRYPTO)
-
-#include <wincrypt.h>
+
+#include <wincrypt.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
-
+
struct md5_ctx {
- HCRYPTPROV hCryptProv;
- HCRYPTHASH hHash;
+ HCRYPTPROV hCryptProv;
+ HCRYPTHASH hHash;
};
typedef struct md5_ctx MD5_CTX;
-
-static void MD5_Init(MD5_CTX *ctx)
-{
+
+static void MD5_Init(MD5_CTX *ctx)
+{
if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
- CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash);
- }
-}
-
-static void MD5_Update(MD5_CTX *ctx,
- const unsigned char *input,
- unsigned int inputLen)
-{
- CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
-}
-
+ CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash);
+ }
+}
+
+static void MD5_Update(MD5_CTX *ctx,
+ const unsigned char *input,
+ unsigned int inputLen)
+{
+ CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);
+}
+
static void MD5_Final(unsigned char *digest, MD5_CTX *ctx)
-{
+{
unsigned long length = 0;
- CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0);
- if(length == 16)
- CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0);
- if(ctx->hHash)
- CryptDestroyHash(ctx->hHash);
- if(ctx->hCryptProv)
- CryptReleaseContext(ctx->hCryptProv, 0);
-}
-
-#else
-
-/* When no other crypto library is available we use this code segment */
+ CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0);
+ if(length == 16)
+ CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0);
+ if(ctx->hHash)
+ CryptDestroyHash(ctx->hHash);
+ if(ctx->hCryptProv)
+ CryptReleaseContext(ctx->hCryptProv, 0);
+}
+
+#else
+
+/* When no other crypto library is available we use this code segment */
/*
* This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
@@ -253,17 +253,17 @@ static void MD5_Final(unsigned char *digest, MD5_CTX *ctx)
* It is meant to be fast, but not as fast as possible. Some known
* optimizations are not included to reduce source code size and avoid
* compile-time configuration.
- */
-
+ */
+
#include <string.h>
-
+
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
-
+
/* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned int MD5_u32plus;
-
+
struct md5_ctx {
MD5_u32plus lo, hi;
MD5_u32plus a, b, c, d;
@@ -271,32 +271,32 @@ struct md5_ctx {
MD5_u32plus block[16];
};
typedef struct md5_ctx MD5_CTX;
-
+
static void MD5_Init(MD5_CTX *ctx);
static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size);
static void MD5_Final(unsigned char *result, MD5_CTX *ctx);
-
+
/*
* The basic MD5 functions.
*
* F and G are optimized compared to their RFC 1321 definitions for
* architectures that lack an AND-NOT instruction, just like in Colin Plumb's
* implementation.
- */
+ */
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y))))
#define H(x, y, z) (((x) ^ (y)) ^ (z))
#define H2(x, y, z) ((x) ^ ((y) ^ (z)))
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
-
+
/*
* The MD5 transformation for all four rounds.
- */
+ */
#define STEP(f, a, b, c, d, x, t, s) \
(a) += f((b), (c), (d)) + (x) + (t); \
(a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \
(a) += (b);
-
+
/*
* SET reads 4 input bytes in little-endian byte order and stores them
* in a properly aligned word in host byte order.
@@ -304,7 +304,7 @@ static void MD5_Final(unsigned char *result, MD5_CTX *ctx);
* The check for little-endian architectures that tolerate unaligned
* memory accesses is just an optimization. Nothing will break if it
* doesn't work.
- */
+ */
#if defined(__i386__) || defined(__x86_64__) || defined(__vax__)
#define SET(n) \
(*(MD5_u32plus *)(void *)&ptr[(n) * 4])
@@ -320,23 +320,23 @@ static void MD5_Final(unsigned char *result, MD5_CTX *ctx);
#define GET(n) \
(ctx->block[(n)])
#endif
-
+
/*
* This processes one or more 64-byte data blocks, but does NOT update
* the bit counters. There are no alignment requirements.
- */
+ */
static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
-{
+{
const unsigned char *ptr;
MD5_u32plus a, b, c, d;
-
+
ptr = (const unsigned char *)data;
-
+
a = ctx->a;
b = ctx->b;
c = ctx->c;
d = ctx->d;
-
+
do {
MD5_u32plus saved_a, saved_b, saved_c, saved_d;
@@ -344,7 +344,7 @@ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
saved_b = b;
saved_c = c;
saved_d = d;
-
+
/* Round 1 */
STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7)
STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12)
@@ -362,7 +362,7 @@ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
STEP(F, d, a, b, c, SET(13), 0xfd987193, 12)
STEP(F, c, d, a, b, SET(14), 0xa679438e, 17)
STEP(F, b, c, d, a, SET(15), 0x49b40821, 22)
-
+
/* Round 2 */
STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5)
STEP(G, d, a, b, c, GET(6), 0xc040b340, 9)
@@ -380,7 +380,7 @@ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9)
STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14)
STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20)
-
+
/* Round 3 */
STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4)
STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11)
@@ -398,7 +398,7 @@ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11)
STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16)
STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23)
-
+
/* Round 4 */
STEP(I, a, b, c, d, GET(0), 0xf4292244, 6)
STEP(I, d, a, b, c, GET(7), 0x432aff97, 10)
@@ -416,73 +416,73 @@ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10)
STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15)
STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21)
-
+
a += saved_a;
b += saved_b;
c += saved_c;
d += saved_d;
-
+
ptr += 64;
} while(size -= 64);
-
+
ctx->a = a;
ctx->b = b;
ctx->c = c;
ctx->d = d;
-
+
return ptr;
}
-
+
static void MD5_Init(MD5_CTX *ctx)
{
ctx->a = 0x67452301;
ctx->b = 0xefcdab89;
ctx->c = 0x98badcfe;
ctx->d = 0x10325476;
-
+
ctx->lo = 0;
ctx->hi = 0;
-}
-
+}
+
static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size)
-{
+{
MD5_u32plus saved_lo;
unsigned long used;
-
+
saved_lo = ctx->lo;
ctx->lo = (saved_lo + size) & 0x1fffffff;
if(ctx->lo < saved_lo)
ctx->hi++;
ctx->hi += (MD5_u32plus)size >> 29;
-
+
used = saved_lo & 0x3f;
-
+
if(used) {
unsigned long available = 64 - used;
-
+
if(size < available) {
memcpy(&ctx->buffer[used], data, size);
return;
}
-
+
memcpy(&ctx->buffer[used], data, available);
data = (const unsigned char *)data + available;
size -= available;
body(ctx, ctx->buffer, 64);
}
-
+
if(size >= 64) {
data = body(ctx, data, size & ~(unsigned long)0x3f);
size &= 0x3f;
}
-
+
memcpy(ctx->buffer, data, size);
-}
-
+}
+
static void MD5_Final(unsigned char *result, MD5_CTX *ctx)
-{
+{
unsigned long used, available;
-
+
used = ctx->lo & 0x3f;
ctx->buffer[used++] = 0x80;
@@ -494,10 +494,10 @@ static void MD5_Final(unsigned char *result, MD5_CTX *ctx)
body(ctx, ctx->buffer, 64);
used = 0;
available = 64;
- }
-
+ }
+
memset(&ctx->buffer[used], 0, available - 8);
-
+
ctx->lo <<= 3;
ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff);
ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff);
@@ -528,12 +528,12 @@ static void MD5_Final(unsigned char *result, MD5_CTX *ctx)
result[15] = curlx_ultouc(ctx->d >> 24);
memset(ctx, 0, sizeof(*ctx));
-}
-
-#endif /* CRYPTO LIBS */
-
+}
+
+#endif /* CRYPTO LIBS */
+
const struct HMAC_params Curl_HMAC_MD5[] = {
- {
+ {
/* Hash initialization function. */
CURLX_FUNCTION_CAST(HMAC_hinit_func, MD5_Init),
/* Hash update function. */
@@ -546,11 +546,11 @@ const struct HMAC_params Curl_HMAC_MD5[] = {
64,
/* Result size. */
16
- }
-};
-
+ }
+};
+
const struct MD5_params Curl_DIGEST_MD5[] = {
- {
+ {
/* Digest initialization function */
CURLX_FUNCTION_CAST(Curl_MD5_init_func, MD5_Init),
/* Digest update function */
@@ -561,63 +561,63 @@ const struct MD5_params Curl_DIGEST_MD5[] = {
sizeof(MD5_CTX),
/* Result size */
16
- }
-};
-
+ }
+};
+
/*
* @unittest: 1601
*/
void Curl_md5it(unsigned char *outbuffer, const unsigned char *input,
const size_t len)
-{
- MD5_CTX ctx;
+{
+ MD5_CTX ctx;
- MD5_Init(&ctx);
+ MD5_Init(&ctx);
MD5_Update(&ctx, input, curlx_uztoui(len));
- MD5_Final(outbuffer, &ctx);
-}
-
+ MD5_Final(outbuffer, &ctx);
+}
+
struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params)
-{
+{
struct MD5_context *ctxt;
-
- /* Create MD5 context */
+
+ /* Create MD5 context */
ctxt = malloc(sizeof(*ctxt));
-
- if(!ctxt)
- return ctxt;
-
- ctxt->md5_hashctx = malloc(md5params->md5_ctxtsize);
-
- if(!ctxt->md5_hashctx) {
- free(ctxt);
- return NULL;
- }
-
- ctxt->md5_hash = md5params;
-
- (*md5params->md5_init_func)(ctxt->md5_hashctx);
-
- return ctxt;
-}
-
+
+ if(!ctxt)
+ return ctxt;
+
+ ctxt->md5_hashctx = malloc(md5params->md5_ctxtsize);
+
+ if(!ctxt->md5_hashctx) {
+ free(ctxt);
+ return NULL;
+ }
+
+ ctxt->md5_hash = md5params;
+
+ (*md5params->md5_init_func)(ctxt->md5_hashctx);
+
+ return ctxt;
+}
+
CURLcode Curl_MD5_update(struct MD5_context *context,
const unsigned char *data,
unsigned int len)
-{
- (*context->md5_hash->md5_update_func)(context->md5_hashctx, data, len);
-
+{
+ (*context->md5_hash->md5_update_func)(context->md5_hashctx, data, len);
+
return CURLE_OK;
-}
-
+}
+
CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result)
-{
- (*context->md5_hash->md5_final_func)(result, context->md5_hashctx);
-
- free(context->md5_hashctx);
- free(context);
-
+{
+ (*context->md5_hash->md5_final_func)(result, context->md5_hashctx);
+
+ free(context->md5_hashctx);
+ free(context);
+
return CURLE_OK;
-}
-
-#endif /* CURL_DISABLE_CRYPTO_AUTH */
+}
+
+#endif /* CURL_DISABLE_CRYPTO_AUTH */
diff --git a/contrib/libs/curl/lib/memdebug.c b/contrib/libs/curl/lib/memdebug.c
index f2958ed66f..881ee85c32 100644
--- a/contrib/libs/curl/lib/memdebug.c
+++ b/contrib/libs/curl/lib/memdebug.c
@@ -1,308 +1,308 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef CURLDEBUG
-
-#include <curl/curl.h>
-
-#include "urldata.h"
-
-#define MEMDEBUG_NODEFINES /* don't redefine the standard functions */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef CURLDEBUG
+
+#include <curl/curl.h>
+
+#include "urldata.h"
+
+#define MEMDEBUG_NODEFINES /* don't redefine the standard functions */
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-struct memdebug {
- size_t size;
- union {
- curl_off_t o;
- double d;
+#include "curl_memory.h"
+#include "memdebug.h"
+
+struct memdebug {
+ size_t size;
+ union {
+ curl_off_t o;
+ double d;
void *p;
- } mem[1];
- /* I'm hoping this is the thing with the strictest alignment
- * requirements. That also means we waste some space :-( */
-};
-
-/*
- * Note that these debug functions are very simple and they are meant to
- * remain so. For advanced analysis, record a log file and write perl scripts
- * to analyze them!
- *
- * Don't use these with multithreaded test programs!
- */
-
+ } mem[1];
+ /* I'm hoping this is the thing with the strictest alignment
+ * requirements. That also means we waste some space :-( */
+};
+
+/*
+ * Note that these debug functions are very simple and they are meant to
+ * remain so. For advanced analysis, record a log file and write perl scripts
+ * to analyze them!
+ *
+ * Don't use these with multithreaded test programs!
+ */
+
FILE *curl_dbg_logfile = NULL;
-static bool memlimit = FALSE; /* enable memory limit */
-static long memsize = 0; /* set number of mallocs allowed */
-
-/* this sets the log file name */
+static bool memlimit = FALSE; /* enable memory limit */
+static long memsize = 0; /* set number of mallocs allowed */
+
+/* this sets the log file name */
void curl_dbg_memdebug(const char *logname)
-{
+{
if(!curl_dbg_logfile) {
- if(logname && *logname)
+ if(logname && *logname)
curl_dbg_logfile = fopen(logname, FOPEN_WRITETEXT);
- else
+ else
curl_dbg_logfile = stderr;
-#ifdef MEMDEBUG_LOG_SYNC
- /* Flush the log file after every line so the log isn't lost in a crash */
+#ifdef MEMDEBUG_LOG_SYNC
+ /* Flush the log file after every line so the log isn't lost in a crash */
if(curl_dbg_logfile)
setbuf(curl_dbg_logfile, (char *)NULL);
-#endif
- }
-}
-
-/* This function sets the number of malloc() calls that should return
- successfully! */
+#endif
+ }
+}
+
+/* This function sets the number of malloc() calls that should return
+ successfully! */
void curl_dbg_memlimit(long limit)
-{
- if(!memlimit) {
- memlimit = TRUE;
- memsize = limit;
- }
-}
-
-/* returns TRUE if this isn't allowed! */
-static bool countcheck(const char *func, int line, const char *source)
-{
- /* if source is NULL, then the call is made internally and this check
- should not be made */
- if(memlimit && source) {
- if(!memsize) {
- if(source) {
- /* log to file */
+{
+ if(!memlimit) {
+ memlimit = TRUE;
+ memsize = limit;
+ }
+}
+
+/* returns TRUE if this isn't allowed! */
+static bool countcheck(const char *func, int line, const char *source)
+{
+ /* if source is NULL, then the call is made internally and this check
+ should not be made */
+ if(memlimit && source) {
+ if(!memsize) {
+ if(source) {
+ /* log to file */
curl_dbg_log("LIMIT %s:%d %s reached memlimit\n",
source, line, func);
- /* log to stderr also */
- fprintf(stderr, "LIMIT %s:%d %s reached memlimit\n",
- source, line, func);
+ /* log to stderr also */
+ fprintf(stderr, "LIMIT %s:%d %s reached memlimit\n",
+ source, line, func);
fflush(curl_dbg_logfile); /* because it might crash now */
- }
+ }
errno = ENOMEM;
- return TRUE; /* RETURN ERROR! */
- }
- else
- memsize--; /* countdown */
-
-
- }
-
- return FALSE; /* allow this */
-}
-
+ return TRUE; /* RETURN ERROR! */
+ }
+ else
+ memsize--; /* countdown */
+
+
+ }
+
+ return FALSE; /* allow this */
+}
+
void *curl_dbg_malloc(size_t wantedsize, int line, const char *source)
-{
- struct memdebug *mem;
- size_t size;
-
+{
+ struct memdebug *mem;
+ size_t size;
+
DEBUGASSERT(wantedsize != 0);
-
- if(countcheck("malloc", line, source))
- return NULL;
-
- /* alloc at least 64 bytes */
+
+ if(countcheck("malloc", line, source))
+ return NULL;
+
+ /* alloc at least 64 bytes */
size = sizeof(struct memdebug) + wantedsize;
-
- mem = (Curl_cmalloc)(size);
- if(mem) {
- mem->size = wantedsize;
- }
-
- if(source)
+
+ mem = (Curl_cmalloc)(size);
+ if(mem) {
+ mem->size = wantedsize;
+ }
+
+ if(source)
curl_dbg_log("MEM %s:%d malloc(%zu) = %p\n",
source, line, wantedsize,
mem ? (void *)mem->mem : (void *)0);
-
- return (mem ? mem->mem : NULL);
-}
-
+
+ return (mem ? mem->mem : NULL);
+}
+
void *curl_dbg_calloc(size_t wanted_elements, size_t wanted_size,
int line, const char *source)
-{
- struct memdebug *mem;
- size_t size, user_size;
-
+{
+ struct memdebug *mem;
+ size_t size, user_size;
+
DEBUGASSERT(wanted_elements != 0);
DEBUGASSERT(wanted_size != 0);
-
- if(countcheck("calloc", line, source))
- return NULL;
-
- /* alloc at least 64 bytes */
- user_size = wanted_size * wanted_elements;
- size = sizeof(struct memdebug) + user_size;
-
- mem = (Curl_ccalloc)(1, size);
- if(mem)
- mem->size = user_size;
-
- if(source)
+
+ if(countcheck("calloc", line, source))
+ return NULL;
+
+ /* alloc at least 64 bytes */
+ user_size = wanted_size * wanted_elements;
+ size = sizeof(struct memdebug) + user_size;
+
+ mem = (Curl_ccalloc)(1, size);
+ if(mem)
+ mem->size = user_size;
+
+ if(source)
curl_dbg_log("MEM %s:%d calloc(%zu,%zu) = %p\n",
source, line, wanted_elements, wanted_size,
mem ? (void *)mem->mem : (void *)0);
-
- return (mem ? mem->mem : NULL);
-}
-
+
+ return (mem ? mem->mem : NULL);
+}
+
char *curl_dbg_strdup(const char *str, int line, const char *source)
-{
- char *mem;
- size_t len;
-
+{
+ char *mem;
+ size_t len;
+
DEBUGASSERT(str != NULL);
-
- if(countcheck("strdup", line, source))
- return NULL;
-
+
+ if(countcheck("strdup", line, source))
+ return NULL;
+
len = strlen(str) + 1;
-
+
mem = curl_dbg_malloc(len, 0, NULL); /* NULL prevents logging */
- if(mem)
- memcpy(mem, str, len);
-
- if(source)
+ if(mem)
+ memcpy(mem, str, len);
+
+ if(source)
curl_dbg_log("MEM %s:%d strdup(%p) (%zu) = %p\n",
source, line, (const void *)str, len, (const void *)mem);
-
- return mem;
-}
-
-#if defined(WIN32) && defined(UNICODE)
+
+ return mem;
+}
+
+#if defined(WIN32) && defined(UNICODE)
wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line, const char *source)
-{
- wchar_t *mem;
- size_t wsiz, bsiz;
-
+{
+ wchar_t *mem;
+ size_t wsiz, bsiz;
+
DEBUGASSERT(str != NULL);
-
- if(countcheck("wcsdup", line, source))
- return NULL;
-
- wsiz = wcslen(str) + 1;
- bsiz = wsiz * sizeof(wchar_t);
-
+
+ if(countcheck("wcsdup", line, source))
+ return NULL;
+
+ wsiz = wcslen(str) + 1;
+ bsiz = wsiz * sizeof(wchar_t);
+
mem = curl_dbg_malloc(bsiz, 0, NULL); /* NULL prevents logging */
- if(mem)
- memcpy(mem, str, bsiz);
-
- if(source)
+ if(mem)
+ memcpy(mem, str, bsiz);
+
+ if(source)
curl_dbg_log("MEM %s:%d wcsdup(%p) (%zu) = %p\n",
- source, line, (void *)str, bsiz, (void *)mem);
-
- return mem;
-}
-#endif
-
-/* We provide a realloc() that accepts a NULL as pointer, which then
- performs a malloc(). In order to work with ares. */
+ source, line, (void *)str, bsiz, (void *)mem);
+
+ return mem;
+}
+#endif
+
+/* We provide a realloc() that accepts a NULL as pointer, which then
+ performs a malloc(). In order to work with ares. */
void *curl_dbg_realloc(void *ptr, size_t wantedsize,
int line, const char *source)
-{
+{
struct memdebug *mem = NULL;
-
+
size_t size = sizeof(struct memdebug) + wantedsize;
-
+
DEBUGASSERT(wantedsize != 0);
-
- if(countcheck("realloc", line, source))
- return NULL;
-
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:1684)
- /* 1684: conversion from pointer to same-sized integral type */
-#endif
-
- if(ptr)
- mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-
- mem = (Curl_crealloc)(mem, size);
- if(source)
+
+ if(countcheck("realloc", line, source))
+ return NULL;
+
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:1684)
+ /* 1684: conversion from pointer to same-sized integral type */
+#endif
+
+ if(ptr)
+ mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+
+ mem = (Curl_crealloc)(mem, size);
+ if(source)
curl_dbg_log("MEM %s:%d realloc(%p, %zu) = %p\n",
- source, line, (void *)ptr, wantedsize,
- mem ? (void *)mem->mem : (void *)0);
-
- if(mem) {
- mem->size = wantedsize;
- return mem->mem;
- }
-
- return NULL;
-}
-
+ source, line, (void *)ptr, wantedsize,
+ mem ? (void *)mem->mem : (void *)0);
+
+ if(mem) {
+ mem->size = wantedsize;
+ return mem->mem;
+ }
+
+ return NULL;
+}
+
void curl_dbg_free(void *ptr, int line, const char *source)
-{
+{
if(ptr) {
struct memdebug *mem;
-
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:1684)
- /* 1684: conversion from pointer to same-sized integral type */
-#endif
-
+
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:1684)
+ /* 1684: conversion from pointer to same-sized integral type */
+#endif
+
mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+
/* free for real */
(Curl_cfree)(mem);
}
-
+
if(source && ptr)
curl_dbg_log("MEM %s:%d free(%p)\n", source, line, (void *)ptr);
-}
-
+}
+
curl_socket_t curl_dbg_socket(int domain, int type, int protocol,
int line, const char *source)
-{
- const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
+{
+ const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d socket() = %d\n" :
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d socket() = %ld\n" :
"FD %s:%d socket() = %zd\n";
-
+
curl_socket_t sockfd;
-
+
if(countcheck("socket", line, source))
return CURL_SOCKET_BAD;
sockfd = socket(domain, type, protocol);
- if(source && (sockfd != CURL_SOCKET_BAD))
+ if(source && (sockfd != CURL_SOCKET_BAD))
curl_dbg_log(fmt, source, line, sockfd);
-
- return sockfd;
-}
-
+
+ return sockfd;
+}
+
SEND_TYPE_RETV curl_dbg_send(SEND_TYPE_ARG1 sockfd,
SEND_QUAL_ARG2 SEND_TYPE_ARG2 buf,
SEND_TYPE_ARG3 len, SEND_TYPE_ARG4 flags, int line,
@@ -332,79 +332,79 @@ RECV_TYPE_RETV curl_dbg_recv(RECV_TYPE_ARG1 sockfd, RECV_TYPE_ARG2 buf,
return rc;
}
-#ifdef HAVE_SOCKETPAIR
+#ifdef HAVE_SOCKETPAIR
int curl_dbg_socketpair(int domain, int type, int protocol,
curl_socket_t socket_vector[2],
int line, const char *source)
-{
- const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
+{
+ const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d socketpair() = %d %d\n" :
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d socketpair() = %ld %ld\n" :
"FD %s:%d socketpair() = %zd %zd\n";
-
- int res = socketpair(domain, type, protocol, socket_vector);
-
- if(source && (0 == res))
+
+ int res = socketpair(domain, type, protocol, socket_vector);
+
+ if(source && (0 == res))
curl_dbg_log(fmt, source, line, socket_vector[0], socket_vector[1]);
-
- return res;
-}
-#endif
-
+
+ return res;
+}
+#endif
+
curl_socket_t curl_dbg_accept(curl_socket_t s, void *saddr, void *saddrlen,
int line, const char *source)
-{
- const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
+{
+ const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d accept() = %d\n" :
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d accept() = %ld\n" :
"FD %s:%d accept() = %zd\n";
-
- struct sockaddr *addr = (struct sockaddr *)saddr;
- curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen;
-
- curl_socket_t sockfd = accept(s, addr, addrlen);
-
- if(source && (sockfd != CURL_SOCKET_BAD))
+
+ struct sockaddr *addr = (struct sockaddr *)saddr;
+ curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen;
+
+ curl_socket_t sockfd = accept(s, addr, addrlen);
+
+ if(source && (sockfd != CURL_SOCKET_BAD))
curl_dbg_log(fmt, source, line, sockfd);
-
- return sockfd;
-}
-
-/* separate function to allow libcurl to mark a "faked" close */
+
+ return sockfd;
+}
+
+/* separate function to allow libcurl to mark a "faked" close */
void curl_dbg_mark_sclose(curl_socket_t sockfd, int line, const char *source)
-{
- const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
+{
+ const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d sclose(%d)\n":
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d sclose(%ld)\n":
"FD %s:%d sclose(%zd)\n";
-
- if(source)
+
+ if(source)
curl_dbg_log(fmt, source, line, sockfd);
-}
-
-/* this is our own defined way to close sockets on *ALL* platforms */
+}
+
+/* this is our own defined way to close sockets on *ALL* platforms */
int curl_dbg_sclose(curl_socket_t sockfd, int line, const char *source)
-{
+{
int res = sclose(sockfd);
curl_dbg_mark_sclose(sockfd, line, source);
- return res;
-}
-
+ return res;
+}
+
FILE *curl_dbg_fopen(const char *file, const char *mode,
int line, const char *source)
-{
+{
FILE *res = fopen(file, mode);
-
- if(source)
+
+ if(source)
curl_dbg_log("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n",
- source, line, file, mode, (void *)res);
-
- return res;
-}
-
+ source, line, file, mode, (void *)res);
+
+ return res;
+}
+
FILE *curl_dbg_fdopen(int filedes, const char *mode,
int line, const char *source)
{
@@ -416,47 +416,47 @@ FILE *curl_dbg_fdopen(int filedes, const char *mode,
}
int curl_dbg_fclose(FILE *file, int line, const char *source)
-{
- int res;
-
+{
+ int res;
+
DEBUGASSERT(file != NULL);
-
+
if(source)
curl_dbg_log("FILE %s:%d fclose(%p)\n",
source, line, (void *)file);
res = fclose(file);
-
- return res;
-}
-
-#define LOGLINE_BUFSIZE 1024
-
+
+ return res;
+}
+
+#define LOGLINE_BUFSIZE 1024
+
/* this does the writing to the memory tracking log file */
void curl_dbg_log(const char *format, ...)
-{
- char *buf;
- int nchars;
- va_list ap;
-
+{
+ char *buf;
+ int nchars;
+ va_list ap;
+
if(!curl_dbg_logfile)
- return;
-
- buf = (Curl_cmalloc)(LOGLINE_BUFSIZE);
- if(!buf)
- return;
-
- va_start(ap, format);
+ return;
+
+ buf = (Curl_cmalloc)(LOGLINE_BUFSIZE);
+ if(!buf)
+ return;
+
+ va_start(ap, format);
nchars = mvsnprintf(buf, LOGLINE_BUFSIZE, format, ap);
- va_end(ap);
-
- if(nchars > LOGLINE_BUFSIZE - 1)
- nchars = LOGLINE_BUFSIZE - 1;
-
- if(nchars > 0)
+ va_end(ap);
+
+ if(nchars > LOGLINE_BUFSIZE - 1)
+ nchars = LOGLINE_BUFSIZE - 1;
+
+ if(nchars > 0)
fwrite(buf, 1, (size_t)nchars, curl_dbg_logfile);
-
- (Curl_cfree)(buf);
-}
-
-#endif /* CURLDEBUG */
+
+ (Curl_cfree)(buf);
+}
+
+#endif /* CURLDEBUG */
diff --git a/contrib/libs/curl/lib/memdebug.h b/contrib/libs/curl/lib/memdebug.h
index c0f47bd081..8e88cea580 100644
--- a/contrib/libs/curl/lib/memdebug.h
+++ b/contrib/libs/curl/lib/memdebug.h
@@ -1,38 +1,38 @@
-#ifndef HEADER_CURL_MEMDEBUG_H
-#define HEADER_CURL_MEMDEBUG_H
-#ifdef CURLDEBUG
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MEMDEBUG_H
+#define HEADER_CURL_MEMDEBUG_H
+#ifdef CURLDEBUG
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * CAUTION: this header is designed to work when included by the app-side
- * as well as the library. Do not mix with library internals!
- */
-
-#define CURL_MT_LOGFNAME_BUFSIZE 512
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * CAUTION: this header is designed to work when included by the app-side
+ * as well as the library. Do not mix with library internals!
+ */
+
+#define CURL_MT_LOGFNAME_BUFSIZE 512
+
extern FILE *curl_dbg_logfile;
-
-/* memory functions */
+
+/* memory functions */
CURL_EXTERN void *curl_dbg_malloc(size_t size, int line, const char *source);
CURL_EXTERN void *curl_dbg_calloc(size_t elements, size_t size, int line,
const char *source);
@@ -40,16 +40,16 @@ CURL_EXTERN void *curl_dbg_realloc(void *ptr, size_t size, int line,
const char *source);
CURL_EXTERN void curl_dbg_free(void *ptr, int line, const char *source);
CURL_EXTERN char *curl_dbg_strdup(const char *str, int line, const char *src);
-#if defined(WIN32) && defined(UNICODE)
+#if defined(WIN32) && defined(UNICODE)
CURL_EXTERN wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line,
const char *source);
-#endif
-
+#endif
+
CURL_EXTERN void curl_dbg_memdebug(const char *logname);
CURL_EXTERN void curl_dbg_memlimit(long limit);
CURL_EXTERN void curl_dbg_log(const char *format, ...);
-
-/* file descriptor manipulators */
+
+/* file descriptor manipulators */
CURL_EXTERN curl_socket_t curl_dbg_socket(int domain, int type, int protocol,
int line, const char *source);
CURL_EXTERN void curl_dbg_mark_sclose(curl_socket_t sockfd,
@@ -58,12 +58,12 @@ CURL_EXTERN int curl_dbg_sclose(curl_socket_t sockfd,
int line, const char *source);
CURL_EXTERN curl_socket_t curl_dbg_accept(curl_socket_t s, void *a, void *alen,
int line, const char *source);
-#ifdef HAVE_SOCKETPAIR
+#ifdef HAVE_SOCKETPAIR
CURL_EXTERN int curl_dbg_socketpair(int domain, int type, int protocol,
curl_socket_t socket_vector[2],
int line, const char *source);
-#endif
-
+#endif
+
/* send/receive sockets */
CURL_EXTERN SEND_TYPE_RETV curl_dbg_send(SEND_TYPE_ARG1 sockfd,
SEND_QUAL_ARG2 SEND_TYPE_ARG2 buf,
@@ -76,18 +76,18 @@ CURL_EXTERN RECV_TYPE_RETV curl_dbg_recv(RECV_TYPE_ARG1 sockfd,
RECV_TYPE_ARG4 flags, int line,
const char *source);
-/* FILE functions */
+/* FILE functions */
CURL_EXTERN FILE *curl_dbg_fopen(const char *file, const char *mode, int line,
const char *source);
CURL_EXTERN FILE *curl_dbg_fdopen(int filedes, const char *mode,
int line, const char *source);
CURL_EXTERN int curl_dbg_fclose(FILE *file, int line, const char *source);
-
-#ifndef MEMDEBUG_NODEFINES
-
-/* Set this symbol on the command-line, recompile all lib-sources */
-#undef strdup
+
+#ifndef MEMDEBUG_NODEFINES
+
+/* Set this symbol on the command-line, recompile all lib-sources */
+#undef strdup
#define strdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__)
#define malloc(size) curl_dbg_malloc(size, __LINE__, __FILE__)
#define calloc(nbelem,size) curl_dbg_calloc(nbelem, size, __LINE__, __FILE__)
@@ -95,83 +95,83 @@ CURL_EXTERN int curl_dbg_fclose(FILE *file, int line, const char *source);
#define free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__)
#define send(a,b,c,d) curl_dbg_send(a,b,c,d, __LINE__, __FILE__)
#define recv(a,b,c,d) curl_dbg_recv(a,b,c,d, __LINE__, __FILE__)
-
-#ifdef WIN32
-# ifdef UNICODE
-# undef wcsdup
+
+#ifdef WIN32
+# ifdef UNICODE
+# undef wcsdup
# define wcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__)
-# undef _wcsdup
+# undef _wcsdup
# define _wcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__)
-# undef _tcsdup
+# undef _tcsdup
# define _tcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__)
-# else
-# undef _tcsdup
+# else
+# undef _tcsdup
# define _tcsdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__)
-# endif
-#endif
-
+# endif
+#endif
+
#undef socket
-#define socket(domain,type,protocol)\
+#define socket(domain,type,protocol)\
curl_dbg_socket(domain, type, protocol, __LINE__, __FILE__)
-#undef accept /* for those with accept as a macro */
-#define accept(sock,addr,len)\
+#undef accept /* for those with accept as a macro */
+#define accept(sock,addr,len)\
curl_dbg_accept(sock, addr, len, __LINE__, __FILE__)
-#ifdef HAVE_SOCKETPAIR
-#define socketpair(domain,type,protocol,socket_vector)\
+#ifdef HAVE_SOCKETPAIR
+#define socketpair(domain,type,protocol,socket_vector)\
curl_dbg_socketpair(domain, type, protocol, socket_vector, __LINE__, __FILE__)
-#endif
-
-#ifdef HAVE_GETADDRINFO
-#if defined(getaddrinfo) && defined(__osf__)
-/* OSF/1 and Tru64 have getaddrinfo as a define already, so we cannot define
- our macro as for other platforms. Instead, we redefine the new name they
- define getaddrinfo to become! */
-#define ogetaddrinfo(host,serv,hint,res) \
+#endif
+
+#ifdef HAVE_GETADDRINFO
+#if defined(getaddrinfo) && defined(__osf__)
+/* OSF/1 and Tru64 have getaddrinfo as a define already, so we cannot define
+ our macro as for other platforms. Instead, we redefine the new name they
+ define getaddrinfo to become! */
+#define ogetaddrinfo(host,serv,hint,res) \
curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__)
-#else
-#undef getaddrinfo
-#define getaddrinfo(host,serv,hint,res) \
+#else
+#undef getaddrinfo
+#define getaddrinfo(host,serv,hint,res) \
curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__)
-#endif
-#endif /* HAVE_GETADDRINFO */
-
-#ifdef HAVE_FREEADDRINFO
-#undef freeaddrinfo
-#define freeaddrinfo(data) \
+#endif
+#endif /* HAVE_GETADDRINFO */
+
+#ifdef HAVE_FREEADDRINFO
+#undef freeaddrinfo
+#define freeaddrinfo(data) \
curl_dbg_freeaddrinfo(data, __LINE__, __FILE__)
-#endif /* HAVE_FREEADDRINFO */
-
-/* sclose is probably already defined, redefine it! */
-#undef sclose
+#endif /* HAVE_FREEADDRINFO */
+
+/* sclose is probably already defined, redefine it! */
+#undef sclose
#define sclose(sockfd) curl_dbg_sclose(sockfd,__LINE__,__FILE__)
-
+
#define fake_sclose(sockfd) curl_dbg_mark_sclose(sockfd,__LINE__,__FILE__)
-
-#undef fopen
+
+#undef fopen
#define fopen(file,mode) curl_dbg_fopen(file,mode,__LINE__,__FILE__)
-#undef fdopen
+#undef fdopen
#define fdopen(file,mode) curl_dbg_fdopen(file,mode,__LINE__,__FILE__)
#define fclose(file) curl_dbg_fclose(file,__LINE__,__FILE__)
-
-#endif /* MEMDEBUG_NODEFINES */
-
-#endif /* CURLDEBUG */
-
-/*
-** Following section applies even when CURLDEBUG is not defined.
-*/
-
-#ifndef fake_sclose
-#define fake_sclose(x) Curl_nop_stmt
-#endif
-
-/*
- * Curl_safefree defined as a macro to allow MemoryTracking feature
- * to log free() calls at same location where Curl_safefree is used.
- * This macro also assigns NULL to given pointer when free'd.
- */
-
-#define Curl_safefree(ptr) \
+
+#endif /* MEMDEBUG_NODEFINES */
+
+#endif /* CURLDEBUG */
+
+/*
+** Following section applies even when CURLDEBUG is not defined.
+*/
+
+#ifndef fake_sclose
+#define fake_sclose(x) Curl_nop_stmt
+#endif
+
+/*
+ * Curl_safefree defined as a macro to allow MemoryTracking feature
+ * to log free() calls at same location where Curl_safefree is used.
+ * This macro also assigns NULL to given pointer when free'd.
+ */
+
+#define Curl_safefree(ptr) \
do { free((ptr)); (ptr) = NULL;} while(0)
-
-#endif /* HEADER_CURL_MEMDEBUG_H */
+
+#endif /* HEADER_CURL_MEMDEBUG_H */
diff --git a/contrib/libs/curl/lib/mprintf.c b/contrib/libs/curl/lib/mprintf.c
index 53a3027ad9..c681248dee 100644
--- a/contrib/libs/curl/lib/mprintf.c
+++ b/contrib/libs/curl/lib/mprintf.c
@@ -1,66 +1,66 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1999 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- *
- * Purpose:
- * A merge of Bjorn Reese's format() function and Daniel's dsprintf()
- * 1.0. A full blooded printf() clone with full support for <num>$
- * everywhere (parameters, widths and precisions) including variabled
- * sized parameters (like doubles, long longs, long doubles and even
- * void * in 64-bit architectures).
- *
- * Current restrictions:
- * - Max 128 parameters
- * - No 'long double' support.
- *
- * If you ever want truly portable and good *printf() clones, the project that
- * took on from here is named 'Trio' and you find more details on the trio web
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ *
+ * Purpose:
+ * A merge of Bjorn Reese's format() function and Daniel's dsprintf()
+ * 1.0. A full blooded printf() clone with full support for <num>$
+ * everywhere (parameters, widths and precisions) including variabled
+ * sized parameters (like doubles, long longs, long doubles and even
+ * void * in 64-bit architectures).
+ *
+ * Current restrictions:
+ * - Max 128 parameters
+ * - No 'long double' support.
+ *
+ * If you ever want truly portable and good *printf() clones, the project that
+ * took on from here is named 'Trio' and you find more details on the trio web
* page at https://daniel.haxx.se/projects/trio/
- */
-
-#include "curl_setup.h"
+ */
+
+#include "curl_setup.h"
#include "dynbuf.h"
-#include <curl/mprintf.h>
-
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-/*
- * If SIZEOF_SIZE_T has not been defined, default to the size of long.
- */
-
-#ifdef HAVE_LONGLONG
-# define LONG_LONG_TYPE long long
-# define HAVE_LONG_LONG_TYPE
-#else
-# if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
-# define LONG_LONG_TYPE __int64
-# define HAVE_LONG_LONG_TYPE
-# else
-# undef LONG_LONG_TYPE
-# undef HAVE_LONG_LONG_TYPE
-# endif
-#endif
-
-/*
+#include <curl/mprintf.h>
+
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * If SIZEOF_SIZE_T has not been defined, default to the size of long.
+ */
+
+#ifdef HAVE_LONGLONG
+# define LONG_LONG_TYPE long long
+# define HAVE_LONG_LONG_TYPE
+#else
+# if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
+# define LONG_LONG_TYPE __int64
+# define HAVE_LONG_LONG_TYPE
+# else
+# undef LONG_LONG_TYPE
+# undef HAVE_LONG_LONG_TYPE
+# endif
+#endif
+
+/*
* Non-ANSI integer extensions
*/
@@ -74,125 +74,125 @@
#endif
/*
- * Max integer data types that mprintf.c is capable
- */
-
-#ifdef HAVE_LONG_LONG_TYPE
-# define mp_intmax_t LONG_LONG_TYPE
-# define mp_uintmax_t unsigned LONG_LONG_TYPE
-#else
-# define mp_intmax_t long
-# define mp_uintmax_t unsigned long
-#endif
-
+ * Max integer data types that mprintf.c is capable
+ */
+
+#ifdef HAVE_LONG_LONG_TYPE
+# define mp_intmax_t LONG_LONG_TYPE
+# define mp_uintmax_t unsigned LONG_LONG_TYPE
+#else
+# define mp_intmax_t long
+# define mp_uintmax_t unsigned long
+#endif
+
#define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should
fit negative DBL_MAX (317 letters) */
-#define MAX_PARAMETERS 128 /* lame static limit */
-
-#ifdef __AMIGA__
-# undef FORMAT_INT
-#endif
-
-/* Lower-case digits. */
-static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
-
-/* Upper-case digits. */
-static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
+#define MAX_PARAMETERS 128 /* lame static limit */
+
+#ifdef __AMIGA__
+# undef FORMAT_INT
+#endif
+
+/* Lower-case digits. */
+static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
+
+/* Upper-case digits. */
+static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
#define OUTCHAR(x) \
do { \
- if(stream((unsigned char)(x), (FILE *)data) != -1) \
+ if(stream((unsigned char)(x), (FILE *)data) != -1) \
done++; \
else \
return done; /* return immediately on failure */ \
} while(0)
-
-/* Data type to read from the arglist */
+
+/* Data type to read from the arglist */
typedef enum {
- FORMAT_UNKNOWN = 0,
- FORMAT_STRING,
- FORMAT_PTR,
- FORMAT_INT,
- FORMAT_INTPTR,
- FORMAT_LONG,
- FORMAT_LONGLONG,
- FORMAT_DOUBLE,
- FORMAT_LONGDOUBLE,
- FORMAT_WIDTH /* For internal use */
-} FormatType;
-
-/* conversion and display flags */
-enum {
- FLAGS_NEW = 0,
- FLAGS_SPACE = 1<<0,
- FLAGS_SHOWSIGN = 1<<1,
- FLAGS_LEFT = 1<<2,
- FLAGS_ALT = 1<<3,
- FLAGS_SHORT = 1<<4,
- FLAGS_LONG = 1<<5,
- FLAGS_LONGLONG = 1<<6,
- FLAGS_LONGDOUBLE = 1<<7,
- FLAGS_PAD_NIL = 1<<8,
- FLAGS_UNSIGNED = 1<<9,
- FLAGS_OCTAL = 1<<10,
- FLAGS_HEX = 1<<11,
- FLAGS_UPPER = 1<<12,
- FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
- FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
- FLAGS_PREC = 1<<15, /* precision was specified */
- FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
- FLAGS_CHAR = 1<<17, /* %c story */
- FLAGS_FLOATE = 1<<18, /* %e or %E */
- FLAGS_FLOATG = 1<<19 /* %g or %G */
-};
-
+ FORMAT_UNKNOWN = 0,
+ FORMAT_STRING,
+ FORMAT_PTR,
+ FORMAT_INT,
+ FORMAT_INTPTR,
+ FORMAT_LONG,
+ FORMAT_LONGLONG,
+ FORMAT_DOUBLE,
+ FORMAT_LONGDOUBLE,
+ FORMAT_WIDTH /* For internal use */
+} FormatType;
+
+/* conversion and display flags */
+enum {
+ FLAGS_NEW = 0,
+ FLAGS_SPACE = 1<<0,
+ FLAGS_SHOWSIGN = 1<<1,
+ FLAGS_LEFT = 1<<2,
+ FLAGS_ALT = 1<<3,
+ FLAGS_SHORT = 1<<4,
+ FLAGS_LONG = 1<<5,
+ FLAGS_LONGLONG = 1<<6,
+ FLAGS_LONGDOUBLE = 1<<7,
+ FLAGS_PAD_NIL = 1<<8,
+ FLAGS_UNSIGNED = 1<<9,
+ FLAGS_OCTAL = 1<<10,
+ FLAGS_HEX = 1<<11,
+ FLAGS_UPPER = 1<<12,
+ FLAGS_WIDTH = 1<<13, /* '*' or '*<num>$' used */
+ FLAGS_WIDTHPARAM = 1<<14, /* width PARAMETER was specified */
+ FLAGS_PREC = 1<<15, /* precision was specified */
+ FLAGS_PRECPARAM = 1<<16, /* precision PARAMETER was specified */
+ FLAGS_CHAR = 1<<17, /* %c story */
+ FLAGS_FLOATE = 1<<18, /* %e or %E */
+ FLAGS_FLOATG = 1<<19 /* %g or %G */
+};
+
struct va_stack {
- FormatType type;
- int flags;
- long width; /* width OR width parameter number */
- long precision; /* precision OR precision parameter number */
- union {
- char *str;
- void *ptr;
- union {
- mp_intmax_t as_signed;
- mp_uintmax_t as_unsigned;
- } num;
- double dnum;
- } data;
+ FormatType type;
+ int flags;
+ long width; /* width OR width parameter number */
+ long precision; /* precision OR precision parameter number */
+ union {
+ char *str;
+ void *ptr;
+ union {
+ mp_intmax_t as_signed;
+ mp_uintmax_t as_unsigned;
+ } num;
+ double dnum;
+ } data;
};
-
-struct nsprintf {
- char *buffer;
- size_t length;
- size_t max;
-};
-
-struct asprintf {
+
+struct nsprintf {
+ char *buffer;
+ size_t length;
+ size_t max;
+};
+
+struct asprintf {
struct dynbuf *b;
bool fail; /* if an alloc has failed and thus the output is not the complete
data */
-};
-
-static long dprintf_DollarString(char *input, char **end)
-{
+};
+
+static long dprintf_DollarString(char *input, char **end)
+{
int number = 0;
- while(ISDIGIT(*input)) {
+ while(ISDIGIT(*input)) {
if(number < MAX_PARAMETERS) {
number *= 10;
number += *input - '0';
}
- input++;
- }
+ input++;
+ }
if(number <= MAX_PARAMETERS && ('$' == *input)) {
*end = ++input;
- return number;
- }
- return 0;
-}
-
+ return number;
+ }
+ return 0;
+}
+
static bool dprintf_IsQualifierNoDollar(const char *fmt)
-{
+{
#if defined(MP_HAVE_INT_EXTENSIONS)
if(!strncmp(fmt, "I32", 3) || !strncmp(fmt, "I64", 3)) {
return TRUE;
@@ -200,75 +200,75 @@ static bool dprintf_IsQualifierNoDollar(const char *fmt)
#endif
switch(*fmt) {
- case '-': case '+': case ' ': case '#': case '.':
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- case 'h': case 'l': case 'L': case 'z': case 'q':
- case '*': case 'O':
+ case '-': case '+': case ' ': case '#': case '.':
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ case 'h': case 'l': case 'L': case 'z': case 'q':
+ case '*': case 'O':
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
#endif
return TRUE;
- default:
+ default:
return FALSE;
- }
-}
-
-/******************************************************************
- *
- * Pass 1:
- * Create an index with the type of each parameter entry and its
- * value (may vary in size)
- *
+ }
+}
+
+/******************************************************************
+ *
+ * Pass 1:
+ * Create an index with the type of each parameter entry and its
+ * value (may vary in size)
+ *
* Returns zero on success.
*
- ******************************************************************/
-
+ ******************************************************************/
+
static int dprintf_Pass1(const char *format, struct va_stack *vto,
char **endpos, va_list arglist)
-{
- char *fmt = (char *)format;
- int param_num = 0;
- long this_param;
- long width;
- long precision;
- int flags;
+{
+ char *fmt = (char *)format;
+ int param_num = 0;
+ long this_param;
+ long width;
+ long precision;
+ int flags;
long max_param = 0;
- long i;
-
- while(*fmt) {
- if(*fmt++ == '%') {
- if(*fmt == '%') {
- fmt++;
- continue; /* while */
- }
-
- flags = FLAGS_NEW;
-
- /* Handle the positional case (N$) */
-
- param_num++;
-
- this_param = dprintf_DollarString(fmt, &fmt);
- if(0 == this_param)
- /* we got no positional, get the next counter */
- this_param = param_num;
-
- if(this_param > max_param)
- max_param = this_param;
-
- /*
- * The parameter with number 'i' should be used. Next, we need
- * to get SIZE and TYPE of the parameter. Add the information
- * to our array.
- */
-
- width = 0;
- precision = 0;
-
- /* Handle the flags */
-
+ long i;
+
+ while(*fmt) {
+ if(*fmt++ == '%') {
+ if(*fmt == '%') {
+ fmt++;
+ continue; /* while */
+ }
+
+ flags = FLAGS_NEW;
+
+ /* Handle the positional case (N$) */
+
+ param_num++;
+
+ this_param = dprintf_DollarString(fmt, &fmt);
+ if(0 == this_param)
+ /* we got no positional, get the next counter */
+ this_param = param_num;
+
+ if(this_param > max_param)
+ max_param = this_param;
+
+ /*
+ * The parameter with number 'i' should be used. Next, we need
+ * to get SIZE and TYPE of the parameter. Add the information
+ * to our array.
+ */
+
+ width = 0;
+ precision = 0;
+
+ /* Handle the flags */
+
while(dprintf_IsQualifierNoDollar(fmt)) {
#if defined(MP_HAVE_INT_EXTENSIONS)
if(!strncmp(fmt, "I32", 3)) {
@@ -283,44 +283,44 @@ static int dprintf_Pass1(const char *format, struct va_stack *vto,
#endif
switch(*fmt++) {
- case ' ':
- flags |= FLAGS_SPACE;
- break;
- case '+':
- flags |= FLAGS_SHOWSIGN;
- break;
- case '-':
- flags |= FLAGS_LEFT;
- flags &= ~FLAGS_PAD_NIL;
- break;
- case '#':
- flags |= FLAGS_ALT;
- break;
- case '.':
- if('*' == *fmt) {
- /* The precision is picked from a specified parameter */
-
- flags |= FLAGS_PRECPARAM;
- fmt++;
- param_num++;
-
- i = dprintf_DollarString(fmt, &fmt);
- if(i)
- precision = i;
- else
- precision = param_num;
-
- if(precision > max_param)
- max_param = precision;
- }
- else {
- flags |= FLAGS_PREC;
- precision = strtol(fmt, &fmt, 10);
- }
- break;
- case 'h':
- flags |= FLAGS_SHORT;
- break;
+ case ' ':
+ flags |= FLAGS_SPACE;
+ break;
+ case '+':
+ flags |= FLAGS_SHOWSIGN;
+ break;
+ case '-':
+ flags |= FLAGS_LEFT;
+ flags &= ~FLAGS_PAD_NIL;
+ break;
+ case '#':
+ flags |= FLAGS_ALT;
+ break;
+ case '.':
+ if('*' == *fmt) {
+ /* The precision is picked from a specified parameter */
+
+ flags |= FLAGS_PRECPARAM;
+ fmt++;
+ param_num++;
+
+ i = dprintf_DollarString(fmt, &fmt);
+ if(i)
+ precision = i;
+ else
+ precision = param_num;
+
+ if(precision > max_param)
+ max_param = precision;
+ }
+ else {
+ flags |= FLAGS_PREC;
+ precision = strtol(fmt, &fmt, 10);
+ }
+ break;
+ case 'h':
+ flags |= FLAGS_SHORT;
+ break;
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
@@ -330,137 +330,137 @@ static int dprintf_Pass1(const char *format, struct va_stack *vto,
#endif
break;
#endif
- case 'l':
- if(flags & FLAGS_LONG)
- flags |= FLAGS_LONGLONG;
- else
- flags |= FLAGS_LONG;
- break;
- case 'L':
- flags |= FLAGS_LONGDOUBLE;
- break;
- case 'q':
- flags |= FLAGS_LONGLONG;
- break;
- case 'z':
- /* the code below generates a warning if -Wunreachable-code is
- used */
+ case 'l':
+ if(flags & FLAGS_LONG)
+ flags |= FLAGS_LONGLONG;
+ else
+ flags |= FLAGS_LONG;
+ break;
+ case 'L':
+ flags |= FLAGS_LONGDOUBLE;
+ break;
+ case 'q':
+ flags |= FLAGS_LONGLONG;
+ break;
+ case 'z':
+ /* the code below generates a warning if -Wunreachable-code is
+ used */
#if (SIZEOF_SIZE_T > SIZEOF_LONG)
- flags |= FLAGS_LONGLONG;
-#else
- flags |= FLAGS_LONG;
-#endif
- break;
- case 'O':
+ flags |= FLAGS_LONGLONG;
+#else
+ flags |= FLAGS_LONG;
+#endif
+ break;
+ case 'O':
#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
- flags |= FLAGS_LONGLONG;
-#else
- flags |= FLAGS_LONG;
-#endif
- break;
- case '0':
- if(!(flags & FLAGS_LEFT))
- flags |= FLAGS_PAD_NIL;
- /* FALLTHROUGH */
- case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- flags |= FLAGS_WIDTH;
- width = strtol(fmt-1, &fmt, 10);
- break;
- case '*': /* Special case */
- flags |= FLAGS_WIDTHPARAM;
- param_num++;
-
- i = dprintf_DollarString(fmt, &fmt);
- if(i)
- width = i;
- else
- width = param_num;
- if(width > max_param)
+ flags |= FLAGS_LONGLONG;
+#else
+ flags |= FLAGS_LONG;
+#endif
+ break;
+ case '0':
+ if(!(flags & FLAGS_LEFT))
+ flags |= FLAGS_PAD_NIL;
+ /* FALLTHROUGH */
+ case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ flags |= FLAGS_WIDTH;
+ width = strtol(fmt-1, &fmt, 10);
+ break;
+ case '*': /* Special case */
+ flags |= FLAGS_WIDTHPARAM;
+ param_num++;
+
+ i = dprintf_DollarString(fmt, &fmt);
+ if(i)
+ width = i;
+ else
+ width = param_num;
+ if(width > max_param)
max_param = width;
- break;
+ break;
case '\0':
fmt--;
- default:
- break;
- }
- } /* switch */
-
- /* Handle the specifier */
-
- i = this_param - 1;
-
+ default:
+ break;
+ }
+ } /* switch */
+
+ /* Handle the specifier */
+
+ i = this_param - 1;
+
if((i < 0) || (i >= MAX_PARAMETERS))
/* out of allowed range */
return 1;
- switch (*fmt) {
- case 'S':
- flags |= FLAGS_ALT;
- /* FALLTHROUGH */
- case 's':
- vto[i].type = FORMAT_STRING;
- break;
- case 'n':
- vto[i].type = FORMAT_INTPTR;
- break;
- case 'p':
- vto[i].type = FORMAT_PTR;
- break;
- case 'd': case 'i':
- vto[i].type = FORMAT_INT;
- break;
- case 'u':
- vto[i].type = FORMAT_INT;
- flags |= FLAGS_UNSIGNED;
- break;
- case 'o':
- vto[i].type = FORMAT_INT;
- flags |= FLAGS_OCTAL;
- break;
- case 'x':
- vto[i].type = FORMAT_INT;
- flags |= FLAGS_HEX|FLAGS_UNSIGNED;
- break;
- case 'X':
- vto[i].type = FORMAT_INT;
- flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
- break;
- case 'c':
- vto[i].type = FORMAT_INT;
- flags |= FLAGS_CHAR;
- break;
- case 'f':
- vto[i].type = FORMAT_DOUBLE;
- break;
- case 'e':
- vto[i].type = FORMAT_DOUBLE;
- flags |= FLAGS_FLOATE;
- break;
- case 'E':
- vto[i].type = FORMAT_DOUBLE;
- flags |= FLAGS_FLOATE|FLAGS_UPPER;
- break;
- case 'g':
- vto[i].type = FORMAT_DOUBLE;
- flags |= FLAGS_FLOATG;
- break;
- case 'G':
- vto[i].type = FORMAT_DOUBLE;
- flags |= FLAGS_FLOATG|FLAGS_UPPER;
- break;
- default:
- vto[i].type = FORMAT_UNKNOWN;
- break;
- } /* switch */
-
- vto[i].flags = flags;
- vto[i].width = width;
- vto[i].precision = precision;
-
- if(flags & FLAGS_WIDTHPARAM) {
- /* we have the width specified from a parameter, so we make that
- parameter's info setup properly */
+ switch (*fmt) {
+ case 'S':
+ flags |= FLAGS_ALT;
+ /* FALLTHROUGH */
+ case 's':
+ vto[i].type = FORMAT_STRING;
+ break;
+ case 'n':
+ vto[i].type = FORMAT_INTPTR;
+ break;
+ case 'p':
+ vto[i].type = FORMAT_PTR;
+ break;
+ case 'd': case 'i':
+ vto[i].type = FORMAT_INT;
+ break;
+ case 'u':
+ vto[i].type = FORMAT_INT;
+ flags |= FLAGS_UNSIGNED;
+ break;
+ case 'o':
+ vto[i].type = FORMAT_INT;
+ flags |= FLAGS_OCTAL;
+ break;
+ case 'x':
+ vto[i].type = FORMAT_INT;
+ flags |= FLAGS_HEX|FLAGS_UNSIGNED;
+ break;
+ case 'X':
+ vto[i].type = FORMAT_INT;
+ flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
+ break;
+ case 'c':
+ vto[i].type = FORMAT_INT;
+ flags |= FLAGS_CHAR;
+ break;
+ case 'f':
+ vto[i].type = FORMAT_DOUBLE;
+ break;
+ case 'e':
+ vto[i].type = FORMAT_DOUBLE;
+ flags |= FLAGS_FLOATE;
+ break;
+ case 'E':
+ vto[i].type = FORMAT_DOUBLE;
+ flags |= FLAGS_FLOATE|FLAGS_UPPER;
+ break;
+ case 'g':
+ vto[i].type = FORMAT_DOUBLE;
+ flags |= FLAGS_FLOATG;
+ break;
+ case 'G':
+ vto[i].type = FORMAT_DOUBLE;
+ flags |= FLAGS_FLOATG|FLAGS_UPPER;
+ break;
+ default:
+ vto[i].type = FORMAT_UNKNOWN;
+ break;
+ } /* switch */
+
+ vto[i].flags = flags;
+ vto[i].width = width;
+ vto[i].precision = precision;
+
+ if(flags & FLAGS_WIDTHPARAM) {
+ /* we have the width specified from a parameter, so we make that
+ parameter's info setup properly */
long k = width - 1;
if((k < 0) || (k >= MAX_PARAMETERS))
/* out of allowed range */
@@ -471,10 +471,10 @@ static int dprintf_Pass1(const char *format, struct va_stack *vto,
/* can't use width or precision of width! */
vto[k].width = 0;
vto[k].precision = 0;
- }
- if(flags & FLAGS_PRECPARAM) {
- /* we have the precision specified from a parameter, so we make that
- parameter's info setup properly */
+ }
+ if(flags & FLAGS_PRECPARAM) {
+ /* we have the precision specified from a parameter, so we make that
+ parameter's info setup properly */
long k = precision - 1;
if((k < 0) || (k >= MAX_PARAMETERS))
/* out of allowed range */
@@ -485,182 +485,182 @@ static int dprintf_Pass1(const char *format, struct va_stack *vto,
/* can't use width or precision of width! */
vto[k].width = 0;
vto[k].precision = 0;
- }
+ }
*endpos++ = fmt + ((*fmt == '\0') ? 0 : 1); /* end of this sequence */
- }
- }
-
- /* Read the arg list parameters into our data list */
+ }
+ }
+
+ /* Read the arg list parameters into our data list */
for(i = 0; i<max_param; i++) {
/* Width/precision arguments must be read before the main argument
they are attached to */
if(vto[i].flags & FLAGS_WIDTHPARAM) {
vto[vto[i].width].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
- }
+ }
if(vto[i].flags & FLAGS_PRECPARAM) {
vto[vto[i].precision].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
-
+
switch(vto[i].type) {
- case FORMAT_STRING:
- vto[i].data.str = va_arg(arglist, char *);
- break;
-
- case FORMAT_INTPTR:
- case FORMAT_UNKNOWN:
- case FORMAT_PTR:
- vto[i].data.ptr = va_arg(arglist, void *);
- break;
-
- case FORMAT_INT:
-#ifdef HAVE_LONG_LONG_TYPE
- if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
- vto[i].data.num.as_unsigned =
- (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
- else if(vto[i].flags & FLAGS_LONGLONG)
- vto[i].data.num.as_signed =
- (mp_intmax_t)va_arg(arglist, mp_intmax_t);
- else
-#endif
- {
- if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
- vto[i].data.num.as_unsigned =
- (mp_uintmax_t)va_arg(arglist, unsigned long);
- else if(vto[i].flags & FLAGS_LONG)
- vto[i].data.num.as_signed =
- (mp_intmax_t)va_arg(arglist, long);
- else if(vto[i].flags & FLAGS_UNSIGNED)
- vto[i].data.num.as_unsigned =
- (mp_uintmax_t)va_arg(arglist, unsigned int);
- else
- vto[i].data.num.as_signed =
- (mp_intmax_t)va_arg(arglist, int);
- }
- break;
-
- case FORMAT_DOUBLE:
- vto[i].data.dnum = va_arg(arglist, double);
- break;
-
- case FORMAT_WIDTH:
- /* Argument has been read. Silently convert it into an integer
- * for later use
- */
- vto[i].type = FORMAT_INT;
- break;
-
- default:
- break;
- }
- }
-
+ case FORMAT_STRING:
+ vto[i].data.str = va_arg(arglist, char *);
+ break;
+
+ case FORMAT_INTPTR:
+ case FORMAT_UNKNOWN:
+ case FORMAT_PTR:
+ vto[i].data.ptr = va_arg(arglist, void *);
+ break;
+
+ case FORMAT_INT:
+#ifdef HAVE_LONG_LONG_TYPE
+ if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
+ vto[i].data.num.as_unsigned =
+ (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
+ else if(vto[i].flags & FLAGS_LONGLONG)
+ vto[i].data.num.as_signed =
+ (mp_intmax_t)va_arg(arglist, mp_intmax_t);
+ else
+#endif
+ {
+ if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
+ vto[i].data.num.as_unsigned =
+ (mp_uintmax_t)va_arg(arglist, unsigned long);
+ else if(vto[i].flags & FLAGS_LONG)
+ vto[i].data.num.as_signed =
+ (mp_intmax_t)va_arg(arglist, long);
+ else if(vto[i].flags & FLAGS_UNSIGNED)
+ vto[i].data.num.as_unsigned =
+ (mp_uintmax_t)va_arg(arglist, unsigned int);
+ else
+ vto[i].data.num.as_signed =
+ (mp_intmax_t)va_arg(arglist, int);
+ }
+ break;
+
+ case FORMAT_DOUBLE:
+ vto[i].data.dnum = va_arg(arglist, double);
+ break;
+
+ case FORMAT_WIDTH:
+ /* Argument has been read. Silently convert it into an integer
+ * for later use
+ */
+ vto[i].type = FORMAT_INT;
+ break;
+
+ default:
+ break;
+ }
+ }
+
return 0;
-
-}
-
-static int dprintf_formatf(
- void *data, /* untouched by format(), just sent to the stream() function in
- the second argument */
- /* function pointer called for each output character */
- int (*stream)(int, FILE *),
- const char *format, /* %-formatted string */
- va_list ap_save) /* list of parameters */
-{
- /* Base-36 digits for numbers. */
- const char *digits = lower_digits;
-
- /* Pointer into the format string. */
- char *f;
-
- /* Number of characters written. */
- int done = 0;
-
- long param; /* current parameter to read */
+
+}
+
+static int dprintf_formatf(
+ void *data, /* untouched by format(), just sent to the stream() function in
+ the second argument */
+ /* function pointer called for each output character */
+ int (*stream)(int, FILE *),
+ const char *format, /* %-formatted string */
+ va_list ap_save) /* list of parameters */
+{
+ /* Base-36 digits for numbers. */
+ const char *digits = lower_digits;
+
+ /* Pointer into the format string. */
+ char *f;
+
+ /* Number of characters written. */
+ int done = 0;
+
+ long param; /* current parameter to read */
long param_num = 0; /* parameter counter */
-
+
struct va_stack vto[MAX_PARAMETERS];
- char *endpos[MAX_PARAMETERS];
- char **end;
- char work[BUFFSIZE];
+ char *endpos[MAX_PARAMETERS];
+ char **end;
+ char work[BUFFSIZE];
struct va_stack *p;
-
+
/* 'workend' points to the final buffer byte position, but with an extra
byte as margin to avoid the (false?) warning Coverity gives us
otherwise */
char *workend = &work[sizeof(work) - 2];
- /* Do the actual %-code parsing */
+ /* Do the actual %-code parsing */
if(dprintf_Pass1(format, vto, endpos, ap_save))
return -1;
-
- end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
- created for us */
-
- f = (char *)format;
- while(*f != '\0') {
- /* Format spec modifiers. */
- int is_alt;
-
- /* Width of a field. */
- long width;
-
- /* Precision of a field. */
- long prec;
-
- /* Decimal integer is negative. */
- int is_neg;
-
- /* Base of a number to be written. */
+
+ end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
+ created for us */
+
+ f = (char *)format;
+ while(*f != '\0') {
+ /* Format spec modifiers. */
+ int is_alt;
+
+ /* Width of a field. */
+ long width;
+
+ /* Precision of a field. */
+ long prec;
+
+ /* Decimal integer is negative. */
+ int is_neg;
+
+ /* Base of a number to be written. */
unsigned long base;
-
- /* Integral values to be written. */
- mp_uintmax_t num;
-
- /* Used to convert negative in positive. */
- mp_intmax_t signed_num;
-
+
+ /* Integral values to be written. */
+ mp_uintmax_t num;
+
+ /* Used to convert negative in positive. */
+ mp_intmax_t signed_num;
+
char *w;
- if(*f != '%') {
- /* This isn't a format spec, so write everything out until the next one
- OR end of string is reached. */
- do {
- OUTCHAR(*f);
- } while(*++f && ('%' != *f));
- continue;
- }
-
- ++f;
-
- /* Check for "%%". Note that although the ANSI standard lists
- '%' as a conversion specifier, it says "The complete format
- specification shall be `%%'," so we can avoid all the width
- and precision processing. */
- if(*f == '%') {
- ++f;
- OUTCHAR('%');
- continue;
- }
-
- /* If this is a positional parameter, the position must follow immediately
- after the %, thus create a %<num>$ sequence */
+ if(*f != '%') {
+ /* This isn't a format spec, so write everything out until the next one
+ OR end of string is reached. */
+ do {
+ OUTCHAR(*f);
+ } while(*++f && ('%' != *f));
+ continue;
+ }
+
+ ++f;
+
+ /* Check for "%%". Note that although the ANSI standard lists
+ '%' as a conversion specifier, it says "The complete format
+ specification shall be `%%'," so we can avoid all the width
+ and precision processing. */
+ if(*f == '%') {
+ ++f;
+ OUTCHAR('%');
+ continue;
+ }
+
+ /* If this is a positional parameter, the position must follow immediately
+ after the %, thus create a %<num>$ sequence */
param = dprintf_DollarString(f, &f);
-
- if(!param)
- param = param_num;
- else
- --param;
-
- param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
- third %s will pick the 3rd argument */
-
- p = &vto[param];
-
- /* pick up the specified width */
+
+ if(!param)
+ param = param_num;
+ else
+ --param;
+
+ param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
+ third %s will pick the 3rd argument */
+
+ p = &vto[param];
+
+ /* pick up the specified width */
if(p->flags & FLAGS_WIDTHPARAM) {
- width = (long)vto[p->width].data.num.as_signed;
+ width = (long)vto[p->width].data.num.as_signed;
param_num++; /* since the width is extracted from a parameter, we
must skip that to get to the next one properly */
if(width < 0) {
@@ -671,83 +671,83 @@ static int dprintf_formatf(
p->flags &= ~FLAGS_PAD_NIL;
}
}
- else
- width = p->width;
-
- /* pick up the specified precision */
- if(p->flags & FLAGS_PRECPARAM) {
- prec = (long)vto[p->precision].data.num.as_signed;
+ else
+ width = p->width;
+
+ /* pick up the specified precision */
+ if(p->flags & FLAGS_PRECPARAM) {
+ prec = (long)vto[p->precision].data.num.as_signed;
param_num++; /* since the precision is extracted from a parameter, we
- must skip that to get to the next one properly */
+ must skip that to get to the next one properly */
if(prec < 0)
/* "A negative precision is taken as if the precision were
omitted." */
prec = -1;
- }
- else if(p->flags & FLAGS_PREC)
- prec = p->precision;
- else
- prec = -1;
-
- is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
-
+ }
+ else if(p->flags & FLAGS_PREC)
+ prec = p->precision;
+ else
+ prec = -1;
+
+ is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
+
switch(p->type) {
- case FORMAT_INT:
- num = p->data.num.as_unsigned;
- if(p->flags & FLAGS_CHAR) {
- /* Character. */
- if(!(p->flags & FLAGS_LEFT))
- while(--width > 0)
- OUTCHAR(' ');
- OUTCHAR((char) num);
- if(p->flags & FLAGS_LEFT)
- while(--width > 0)
- OUTCHAR(' ');
- break;
- }
- if(p->flags & FLAGS_OCTAL) {
- /* Octal unsigned integer. */
- base = 8;
- goto unsigned_number;
- }
- else if(p->flags & FLAGS_HEX) {
- /* Hexadecimal unsigned integer. */
-
- digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
- base = 16;
- goto unsigned_number;
- }
- else if(p->flags & FLAGS_UNSIGNED) {
- /* Decimal unsigned integer. */
- base = 10;
- goto unsigned_number;
- }
-
- /* Decimal integer. */
- base = 10;
-
- is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
- if(is_neg) {
- /* signed_num might fail to hold absolute negative minimum by 1 */
- signed_num = p->data.num.as_signed + (mp_intmax_t)1;
- signed_num = -signed_num;
- num = (mp_uintmax_t)signed_num;
- num += (mp_uintmax_t)1;
- }
-
- goto number;
-
- unsigned_number:
- /* Unsigned number of base BASE. */
- is_neg = 0;
-
- number:
- /* Number of base BASE. */
-
+ case FORMAT_INT:
+ num = p->data.num.as_unsigned;
+ if(p->flags & FLAGS_CHAR) {
+ /* Character. */
+ if(!(p->flags & FLAGS_LEFT))
+ while(--width > 0)
+ OUTCHAR(' ');
+ OUTCHAR((char) num);
+ if(p->flags & FLAGS_LEFT)
+ while(--width > 0)
+ OUTCHAR(' ');
+ break;
+ }
+ if(p->flags & FLAGS_OCTAL) {
+ /* Octal unsigned integer. */
+ base = 8;
+ goto unsigned_number;
+ }
+ else if(p->flags & FLAGS_HEX) {
+ /* Hexadecimal unsigned integer. */
+
+ digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
+ base = 16;
+ goto unsigned_number;
+ }
+ else if(p->flags & FLAGS_UNSIGNED) {
+ /* Decimal unsigned integer. */
+ base = 10;
+ goto unsigned_number;
+ }
+
+ /* Decimal integer. */
+ base = 10;
+
+ is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
+ if(is_neg) {
+ /* signed_num might fail to hold absolute negative minimum by 1 */
+ signed_num = p->data.num.as_signed + (mp_intmax_t)1;
+ signed_num = -signed_num;
+ num = (mp_uintmax_t)signed_num;
+ num += (mp_uintmax_t)1;
+ }
+
+ goto number;
+
+ unsigned_number:
+ /* Unsigned number of base BASE. */
+ is_neg = 0;
+
+ number:
+ /* Number of base BASE. */
+
/* Supply a default precision if none was given. */
if(prec == -1)
prec = 1;
-
+
/* Put the number in WORK. */
w = workend;
while(num > 0) {
@@ -756,7 +756,7 @@ static int dprintf_formatf(
}
width -= (long)(workend - w);
prec -= (long)(workend - w);
-
+
if(is_alt && base == 8 && prec <= 0) {
*w-- = '0';
--width;
@@ -765,26 +765,26 @@ static int dprintf_formatf(
if(prec > 0) {
width -= prec;
while(prec-- > 0 && w >= work)
- *w-- = '0';
+ *w-- = '0';
}
-
+
if(is_alt && base == 16)
width -= 2;
-
+
if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
--width;
-
+
if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR(' ');
-
+
if(is_neg)
OUTCHAR('-');
else if(p->flags & FLAGS_SHOWSIGN)
OUTCHAR('+');
else if(p->flags & FLAGS_SPACE)
OUTCHAR(' ');
-
+
if(is_alt && base == 16) {
OUTCHAR('0');
if(p->flags & FLAGS_UPPER)
@@ -792,138 +792,138 @@ static int dprintf_formatf(
else
OUTCHAR('x');
}
-
+
if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
- OUTCHAR('0');
-
+ OUTCHAR('0');
+
/* Write the number. */
while(++w <= workend) {
OUTCHAR(*w);
}
-
+
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
- break;
-
- case FORMAT_STRING:
- /* String. */
- {
- static const char null[] = "(nil)";
- const char *str;
- size_t len;
-
- str = (char *) p->data.str;
- if(str == NULL) {
- /* Write null[] if there's space. */
- if(prec == -1 || prec >= (long) sizeof(null) - 1) {
- str = null;
- len = sizeof(null) - 1;
- /* Disable quotes around (nil) */
- p->flags &= (~FLAGS_ALT);
- }
- else {
- str = "";
- len = 0;
- }
- }
+ break;
+
+ case FORMAT_STRING:
+ /* String. */
+ {
+ static const char null[] = "(nil)";
+ const char *str;
+ size_t len;
+
+ str = (char *) p->data.str;
+ if(str == NULL) {
+ /* Write null[] if there's space. */
+ if(prec == -1 || prec >= (long) sizeof(null) - 1) {
+ str = null;
+ len = sizeof(null) - 1;
+ /* Disable quotes around (nil) */
+ p->flags &= (~FLAGS_ALT);
+ }
+ else {
+ str = "";
+ len = 0;
+ }
+ }
else if(prec != -1)
len = (size_t)prec;
- else
- len = strlen(str);
-
+ else
+ len = strlen(str);
+
width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
-
- if(p->flags & FLAGS_ALT)
- OUTCHAR('"');
-
- if(!(p->flags&FLAGS_LEFT))
- while(width-- > 0)
- OUTCHAR(' ');
-
+
+ if(p->flags & FLAGS_ALT)
+ OUTCHAR('"');
+
+ if(!(p->flags&FLAGS_LEFT))
+ while(width-- > 0)
+ OUTCHAR(' ');
+
for(; len && *str; len--)
- OUTCHAR(*str++);
- if(p->flags&FLAGS_LEFT)
- while(width-- > 0)
- OUTCHAR(' ');
-
- if(p->flags & FLAGS_ALT)
- OUTCHAR('"');
- }
- break;
-
- case FORMAT_PTR:
- /* Generic pointer. */
- {
- void *ptr;
- ptr = (void *) p->data.ptr;
- if(ptr != NULL) {
- /* If the pointer is not NULL, write it as a %#x spec. */
- base = 16;
- digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
- is_alt = 1;
- num = (size_t) ptr;
- is_neg = 0;
- goto number;
- }
- else {
- /* Write "(nil)" for a nil pointer. */
- static const char strnil[] = "(nil)";
- const char *point;
-
- width -= (long)(sizeof(strnil) - 1);
- if(p->flags & FLAGS_LEFT)
- while(width-- > 0)
- OUTCHAR(' ');
- for(point = strnil; *point != '\0'; ++point)
- OUTCHAR(*point);
+ OUTCHAR(*str++);
+ if(p->flags&FLAGS_LEFT)
+ while(width-- > 0)
+ OUTCHAR(' ');
+
+ if(p->flags & FLAGS_ALT)
+ OUTCHAR('"');
+ }
+ break;
+
+ case FORMAT_PTR:
+ /* Generic pointer. */
+ {
+ void *ptr;
+ ptr = (void *) p->data.ptr;
+ if(ptr != NULL) {
+ /* If the pointer is not NULL, write it as a %#x spec. */
+ base = 16;
+ digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
+ is_alt = 1;
+ num = (size_t) ptr;
+ is_neg = 0;
+ goto number;
+ }
+ else {
+ /* Write "(nil)" for a nil pointer. */
+ static const char strnil[] = "(nil)";
+ const char *point;
+
+ width -= (long)(sizeof(strnil) - 1);
+ if(p->flags & FLAGS_LEFT)
+ while(width-- > 0)
+ OUTCHAR(' ');
+ for(point = strnil; *point != '\0'; ++point)
+ OUTCHAR(*point);
if(!(p->flags & FLAGS_LEFT))
- while(width-- > 0)
- OUTCHAR(' ');
- }
- }
- break;
-
- case FORMAT_DOUBLE:
- {
- char formatbuf[32]="%";
- char *fptr = &formatbuf[1];
- size_t left = sizeof(formatbuf)-strlen(formatbuf);
- int len;
-
- width = -1;
- if(p->flags & FLAGS_WIDTH)
- width = p->width;
- else if(p->flags & FLAGS_WIDTHPARAM)
- width = (long)vto[p->width].data.num.as_signed;
-
- prec = -1;
- if(p->flags & FLAGS_PREC)
- prec = p->precision;
- else if(p->flags & FLAGS_PRECPARAM)
- prec = (long)vto[p->precision].data.num.as_signed;
-
- if(p->flags & FLAGS_LEFT)
- *fptr++ = '-';
- if(p->flags & FLAGS_SHOWSIGN)
- *fptr++ = '+';
- if(p->flags & FLAGS_SPACE)
- *fptr++ = ' ';
- if(p->flags & FLAGS_ALT)
- *fptr++ = '#';
-
- *fptr = 0;
-
- if(width >= 0) {
+ while(width-- > 0)
+ OUTCHAR(' ');
+ }
+ }
+ break;
+
+ case FORMAT_DOUBLE:
+ {
+ char formatbuf[32]="%";
+ char *fptr = &formatbuf[1];
+ size_t left = sizeof(formatbuf)-strlen(formatbuf);
+ int len;
+
+ width = -1;
+ if(p->flags & FLAGS_WIDTH)
+ width = p->width;
+ else if(p->flags & FLAGS_WIDTHPARAM)
+ width = (long)vto[p->width].data.num.as_signed;
+
+ prec = -1;
+ if(p->flags & FLAGS_PREC)
+ prec = p->precision;
+ else if(p->flags & FLAGS_PRECPARAM)
+ prec = (long)vto[p->precision].data.num.as_signed;
+
+ if(p->flags & FLAGS_LEFT)
+ *fptr++ = '-';
+ if(p->flags & FLAGS_SHOWSIGN)
+ *fptr++ = '+';
+ if(p->flags & FLAGS_SPACE)
+ *fptr++ = ' ';
+ if(p->flags & FLAGS_ALT)
+ *fptr++ = '#';
+
+ *fptr = 0;
+
+ if(width >= 0) {
if(width >= (long)sizeof(work))
width = sizeof(work)-1;
- /* RECURSIVE USAGE */
- len = curl_msnprintf(fptr, left, "%ld", width);
- fptr += len;
- left -= len;
- }
- if(prec >= 0) {
+ /* RECURSIVE USAGE */
+ len = curl_msnprintf(fptr, left, "%ld", width);
+ fptr += len;
+ left -= len;
+ }
+ if(prec >= 0) {
/* for each digit in the integer part, we can have one less
precision */
size_t maxprec = sizeof(work) - 2;
@@ -939,154 +939,154 @@ static int dprintf_formatf(
prec = (long)maxprec-1;
if(prec < 0)
prec = 0;
- /* RECURSIVE USAGE */
- len = curl_msnprintf(fptr, left, ".%ld", prec);
- fptr += len;
- }
- if(p->flags & FLAGS_LONG)
- *fptr++ = 'l';
-
- if(p->flags & FLAGS_FLOATE)
- *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
- else if(p->flags & FLAGS_FLOATG)
- *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
- else
- *fptr++ = 'f';
-
- *fptr = 0; /* and a final zero termination */
-
- /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
- output characters */
- (sprintf)(work, formatbuf, p->data.dnum);
+ /* RECURSIVE USAGE */
+ len = curl_msnprintf(fptr, left, ".%ld", prec);
+ fptr += len;
+ }
+ if(p->flags & FLAGS_LONG)
+ *fptr++ = 'l';
+
+ if(p->flags & FLAGS_FLOATE)
+ *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
+ else if(p->flags & FLAGS_FLOATG)
+ *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
+ else
+ *fptr++ = 'f';
+
+ *fptr = 0; /* and a final zero termination */
+
+ /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
+ output characters */
+ (sprintf)(work, formatbuf, p->data.dnum);
DEBUGASSERT(strlen(work) <= sizeof(work));
for(fptr = work; *fptr; fptr++)
- OUTCHAR(*fptr);
- }
- break;
-
- case FORMAT_INTPTR:
- /* Answer the count of characters written. */
-#ifdef HAVE_LONG_LONG_TYPE
- if(p->flags & FLAGS_LONGLONG)
- *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
- else
-#endif
- if(p->flags & FLAGS_LONG)
- *(long *) p->data.ptr = (long)done;
- else if(!(p->flags & FLAGS_SHORT))
- *(int *) p->data.ptr = (int)done;
- else
- *(short *) p->data.ptr = (short)done;
- break;
-
- default:
- break;
- }
- f = *end++; /* goto end of %-code */
-
- }
- return done;
-}
-
-/* fputc() look-alike */
-static int addbyter(int output, FILE *data)
-{
+ OUTCHAR(*fptr);
+ }
+ break;
+
+ case FORMAT_INTPTR:
+ /* Answer the count of characters written. */
+#ifdef HAVE_LONG_LONG_TYPE
+ if(p->flags & FLAGS_LONGLONG)
+ *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
+ else
+#endif
+ if(p->flags & FLAGS_LONG)
+ *(long *) p->data.ptr = (long)done;
+ else if(!(p->flags & FLAGS_SHORT))
+ *(int *) p->data.ptr = (int)done;
+ else
+ *(short *) p->data.ptr = (short)done;
+ break;
+
+ default:
+ break;
+ }
+ f = *end++; /* goto end of %-code */
+
+ }
+ return done;
+}
+
+/* fputc() look-alike */
+static int addbyter(int output, FILE *data)
+{
struct nsprintf *infop = (struct nsprintf *)data;
- unsigned char outc = (unsigned char)output;
-
- if(infop->length < infop->max) {
- /* only do this if we haven't reached max length yet */
- infop->buffer[0] = outc; /* store */
- infop->buffer++; /* increase pointer */
- infop->length++; /* we are now one byte larger */
- return outc; /* fputc() returns like this on success */
- }
- return -1;
-}
-
-int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
- va_list ap_save)
-{
- int retcode;
- struct nsprintf info;
-
- info.buffer = buffer;
- info.length = 0;
- info.max = maxlength;
-
- retcode = dprintf_formatf(&info, addbyter, format, ap_save);
+ unsigned char outc = (unsigned char)output;
+
+ if(infop->length < infop->max) {
+ /* only do this if we haven't reached max length yet */
+ infop->buffer[0] = outc; /* store */
+ infop->buffer++; /* increase pointer */
+ infop->length++; /* we are now one byte larger */
+ return outc; /* fputc() returns like this on success */
+ }
+ return -1;
+}
+
+int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
+ va_list ap_save)
+{
+ int retcode;
+ struct nsprintf info;
+
+ info.buffer = buffer;
+ info.length = 0;
+ info.max = maxlength;
+
+ retcode = dprintf_formatf(&info, addbyter, format, ap_save);
if((retcode != -1) && info.max) {
- /* we terminate this with a zero byte */
- if(info.max == info.length)
- /* we're at maximum, scrap the last letter */
- info.buffer[-1] = 0;
- else
- info.buffer[0] = 0;
- }
- return retcode;
-}
-
-int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
-{
- int retcode;
- va_list ap_save; /* argument pointer */
- va_start(ap_save, format);
- retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
- va_end(ap_save);
- return retcode;
-}
-
-/* fputc() look-alike */
-static int alloc_addbyter(int output, FILE *data)
-{
+ /* we terminate this with a zero byte */
+ if(info.max == info.length)
+ /* we're at maximum, scrap the last letter */
+ info.buffer[-1] = 0;
+ else
+ info.buffer[0] = 0;
+ }
+ return retcode;
+}
+
+int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
+{
+ int retcode;
+ va_list ap_save; /* argument pointer */
+ va_start(ap_save, format);
+ retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
+ va_end(ap_save);
+ return retcode;
+}
+
+/* fputc() look-alike */
+static int alloc_addbyter(int output, FILE *data)
+{
struct asprintf *infop = (struct asprintf *)data;
- unsigned char outc = (unsigned char)output;
-
+ unsigned char outc = (unsigned char)output;
+
if(Curl_dyn_addn(infop->b, &outc, 1)) {
infop->fail = 1;
return -1; /* fail */
- }
- return outc; /* fputc() returns like this on success */
-}
-
+ }
+ return outc; /* fputc() returns like this on success */
+}
+
extern int Curl_dyn_vprintf(struct dynbuf *dyn,
const char *format, va_list ap_save);
/* appends the formatted string, returns 0 on success, 1 on error */
int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save)
-{
- int retcode;
- struct asprintf info;
+{
+ int retcode;
+ struct asprintf info;
info.b = dyn;
- info.fail = 0;
-
- retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
- if((-1 == retcode) || info.fail) {
+ info.fail = 0;
+
+ retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
+ if((-1 == retcode) || info.fail) {
Curl_dyn_free(info.b);
return 1;
- }
+ }
return 0;
-}
-
-char *curl_mvaprintf(const char *format, va_list ap_save)
-{
- int retcode;
- struct asprintf info;
+}
+
+char *curl_mvaprintf(const char *format, va_list ap_save)
+{
+ int retcode;
+ struct asprintf info;
struct dynbuf dyn;
info.b = &dyn;
Curl_dyn_init(info.b, DYN_APRINTF);
- info.fail = 0;
-
- retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
- if((-1 == retcode) || info.fail) {
+ info.fail = 0;
+
+ retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
+ if((-1 == retcode) || info.fail) {
Curl_dyn_free(info.b);
- return NULL;
- }
+ return NULL;
+ }
if(Curl_dyn_len(info.b))
return Curl_dyn_ptr(info.b);
return strdup("");
-}
-
+}
+
char *curl_maprintf(const char *format, ...)
{
va_list ap_save;
@@ -1097,61 +1097,61 @@ char *curl_maprintf(const char *format, ...)
return s;
}
-static int storebuffer(int output, FILE *data)
-{
- char **buffer = (char **)data;
- unsigned char outc = (unsigned char)output;
- **buffer = outc;
- (*buffer)++;
- return outc; /* act like fputc() ! */
-}
-
-int curl_msprintf(char *buffer, const char *format, ...)
-{
- va_list ap_save; /* argument pointer */
- int retcode;
- va_start(ap_save, format);
- retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
- va_end(ap_save);
+static int storebuffer(int output, FILE *data)
+{
+ char **buffer = (char **)data;
+ unsigned char outc = (unsigned char)output;
+ **buffer = outc;
+ (*buffer)++;
+ return outc; /* act like fputc() ! */
+}
+
+int curl_msprintf(char *buffer, const char *format, ...)
+{
+ va_list ap_save; /* argument pointer */
+ int retcode;
+ va_start(ap_save, format);
+ retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
+ va_end(ap_save);
*buffer = 0; /* we terminate this with a zero byte */
- return retcode;
-}
-
-int curl_mprintf(const char *format, ...)
-{
- int retcode;
- va_list ap_save; /* argument pointer */
- va_start(ap_save, format);
-
- retcode = dprintf_formatf(stdout, fputc, format, ap_save);
- va_end(ap_save);
- return retcode;
-}
-
-int curl_mfprintf(FILE *whereto, const char *format, ...)
-{
- int retcode;
- va_list ap_save; /* argument pointer */
- va_start(ap_save, format);
- retcode = dprintf_formatf(whereto, fputc, format, ap_save);
- va_end(ap_save);
- return retcode;
-}
-
-int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
-{
- int retcode;
- retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
+ return retcode;
+}
+
+int curl_mprintf(const char *format, ...)
+{
+ int retcode;
+ va_list ap_save; /* argument pointer */
+ va_start(ap_save, format);
+
+ retcode = dprintf_formatf(stdout, fputc, format, ap_save);
+ va_end(ap_save);
+ return retcode;
+}
+
+int curl_mfprintf(FILE *whereto, const char *format, ...)
+{
+ int retcode;
+ va_list ap_save; /* argument pointer */
+ va_start(ap_save, format);
+ retcode = dprintf_formatf(whereto, fputc, format, ap_save);
+ va_end(ap_save);
+ return retcode;
+}
+
+int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
+{
+ int retcode;
+ retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
*buffer = 0; /* we terminate this with a zero byte */
- return retcode;
-}
-
-int curl_mvprintf(const char *format, va_list ap_save)
-{
- return dprintf_formatf(stdout, fputc, format, ap_save);
-}
-
-int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
-{
- return dprintf_formatf(whereto, fputc, format, ap_save);
-}
+ return retcode;
+}
+
+int curl_mvprintf(const char *format, va_list ap_save)
+{
+ return dprintf_formatf(stdout, fputc, format, ap_save);
+}
+
+int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
+{
+ return dprintf_formatf(whereto, fputc, format, ap_save);
+}
diff --git a/contrib/libs/curl/lib/multi.c b/contrib/libs/curl/lib/multi.c
index 9075cd6c49..f1c9e4dbfb 100644
--- a/contrib/libs/curl/lib/multi.c
+++ b/contrib/libs/curl/lib/multi.c
@@ -1,46 +1,46 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "transfer.h"
-#include "url.h"
-#include "connect.h"
-#include "progress.h"
-#include "easyif.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "transfer.h"
+#include "url.h"
+#include "connect.h"
+#include "progress.h"
+#include "easyif.h"
#include "share.h"
#include "psl.h"
-#include "multiif.h"
-#include "sendf.h"
-#include "timeval.h"
-#include "http.h"
-#include "select.h"
-#include "warnless.h"
-#include "speedcheck.h"
-#include "conncache.h"
-#include "multihandle.h"
+#include "multiif.h"
+#include "sendf.h"
+#include "timeval.h"
+#include "http.h"
+#include "select.h"
+#include "warnless.h"
+#include "speedcheck.h"
+#include "conncache.h"
+#include "multihandle.h"
#include "sigpipe.h"
#include "vtls/vtls.h"
#include "connect.h"
@@ -50,61 +50,61 @@
#include "socks.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
- CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
- to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
- CURL handle takes 45-50 K memory, therefore this 3K are not significant.
-*/
-#ifndef CURL_SOCKET_HASH_TABLE_SIZE
-#define CURL_SOCKET_HASH_TABLE_SIZE 911
-#endif
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/*
+ CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
+ to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
+ CURL handle takes 45-50 K memory, therefore this 3K are not significant.
+*/
+#ifndef CURL_SOCKET_HASH_TABLE_SIZE
+#define CURL_SOCKET_HASH_TABLE_SIZE 911
+#endif
+
#ifndef CURL_CONNECTION_HASH_SIZE
-#define CURL_CONNECTION_HASH_SIZE 97
+#define CURL_CONNECTION_HASH_SIZE 97
#endif
-
-#define CURL_MULTI_HANDLE 0x000bab1e
-
-#define GOOD_MULTI_HANDLE(x) \
+
+#define CURL_MULTI_HANDLE 0x000bab1e
+
+#define GOOD_MULTI_HANDLE(x) \
((x) && (x)->type == CURL_MULTI_HANDLE)
-
+
static CURLMcode singlesocket(struct Curl_multi *multi,
struct Curl_easy *data);
static CURLMcode add_next_timeout(struct curltime now,
- struct Curl_multi *multi,
+ struct Curl_multi *multi,
struct Curl_easy *d);
-static CURLMcode multi_timeout(struct Curl_multi *multi,
- long *timeout_ms);
+static CURLMcode multi_timeout(struct Curl_multi *multi,
+ long *timeout_ms);
static void process_pending_handles(struct Curl_multi *multi);
-
-#ifdef DEBUGBUILD
-static const char * const statename[]={
- "INIT",
- "CONNECT_PEND",
- "CONNECT",
- "WAITRESOLVE",
- "WAITCONNECT",
- "WAITPROXYCONNECT",
+
+#ifdef DEBUGBUILD
+static const char * const statename[]={
+ "INIT",
+ "CONNECT_PEND",
+ "CONNECT",
+ "WAITRESOLVE",
+ "WAITCONNECT",
+ "WAITPROXYCONNECT",
"SENDPROTOCONNECT",
- "PROTOCONNECT",
- "DO",
- "DOING",
- "DO_MORE",
- "DO_DONE",
- "PERFORM",
- "TOOFAST",
- "DONE",
- "COMPLETED",
- "MSGSENT",
-};
-#endif
-
+ "PROTOCONNECT",
+ "DO",
+ "DOING",
+ "DO_MORE",
+ "DO_DONE",
+ "PERFORM",
+ "TOOFAST",
+ "DONE",
+ "COMPLETED",
+ "MSGSENT",
+};
+#endif
+
/* function pointer called once when switching TO a state */
typedef void (*init_multistate_func)(struct Curl_easy *data);
-
+
static void Curl_init_completed(struct Curl_easy *data)
{
/* this is a completed transfer */
@@ -115,14 +115,14 @@ static void Curl_init_completed(struct Curl_easy *data)
Curl_expire_clear(data); /* stop all timers */
}
-/* always use this function to change state, to make debugging easier */
+/* always use this function to change state, to make debugging easier */
static void mstate(struct Curl_easy *data, CURLMstate state
-#ifdef DEBUGBUILD
- , int lineno
-#endif
-)
-{
- CURLMstate oldstate = data->mstate;
+#ifdef DEBUGBUILD
+ , int lineno
+#endif
+)
+{
+ CURLMstate oldstate = data->mstate;
static const init_multistate_func finit[CURLM_STATE_LAST] = {
NULL, /* INIT */
NULL, /* CONNECT_PEND */
@@ -142,67 +142,67 @@ static void mstate(struct Curl_easy *data, CURLMstate state
Curl_init_completed, /* COMPLETED */
NULL /* MSGSENT */
};
-
+
#if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) lineno;
#endif
- if(oldstate == state)
- /* don't bother when the new state is the same as the old state */
- return;
-
- data->mstate = state;
-
+ if(oldstate == state)
+ /* don't bother when the new state is the same as the old state */
+ return;
+
+ data->mstate = state;
+
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
- if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
- data->mstate < CURLM_STATE_COMPLETED) {
+ if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
+ data->mstate < CURLM_STATE_COMPLETED) {
long connection_id = -5000;
if(data->conn)
connection_id = data->conn->connection_id;
-
- infof(data,
+
+ infof(data,
"STATE: %s => %s handle %p; line %d (connection #%ld)\n",
- statename[oldstate], statename[data->mstate],
- (void *)data, lineno, connection_id);
- }
-#endif
+ statename[oldstate], statename[data->mstate],
+ (void *)data, lineno, connection_id);
+ }
+#endif
if(state == CURLM_STATE_COMPLETED) {
- /* changing to COMPLETED means there's one less easy handle 'alive' */
+ /* changing to COMPLETED means there's one less easy handle 'alive' */
DEBUGASSERT(data->multi->num_alive > 0);
- data->multi->num_alive--;
+ data->multi->num_alive--;
}
/* if this state has an init-function, run it */
if(finit[state])
finit[state](data);
-}
-
-#ifndef DEBUGBUILD
-#define multistate(x,y) mstate(x,y)
-#else
-#define multistate(x,y) mstate(x,y, __LINE__)
-#endif
-
-/*
+}
+
+#ifndef DEBUGBUILD
+#define multistate(x,y) mstate(x,y)
+#else
+#define multistate(x,y) mstate(x,y, __LINE__)
+#endif
+
+/*
* We add one of these structs to the sockhash for each socket
- */
-
-struct Curl_sh_entry {
+ */
+
+struct Curl_sh_entry {
struct Curl_hash transfers; /* hash of transfers using this socket */
unsigned int action; /* what combined action READ/WRITE this socket waits
for */
- void *socketp; /* settable by users with curl_multi_assign() */
+ void *socketp; /* settable by users with curl_multi_assign() */
unsigned int users; /* number of transfers using this */
unsigned int readers; /* this many transfers want to read */
unsigned int writers; /* this many transfers want to write */
-};
-/* bits for 'action' having no bits means this socket is not expecting any
- action */
-#define SH_READ 1
-#define SH_WRITE 2
-
+};
+/* bits for 'action' having no bits means this socket is not expecting any
+ action */
+#define SH_READ 1
+#define SH_WRITE 2
+
/* look up a given socket in the socket hash, skip invalid sockets */
static struct Curl_sh_entry *sh_getentry(struct Curl_hash *sh,
curl_socket_t s)
@@ -237,138 +237,138 @@ static void trhash_dtor(void *nada)
}
-/* make sure this socket is present in the hash for this handle */
+/* make sure this socket is present in the hash for this handle */
static struct Curl_sh_entry *sh_addentry(struct Curl_hash *sh,
curl_socket_t s)
-{
+{
struct Curl_sh_entry *there = sh_getentry(sh, s);
- struct Curl_sh_entry *check;
-
+ struct Curl_sh_entry *check;
+
if(there) {
- /* it is present, return fine */
- return there;
+ /* it is present, return fine */
+ return there;
}
-
- /* not present, add it */
- check = calloc(1, sizeof(struct Curl_sh_entry));
- if(!check)
- return NULL; /* major failure */
+
+ /* not present, add it */
+ check = calloc(1, sizeof(struct Curl_sh_entry));
+ if(!check)
+ return NULL; /* major failure */
if(Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash,
trhash_compare, trhash_dtor)) {
free(check);
return NULL;
}
-
- /* make/add new hash entry */
+
+ /* make/add new hash entry */
if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
Curl_hash_destroy(&check->transfers);
- free(check);
- return NULL; /* major failure */
- }
-
- return check; /* things are good in sockhash land */
-}
-
-
-/* delete the given socket + handle from the hash */
+ free(check);
+ return NULL; /* major failure */
+ }
+
+ return check; /* things are good in sockhash land */
+}
+
+
+/* delete the given socket + handle from the hash */
static void sh_delentry(struct Curl_sh_entry *entry,
struct Curl_hash *sh, curl_socket_t s)
-{
+{
Curl_hash_destroy(&entry->transfers);
/* We remove the hash entry. This will end up in a call to
sh_freeentry(). */
Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
-}
-
-/*
- * free a sockhash entry
- */
-static void sh_freeentry(void *freethis)
-{
- struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
-
+}
+
+/*
+ * free a sockhash entry
+ */
+static void sh_freeentry(void *freethis)
+{
+ struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
+
free(p);
-}
-
-static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
-{
- (void) k1_len; (void) k2_len;
-
+}
+
+static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
+{
+ (void) k1_len; (void) k2_len;
+
return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2));
-}
-
-static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
-{
+}
+
+static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
+{
curl_socket_t fd = *((curl_socket_t *) key);
- (void) key_length;
-
+ (void) key_length;
+
return (fd % slots_num);
-}
-
-/*
- * sh_init() creates a new socket hash and returns the handle for it.
- *
- * Quote from README.multi_socket:
- *
- * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
- * is somewhat of a bottle neck. Its current implementation may be a bit too
- * limiting. It simply has a fixed-size array, and on each entry in the array
- * it has a linked list with entries. So the hash only checks which list to
- * scan through. The code I had used so for used a list with merely 7 slots
- * (as that is what the DNS hash uses) but with 7000 connections that would
- * make an average of 1000 nodes in each list to run through. I upped that to
- * 97 slots (I believe a prime is suitable) and noticed a significant speed
- * increase. I need to reconsider the hash implementation or use a rather
- * large default value like this. At 9000 connections I was still below 10us
- * per call."
- *
- */
+}
+
+/*
+ * sh_init() creates a new socket hash and returns the handle for it.
+ *
+ * Quote from README.multi_socket:
+ *
+ * "Some tests at 7000 and 9000 connections showed that the socket hash lookup
+ * is somewhat of a bottle neck. Its current implementation may be a bit too
+ * limiting. It simply has a fixed-size array, and on each entry in the array
+ * it has a linked list with entries. So the hash only checks which list to
+ * scan through. The code I had used so for used a list with merely 7 slots
+ * (as that is what the DNS hash uses) but with 7000 connections that would
+ * make an average of 1000 nodes in each list to run through. I upped that to
+ * 97 slots (I believe a prime is suitable) and noticed a significant speed
+ * increase. I need to reconsider the hash implementation or use a rather
+ * large default value like this. At 9000 connections I was still below 10us
+ * per call."
+ *
+ */
static int sh_init(struct Curl_hash *hash, int hashsize)
-{
+{
return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare,
sh_freeentry);
-}
-
-/*
- * multi_addmsg()
- *
- * Called when a transfer is completed. Adds the given msg pointer to
- * the list kept in the multi handle.
- */
-static CURLMcode multi_addmsg(struct Curl_multi *multi,
- struct Curl_message *msg)
-{
+}
+
+/*
+ * multi_addmsg()
+ *
+ * Called when a transfer is completed. Adds the given msg pointer to
+ * the list kept in the multi handle.
+ */
+static CURLMcode multi_addmsg(struct Curl_multi *multi,
+ struct Curl_message *msg)
+{
Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg,
&msg->list);
- return CURLM_OK;
-}
-
-struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
- int chashsize) /* connection hash */
-{
- struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
-
- if(!multi)
- return NULL;
-
- multi->type = CURL_MULTI_HANDLE;
-
+ return CURLM_OK;
+}
+
+struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
+ int chashsize) /* connection hash */
+{
+ struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
+
+ if(!multi)
+ return NULL;
+
+ multi->type = CURL_MULTI_HANDLE;
+
if(Curl_mk_dnscache(&multi->hostcache))
- goto error;
-
+ goto error;
+
if(sh_init(&multi->sockhash, hashsize))
- goto error;
-
+ goto error;
+
if(Curl_conncache_init(&multi->conn_cache, chashsize))
- goto error;
-
+ goto error;
+
Curl_llist_init(&multi->msglist, NULL);
Curl_llist_init(&multi->pending, NULL);
-
+
multi->multiplexing = TRUE;
-
+
/* -1 means it not set by user, use the default value */
multi->maxconnects = -1;
multi->max_concurrent_streams = 100;
@@ -389,74 +389,74 @@ struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
#endif
return multi;
-
- error:
-
+
+ error:
+
Curl_hash_destroy(&multi->sockhash);
Curl_hash_destroy(&multi->hostcache);
Curl_conncache_destroy(&multi->conn_cache);
Curl_llist_destroy(&multi->msglist, NULL);
Curl_llist_destroy(&multi->pending, NULL);
-
- free(multi);
- return NULL;
-}
-
+
+ free(multi);
+ return NULL;
+}
+
struct Curl_multi *curl_multi_init(void)
-{
- return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
- CURL_CONNECTION_HASH_SIZE);
-}
-
+{
+ return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
+ CURL_CONNECTION_HASH_SIZE);
+}
+
CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
struct Curl_easy *data)
-{
- /* First, make some basic checks that the CURLM handle is a good handle */
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
- /* Verify that we got a somewhat good easy handle too */
+{
+ /* First, make some basic checks that the CURLM handle is a good handle */
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
+ /* Verify that we got a somewhat good easy handle too */
if(!GOOD_EASY_HANDLE(data))
- return CURLM_BAD_EASY_HANDLE;
-
- /* Prevent users from adding same easy handle more than once and prevent
- adding to more than one multi stack */
- if(data->multi)
- return CURLM_ADDED_ALREADY;
-
+ return CURLM_BAD_EASY_HANDLE;
+
+ /* Prevent users from adding same easy handle more than once and prevent
+ adding to more than one multi stack */
+ if(data->multi)
+ return CURLM_ADDED_ALREADY;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
-
+
/* Initialize timeout list for this handle */
Curl_llist_init(&data->state.timeoutlist, NULL);
- /*
- * No failure allowed in this function beyond this point. And no
- * modification of easy nor multi handle allowed before this except for
- * potential multi's connection cache growing which won't be undone in this
- * function no matter what.
- */
+ /*
+ * No failure allowed in this function beyond this point. And no
+ * modification of easy nor multi handle allowed before this except for
+ * potential multi's connection cache growing which won't be undone in this
+ * function no matter what.
+ */
if(data->set.errorbuffer)
data->set.errorbuffer[0] = 0;
-
- /* set the easy handle */
- multistate(data, CURLM_STATE_INIT);
-
- /* for multi interface connections, we share DNS cache automatically if the
- easy handle's one is currently not set. */
+
+ /* set the easy handle */
+ multistate(data, CURLM_STATE_INIT);
+
+ /* for multi interface connections, we share DNS cache automatically if the
+ easy handle's one is currently not set. */
if(!data->dns.hostcache ||
- (data->dns.hostcachetype == HCACHE_NONE)) {
+ (data->dns.hostcachetype == HCACHE_NONE)) {
data->dns.hostcache = &multi->hostcache;
- data->dns.hostcachetype = HCACHE_MULTI;
- }
-
+ data->dns.hostcachetype = HCACHE_MULTI;
+ }
+
/* Point to the shared or multi handle connection cache */
if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT)))
data->state.conn_cache = &data->share->conn_cache;
else
data->state.conn_cache = &multi->conn_cache;
data->state.lastconnect_id = -1;
-
+
#ifdef USE_LIBPSL
/* Do the same for PSL. */
if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL)))
@@ -466,48 +466,48 @@ CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
#endif
/* We add the new entry last in the list. */
- data->next = NULL; /* end of the line */
- if(multi->easyp) {
+ data->next = NULL; /* end of the line */
+ if(multi->easyp) {
struct Curl_easy *last = multi->easylp;
- last->next = data;
- data->prev = last;
- multi->easylp = data; /* the new last node */
- }
- else {
+ last->next = data;
+ data->prev = last;
+ multi->easylp = data; /* the new last node */
+ }
+ else {
/* first node, make prev NULL! */
- data->prev = NULL;
- multi->easylp = multi->easyp = data; /* both first and last */
- }
-
+ data->prev = NULL;
+ multi->easylp = multi->easyp = data; /* both first and last */
+ }
+
/* make the Curl_easy refer back to this multi handle */
data->multi = multi;
-
- /* Set the timeout for this handle to expire really soon so that it will
- be taken care of even when this handle is added in the midst of operation
- when only the curl_multi_socket() API is used. During that flow, only
- sockets that time-out or have actions will be dealt with. Since this
- handle has no action yet, we make sure it times out to get things to
- happen. */
+
+ /* Set the timeout for this handle to expire really soon so that it will
+ be taken care of even when this handle is added in the midst of operation
+ when only the curl_multi_socket() API is used. During that flow, only
+ sockets that time-out or have actions will be dealt with. Since this
+ handle has no action yet, we make sure it times out to get things to
+ happen. */
Curl_expire(data, 0, EXPIRE_RUN_NOW);
-
- /* increase the node-counter */
- multi->num_easy++;
-
- /* increase the alive-counter */
- multi->num_alive++;
-
+
+ /* increase the node-counter */
+ multi->num_easy++;
+
+ /* increase the alive-counter */
+ multi->num_alive++;
+
/* A somewhat crude work-around for a little glitch in Curl_update_timer()
that happens if the lastcall time is set to the same time when the handle
is removed as when the next handle is added, as then the check in
Curl_update_timer() that prevents calling the application multiple times
with the same timer info will not trigger and then the new handle's
timeout will not be notified to the app.
-
- The work-around is thus simply to clear the 'lastcall' variable to force
+
+ The work-around is thus simply to clear the 'lastcall' variable to force
Curl_update_timer() to always trigger a callback to the app when a new
easy handle is added */
- memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
-
+ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
+
CONNCACHE_LOCK(data);
/* The closure handle only ever has default timeouts set. To improve the
state somewhat we clone the timeouts from each added handle so that the
@@ -521,34 +521,34 @@ CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
CONNCACHE_UNLOCK(data);
Curl_update_timer(multi);
- return CURLM_OK;
-}
-
-#if 0
-/* Debug-function, used like this:
- *
- * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
- *
- * Enable the hash print function first by editing hash.c
- */
-static void debug_print_sock_hash(void *p)
-{
- struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
-
- fprintf(stderr, " [easy %p/magic %x/socket %d]",
- (void *)sh->data, sh->data->magic, (int)sh->socket);
-}
-#endif
-
+ return CURLM_OK;
+}
+
+#if 0
+/* Debug-function, used like this:
+ *
+ * Curl_hash_print(multi->sockhash, debug_print_sock_hash);
+ *
+ * Enable the hash print function first by editing hash.c
+ */
+static void debug_print_sock_hash(void *p)
+{
+ struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
+
+ fprintf(stderr, " [easy %p/magic %x/socket %d]",
+ (void *)sh->data, sh->data->magic, (int)sh->socket);
+}
+#endif
+
static CURLcode multi_done(struct Curl_easy *data,
CURLcode status, /* an error if this is called
after an error was detected */
bool premature)
-{
+{
CURLcode result;
struct connectdata *conn = data->conn;
unsigned int i;
-
+
DEBUGF(infof(data, "multi_done\n"));
if(data->state.done)
@@ -720,29 +720,29 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
bool easy_owns_conn;
struct Curl_llist_element *e;
- /* First, make some basic checks that the CURLM handle is a good handle */
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
- /* Verify that we got a somewhat good easy handle too */
+ /* First, make some basic checks that the CURLM handle is a good handle */
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
+ /* Verify that we got a somewhat good easy handle too */
if(!GOOD_EASY_HANDLE(data))
- return CURLM_BAD_EASY_HANDLE;
-
- /* Prevent users from trying to remove same easy handle more than once */
- if(!data->multi)
- return CURLM_OK; /* it is already removed so let's say it is fine! */
-
+ return CURLM_BAD_EASY_HANDLE;
+
+ /* Prevent users from trying to remove same easy handle more than once */
+ if(!data->multi)
+ return CURLM_OK; /* it is already removed so let's say it is fine! */
+
/* Prevent users from trying to remove an easy handle from the wrong multi */
if(data->multi != multi)
return CURLM_BAD_EASY_HANDLE;
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
-
+
premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
easy_owns_conn = (data->conn && (data->conn->data == easy)) ?
TRUE : FALSE;
-
+
/* If the 'state' is not INIT or COMPLETED, we might need to do something
nice to put the easy_handle in a good known state when this returns. */
if(premature) {
@@ -750,7 +750,7 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
alive connections when this is removed */
multi->num_alive--;
}
-
+
if(data->conn &&
data->mstate > CURLM_STATE_DO &&
data->mstate < CURLM_STATE_COMPLETED) {
@@ -760,22 +760,22 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
streamclose(data->conn, "Removed with partial response");
easy_owns_conn = TRUE;
}
-
+
if(data->conn) {
-
+
/* we must call multi_done() here (if we still own the connection) so that
we don't leave a half-baked one around */
if(easy_owns_conn) {
-
+
/* multi_done() clears the association between the easy handle and the
connection.
-
+
Note that this ignores the return code simply because there's
nothing really useful to do with it anyway! */
(void)multi_done(data, data->result, premature);
- }
+ }
}
-
+
/* The timer must be shut down before data->multi is set to NULL, else the
timenode will remain in the splay tree after curl_easy_cleanup is
called. Do it after multi_done() in case that sets another time! */
@@ -785,26 +785,26 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
/* the handle was in the pending list waiting for an available connection,
so go ahead and remove it */
Curl_llist_remove(&multi->pending, &data->connect_queue, NULL);
-
+
if(data->dns.hostcachetype == HCACHE_MULTI) {
/* stop using the multi handle's DNS cache, *after* the possible
multi_done() call above */
data->dns.hostcache = NULL;
data->dns.hostcachetype = HCACHE_NONE;
}
-
+
Curl_wildcard_dtor(&data->wildcard);
-
+
/* destroy the timeout list that is held in the easy handle, do this *after*
multi_done() as that may actually call Curl_expire that uses this */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
-
+
/* change state without using multistate(), only to make singlesocket() do
what we want */
data->mstate = CURLM_STATE_COMPLETED;
singlesocket(multi, easy); /* to let the application know what sockets that
vanish with this handle */
-
+
/* Remove the association between the connection and the handle */
Curl_detach_connnection(data);
@@ -813,36 +813,36 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
Curl_conncache_foreach(data, data->state.conn_cache,
data, &close_connect_only);
}
-
+
#ifdef USE_LIBPSL
/* Remove the PSL association. */
if(data->psl == &multi->psl)
data->psl = NULL;
#endif
-
+
/* as this was using a shared connection cache we clear the pointer to that
since we're not part of that multi handle anymore */
data->state.conn_cache = NULL;
data->multi = NULL; /* clear the association to this multi handle */
-
+
/* make sure there's no pending message in the queue sent from this easy
handle */
-
+
for(e = multi->msglist.head; e; e = e->next) {
struct Curl_message *msg = e->ptr;
-
+
if(msg->extmsg.easy_handle == easy) {
Curl_llist_remove(&multi->msglist, e, NULL);
/* there can only be one from this specific handle */
break;
}
- }
+ }
/* make the previous node point to our next */
if(data->prev)
data->prev->next = data->next;
- else
+ else
multi->easyp = data->next; /* point to first node */
/* make our next point to our previous node */
@@ -857,14 +857,14 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
Curl_update_timer(multi);
return CURLM_OK;
-}
-
+}
+
/* Return TRUE if the application asked for multiplexing */
bool Curl_multiplex_wanted(const struct Curl_multi *multi)
-{
+{
return (multi && (multi->multiplexing));
-}
-
+}
+
/*
* Curl_detach_connnection() removes the given transfer from the connection.
*
@@ -872,13 +872,13 @@ bool Curl_multiplex_wanted(const struct Curl_multi *multi)
* occasionally be called with the data->conn pointer already cleared.
*/
void Curl_detach_connnection(struct Curl_easy *data)
-{
+{
struct connectdata *conn = data->conn;
if(conn)
Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL);
data->conn = NULL;
-}
-
+}
+
/*
* Curl_attach_connnection() attaches this transfer to this connection.
*
@@ -894,9 +894,9 @@ void Curl_attach_connnection(struct Curl_easy *data,
&data->conn_queue);
}
-static int waitconnect_getsock(struct connectdata *conn,
+static int waitconnect_getsock(struct connectdata *conn,
curl_socket_t *sock)
-{
+{
int i;
int s = 0;
int rc = 0;
@@ -930,24 +930,24 @@ static int waitconnect_getsock(struct connectdata *conn,
static int waitproxyconnect_getsock(struct connectdata *conn,
curl_socket_t *sock)
{
- sock[0] = conn->sock[FIRSTSOCKET];
-
- /* when we've sent a CONNECT to a proxy, we should rather wait for the
- socket to become readable to be able to get the response headers */
+ sock[0] = conn->sock[FIRSTSOCKET];
+
+ /* when we've sent a CONNECT to a proxy, we should rather wait for the
+ socket to become readable to be able to get the response headers */
if(conn->connect_state)
- return GETSOCK_READSOCK(0);
-
- return GETSOCK_WRITESOCK(0);
-}
-
-static int domore_getsock(struct connectdata *conn,
+ return GETSOCK_READSOCK(0);
+
+ return GETSOCK_WRITESOCK(0);
+}
+
+static int domore_getsock(struct connectdata *conn,
curl_socket_t *socks)
-{
- if(conn && conn->handler->domore_getsock)
+{
+ if(conn && conn->handler->domore_getsock)
return conn->handler->domore_getsock(conn, socks);
- return GETSOCK_BLANK;
-}
-
+ return GETSOCK_BLANK;
+}
+
static int doing_getsock(struct connectdata *conn,
curl_socket_t *socks)
{
@@ -972,101 +972,101 @@ static int protocol_getsock(struct connectdata *conn,
array contains MAX_SOCKSPEREASYHANDLE entries. */
static int multi_getsock(struct Curl_easy *data,
curl_socket_t *socks)
-{
+{
/* The no connection case can happen when this is called from
curl_multi_remove_handle() => singlesocket() => multi_getsock().
- */
+ */
if(!data->conn)
- return 0;
-
- if(data->mstate > CURLM_STATE_CONNECT &&
- data->mstate < CURLM_STATE_COMPLETED) {
- /* Set up ownership correctly */
+ return 0;
+
+ if(data->mstate > CURLM_STATE_CONNECT &&
+ data->mstate < CURLM_STATE_COMPLETED) {
+ /* Set up ownership correctly */
data->conn->data = data;
- }
-
- switch(data->mstate) {
- default:
- return 0;
-
- case CURLM_STATE_WAITRESOLVE:
+ }
+
+ switch(data->mstate) {
+ default:
+ return 0;
+
+ case CURLM_STATE_WAITRESOLVE:
return Curl_resolv_getsock(data->conn, socks);
-
- case CURLM_STATE_PROTOCONNECT:
+
+ case CURLM_STATE_PROTOCONNECT:
case CURLM_STATE_SENDPROTOCONNECT:
return protocol_getsock(data->conn, socks);
-
- case CURLM_STATE_DO:
- case CURLM_STATE_DOING:
+
+ case CURLM_STATE_DO:
+ case CURLM_STATE_DOING:
return doing_getsock(data->conn, socks);
-
- case CURLM_STATE_WAITPROXYCONNECT:
+
+ case CURLM_STATE_WAITPROXYCONNECT:
return waitproxyconnect_getsock(data->conn, socks);
- case CURLM_STATE_WAITCONNECT:
+ case CURLM_STATE_WAITCONNECT:
return waitconnect_getsock(data->conn, socks);
-
- case CURLM_STATE_DO_MORE:
+
+ case CURLM_STATE_DO_MORE:
return domore_getsock(data->conn, socks);
-
- case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
- to waiting for the same as the *PERFORM
- states */
- case CURLM_STATE_PERFORM:
+
+ case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
+ to waiting for the same as the *PERFORM
+ states */
+ case CURLM_STATE_PERFORM:
return Curl_single_getsock(data->conn, socks);
- }
-
-}
-
+ }
+
+}
+
CURLMcode curl_multi_fdset(struct Curl_multi *multi,
- fd_set *read_fd_set, fd_set *write_fd_set,
- fd_set *exc_fd_set, int *max_fd)
-{
- /* Scan through all the easy handles to get the file descriptors set.
- Some easy handles may not have connected to the remote host yet,
- and then we must make sure that is done. */
+ fd_set *read_fd_set, fd_set *write_fd_set,
+ fd_set *exc_fd_set, int *max_fd)
+{
+ /* Scan through all the easy handles to get the file descriptors set.
+ Some easy handles may not have connected to the remote host yet,
+ and then we must make sure that is done. */
struct Curl_easy *data;
int this_max_fd = -1;
- curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
- int i;
- (void)exc_fd_set; /* not used */
-
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
+ curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
+ int i;
+ (void)exc_fd_set; /* not used */
+
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
data = multi->easyp;
- while(data) {
+ while(data) {
int bitmap = multi_getsock(data, sockbunch);
-
+
for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
- curl_socket_t s = CURL_SOCKET_BAD;
-
- if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
- FD_SET(sockbunch[i], read_fd_set);
- s = sockbunch[i];
- }
- if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
- FD_SET(sockbunch[i], write_fd_set);
- s = sockbunch[i];
- }
- if(s == CURL_SOCKET_BAD)
- /* this socket is unused, break out of loop */
- break;
+ curl_socket_t s = CURL_SOCKET_BAD;
+
+ if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
+ FD_SET(sockbunch[i], read_fd_set);
+ s = sockbunch[i];
+ }
+ if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
+ FD_SET(sockbunch[i], write_fd_set);
+ s = sockbunch[i];
+ }
+ if(s == CURL_SOCKET_BAD)
+ /* this socket is unused, break out of loop */
+ break;
if((int)s > this_max_fd)
this_max_fd = (int)s;
- }
-
- data = data->next; /* check next handle */
- }
-
- *max_fd = this_max_fd;
-
- return CURLM_OK;
-}
-
+ }
+
+ data = data->next; /* check next handle */
+ }
+
+ *max_fd = this_max_fd;
+
+ return CURLM_OK;
+}
+
#define NUM_POLLS_ON_STACK 10
static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
@@ -1076,52 +1076,52 @@ static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
int *ret,
bool extrawait, /* when no socket, wait */
bool use_wakeup)
-{
+{
struct Curl_easy *data;
- curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
- int bitmap;
- unsigned int i;
- unsigned int nfds = 0;
- unsigned int curlfds;
- long timeout_internal;
+ curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
+ int bitmap;
+ unsigned int i;
+ unsigned int nfds = 0;
+ unsigned int curlfds;
+ long timeout_internal;
int retcode = 0;
struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK];
struct pollfd *ufds = &a_few_on_stack[0];
bool ufds_malloc = FALSE;
-
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
+
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
-
+
if(timeout_ms < 0)
return CURLM_BAD_FUNCTION_ARGUMENT;
- /* Count up how many fds we have from the multi handle */
+ /* Count up how many fds we have from the multi handle */
data = multi->easyp;
- while(data) {
+ while(data) {
bitmap = multi_getsock(data, sockbunch);
-
+
for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
- curl_socket_t s = CURL_SOCKET_BAD;
-
- if(bitmap & GETSOCK_READSOCK(i)) {
- ++nfds;
- s = sockbunch[i];
- }
- if(bitmap & GETSOCK_WRITESOCK(i)) {
- ++nfds;
- s = sockbunch[i];
- }
- if(s == CURL_SOCKET_BAD) {
- break;
- }
- }
-
- data = data->next; /* check next handle */
- }
-
+ curl_socket_t s = CURL_SOCKET_BAD;
+
+ if(bitmap & GETSOCK_READSOCK(i)) {
+ ++nfds;
+ s = sockbunch[i];
+ }
+ if(bitmap & GETSOCK_WRITESOCK(i)) {
+ ++nfds;
+ s = sockbunch[i];
+ }
+ if(s == CURL_SOCKET_BAD) {
+ break;
+ }
+ }
+
+ data = data->next; /* check next handle */
+ }
+
/* If the internally desired timeout is actually shorter than requested from
the outside, then use the shorter time! But only if the internal timer
is actually larger than -1! */
@@ -1129,9 +1129,9 @@ static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
timeout_ms = (int)timeout_internal;
- curlfds = nfds; /* number of internal file descriptors */
- nfds += extra_nfds; /* add the externally provided ones */
-
+ curlfds = nfds; /* number of internal file descriptors */
+ nfds += extra_nfds; /* add the externally provided ones */
+
#ifdef ENABLE_WAKEUP
if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
++nfds;
@@ -1147,55 +1147,55 @@ static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
if(!ufds)
return CURLM_OUT_OF_MEMORY;
ufds_malloc = TRUE;
- }
- nfds = 0;
-
- /* only do the second loop if we found descriptors in the first stage run
- above */
-
- if(curlfds) {
- /* Add the curl handles to our pollfds first */
+ }
+ nfds = 0;
+
+ /* only do the second loop if we found descriptors in the first stage run
+ above */
+
+ if(curlfds) {
+ /* Add the curl handles to our pollfds first */
data = multi->easyp;
- while(data) {
+ while(data) {
bitmap = multi_getsock(data, sockbunch);
-
+
for(i = 0; i < MAX_SOCKSPEREASYHANDLE; i++) {
- curl_socket_t s = CURL_SOCKET_BAD;
-
- if(bitmap & GETSOCK_READSOCK(i)) {
- ufds[nfds].fd = sockbunch[i];
- ufds[nfds].events = POLLIN;
- ++nfds;
- s = sockbunch[i];
- }
- if(bitmap & GETSOCK_WRITESOCK(i)) {
- ufds[nfds].fd = sockbunch[i];
- ufds[nfds].events = POLLOUT;
- ++nfds;
- s = sockbunch[i];
- }
- if(s == CURL_SOCKET_BAD) {
- break;
- }
- }
-
- data = data->next; /* check next handle */
- }
- }
-
- /* Add external file descriptions from poll-like struct curl_waitfd */
- for(i = 0; i < extra_nfds; i++) {
- ufds[nfds].fd = extra_fds[i].fd;
- ufds[nfds].events = 0;
- if(extra_fds[i].events & CURL_WAIT_POLLIN)
- ufds[nfds].events |= POLLIN;
- if(extra_fds[i].events & CURL_WAIT_POLLPRI)
- ufds[nfds].events |= POLLPRI;
- if(extra_fds[i].events & CURL_WAIT_POLLOUT)
- ufds[nfds].events |= POLLOUT;
- ++nfds;
- }
-
+ curl_socket_t s = CURL_SOCKET_BAD;
+
+ if(bitmap & GETSOCK_READSOCK(i)) {
+ ufds[nfds].fd = sockbunch[i];
+ ufds[nfds].events = POLLIN;
+ ++nfds;
+ s = sockbunch[i];
+ }
+ if(bitmap & GETSOCK_WRITESOCK(i)) {
+ ufds[nfds].fd = sockbunch[i];
+ ufds[nfds].events = POLLOUT;
+ ++nfds;
+ s = sockbunch[i];
+ }
+ if(s == CURL_SOCKET_BAD) {
+ break;
+ }
+ }
+
+ data = data->next; /* check next handle */
+ }
+ }
+
+ /* Add external file descriptions from poll-like struct curl_waitfd */
+ for(i = 0; i < extra_nfds; i++) {
+ ufds[nfds].fd = extra_fds[i].fd;
+ ufds[nfds].events = 0;
+ if(extra_fds[i].events & CURL_WAIT_POLLIN)
+ ufds[nfds].events |= POLLIN;
+ if(extra_fds[i].events & CURL_WAIT_POLLPRI)
+ ufds[nfds].events |= POLLPRI;
+ if(extra_fds[i].events & CURL_WAIT_POLLOUT)
+ ufds[nfds].events |= POLLOUT;
+ ++nfds;
+ }
+
#ifdef ENABLE_WAKEUP
if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
ufds[nfds].fd = multi->wakeup_pair[0];
@@ -1204,26 +1204,26 @@ static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
}
#endif
- if(nfds) {
- /* wait... */
+ if(nfds) {
+ /* wait... */
int pollrc = Curl_poll(ufds, nfds, timeout_ms);
if(pollrc > 0) {
retcode = pollrc;
- /* copy revents results from the poll to the curl_multi_wait poll
- struct, the bit values of the actual underlying poll() implementation
- may not be the same as the ones in the public libcurl API! */
+ /* copy revents results from the poll to the curl_multi_wait poll
+ struct, the bit values of the actual underlying poll() implementation
+ may not be the same as the ones in the public libcurl API! */
for(i = 0; i < extra_nfds; i++) {
- unsigned short mask = 0;
+ unsigned short mask = 0;
unsigned r = ufds[curlfds + i].revents;
-
- if(r & POLLIN)
- mask |= CURL_WAIT_POLLIN;
- if(r & POLLOUT)
- mask |= CURL_WAIT_POLLOUT;
- if(r & POLLPRI)
- mask |= CURL_WAIT_POLLPRI;
+
+ if(r & POLLIN)
+ mask |= CURL_WAIT_POLLIN;
+ if(r & POLLOUT)
+ mask |= CURL_WAIT_POLLOUT;
+ if(r & POLLPRI)
+ mask |= CURL_WAIT_POLLPRI;
extra_fds[i].revents = mask;
- }
+ }
#ifdef ENABLE_WAKEUP
if(use_wakeup && multi->wakeup_pair[0] != CURL_SOCKET_BAD) {
@@ -1249,12 +1249,12 @@ static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
}
}
#endif
- }
- }
-
+ }
+ }
+
if(ufds_malloc)
free(ufds);
- if(ret)
+ if(ret)
*ret = retcode;
if(!extrawait || nfds)
/* if any socket was checked */
@@ -1274,9 +1274,9 @@ static CURLMcode Curl_multi_wait(struct Curl_multi *multi,
}
}
- return CURLM_OK;
-}
-
+ return CURLM_OK;
+}
+
CURLMcode curl_multi_wait(struct Curl_multi *multi,
struct curl_waitfd extra_fds[],
unsigned int extra_nfds,
@@ -1560,32 +1560,32 @@ CURLcode Curl_preconnect(struct Curl_easy *data)
}
-static CURLMcode multi_runsingle(struct Curl_multi *multi,
+static CURLMcode multi_runsingle(struct Curl_multi *multi,
struct curltime *nowp,
struct Curl_easy *data)
-{
- struct Curl_message *msg = NULL;
- bool connected;
- bool async;
+{
+ struct Curl_message *msg = NULL;
+ bool connected;
+ bool async;
bool protocol_connected = FALSE;
- bool dophase_done = FALSE;
- bool done = FALSE;
+ bool dophase_done = FALSE;
+ bool done = FALSE;
CURLMcode rc;
CURLcode result = CURLE_OK;
timediff_t timeout_ms;
timediff_t recv_timeout_ms;
timediff_t send_timeout_ms;
- int control;
-
- if(!GOOD_EASY_HANDLE(data))
- return CURLM_BAD_EASY_HANDLE;
-
- do {
+ int control;
+
+ if(!GOOD_EASY_HANDLE(data))
+ return CURLM_BAD_EASY_HANDLE;
+
+ do {
/* A "stream" here is a logical stream if the protocol can handle that
(HTTP/2), or the full connection for older protocols */
bool stream_error = FALSE;
rc = CURLM_OK;
-
+
if(multi_ischanged(multi, TRUE)) {
DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n"));
process_pending_handles(multi); /* multiplexed */
@@ -1593,30 +1593,30 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
if(data->conn && data->mstate > CURLM_STATE_CONNECT &&
data->mstate < CURLM_STATE_COMPLETED) {
- /* Make sure we set the connection's current owner */
+ /* Make sure we set the connection's current owner */
data->conn->data = data;
}
-
+
if(data->conn &&
- (data->mstate >= CURLM_STATE_CONNECT) &&
- (data->mstate < CURLM_STATE_COMPLETED)) {
- /* we need to wait for the connect state as only then is the start time
- stored, but we must not check already completed handles */
+ (data->mstate >= CURLM_STATE_CONNECT) &&
+ (data->mstate < CURLM_STATE_COMPLETED)) {
+ /* we need to wait for the connect state as only then is the start time
+ stored, but we must not check already completed handles */
timeout_ms = Curl_timeleft(data, nowp,
(data->mstate <= CURLM_STATE_DO)?
- TRUE:FALSE);
-
- if(timeout_ms < 0) {
- /* Handle timed out */
- if(data->mstate == CURLM_STATE_WAITRESOLVE)
+ TRUE:FALSE);
+
+ if(timeout_ms < 0) {
+ /* Handle timed out */
+ if(data->mstate == CURLM_STATE_WAITRESOLVE)
failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T
" milliseconds",
Curl_timediff(*nowp, data->progress.t_startsingle));
- else if(data->mstate == CURLM_STATE_WAITCONNECT)
+ else if(data->mstate == CURLM_STATE_WAITCONNECT)
failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T
" milliseconds",
Curl_timediff(*nowp, data->progress.t_startsingle));
- else {
+ else {
struct SingleRequest *k = &data->req;
if(k->size != -1) {
failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
@@ -1632,8 +1632,8 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
Curl_timediff(*nowp, data->progress.t_startsingle),
k->bytecount);
}
- }
-
+ }
+
/* Force connection closed if the connection has indeed been used */
if(data->mstate > CURLM_STATE_DO) {
streamclose(data->conn, "Disconnected with pending data");
@@ -1643,29 +1643,29 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
(void)multi_done(data, result, TRUE);
/* Skip the statemachine and go directly to error handling section. */
goto statemachine_end;
- }
- }
-
- switch(data->mstate) {
- case CURLM_STATE_INIT:
- /* init this transfer. */
+ }
+ }
+
+ switch(data->mstate) {
+ case CURLM_STATE_INIT:
+ /* init this transfer. */
result = Curl_pretransfer(data);
-
+
if(!result) {
- /* after init, go CONNECT */
- multistate(data, CURLM_STATE_CONNECT);
+ /* after init, go CONNECT */
+ multistate(data, CURLM_STATE_CONNECT);
*nowp = Curl_pgrsTime(data, TIMER_STARTOP);
rc = CURLM_CALL_MULTI_PERFORM;
- }
- break;
-
- case CURLM_STATE_CONNECT_PEND:
- /* We will stay here until there is a connection available. Then
- we try again in the CURLM_STATE_CONNECT state. */
- break;
-
- case CURLM_STATE_CONNECT:
- /* Connect. We want to get a connection identifier filled in. */
+ }
+ break;
+
+ case CURLM_STATE_CONNECT_PEND:
+ /* We will stay here until there is a connection available. Then
+ we try again in the CURLM_STATE_CONNECT state. */
+ break;
+
+ case CURLM_STATE_CONNECT:
+ /* Connect. We want to get a connection identifier filled in. */
/* init this transfer. */
result = Curl_preconnect(data);
if(result)
@@ -1680,27 +1680,27 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
result = Curl_connect(data, &async, &protocol_connected);
if(CURLE_NO_CONNECTION_AVAILABLE == result) {
- /* There was no connection available. We will go to the pending
- state and wait for an available connection. */
- multistate(data, CURLM_STATE_CONNECT_PEND);
+ /* There was no connection available. We will go to the pending
+ state and wait for an available connection. */
+ multistate(data, CURLM_STATE_CONNECT_PEND);
/* add this handle to the list of connect-pending handles */
Curl_llist_insert_next(&multi->pending, multi->pending.tail, data,
&data->connect_queue);
result = CURLE_OK;
- break;
- }
+ break;
+ }
else if(data->state.previouslypending) {
/* this transfer comes from the pending queue so try move another */
infof(data, "Transfer was pending, now try another\n");
process_pending_handles(data->multi);
}
-
+
if(!result) {
if(async)
/* We're now waiting for an asynchronous name lookup */
multistate(data, CURLM_STATE_WAITRESOLVE);
- else {
+ else {
/* after the connect has been sent off, go WAITCONNECT unless the
protocol connect is already done and we can go directly to
WAITDO or DO! */
@@ -1708,25 +1708,25 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
if(protocol_connected)
multistate(data, CURLM_STATE_DO);
- else {
-#ifndef CURL_DISABLE_HTTP
+ else {
+#ifndef CURL_DISABLE_HTTP
if(Curl_connect_ongoing(data->conn))
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
-#endif
+#endif
multistate(data, CURLM_STATE_WAITCONNECT);
- }
- }
- }
- break;
-
- case CURLM_STATE_WAITRESOLVE:
- /* awaiting an asynch name resolve to complete */
- {
- struct Curl_dns_entry *dns = NULL;
+ }
+ }
+ }
+ break;
+
+ case CURLM_STATE_WAITRESOLVE:
+ /* awaiting an asynch name resolve to complete */
+ {
+ struct Curl_dns_entry *dns = NULL;
struct connectdata *conn = data->conn;
const char *hostname;
-
+
DEBUGASSERT(conn);
#ifndef CURL_DISABLE_PROXY
if(conn->bits.httpproxy)
@@ -1738,9 +1738,9 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
else
hostname = conn->host.name;
- /* check if we have the name resolved by now */
+ /* check if we have the name resolved by now */
dns = Curl_fetch_addr(conn, hostname, (int)conn->port);
-
+
if(dns) {
#ifdef CURLRES_ASYNCH
conn->async.dns = dns;
@@ -1753,50 +1753,50 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
if(!dns)
result = Curl_resolv_check(data->conn, &dns);
- /* Update sockets here, because the socket(s) may have been
- closed and the application thus needs to be told, even if it
- is likely that the same socket(s) will again be used further
- down. If the name has not yet been resolved, it is likely
- that new sockets have been opened in an attempt to contact
- another resolver. */
- singlesocket(multi, data);
-
- if(dns) {
- /* Perform the next step in the connection phase, and then move on
- to the WAITCONNECT state */
+ /* Update sockets here, because the socket(s) may have been
+ closed and the application thus needs to be told, even if it
+ is likely that the same socket(s) will again be used further
+ down. If the name has not yet been resolved, it is likely
+ that new sockets have been opened in an attempt to contact
+ another resolver. */
+ singlesocket(multi, data);
+
+ if(dns) {
+ /* Perform the next step in the connection phase, and then move on
+ to the WAITCONNECT state */
result = Curl_once_resolved(data->conn, &protocol_connected);
-
+
if(result)
/* if Curl_once_resolved() returns failure, the connection struct
- is already freed and gone */
+ is already freed and gone */
data->conn = NULL; /* no more connection */
- else {
- /* call again please so that we get the next socket setup */
+ else {
+ /* call again please so that we get the next socket setup */
rc = CURLM_CALL_MULTI_PERFORM;
if(protocol_connected)
multistate(data, CURLM_STATE_DO);
- else {
-#ifndef CURL_DISABLE_HTTP
+ else {
+#ifndef CURL_DISABLE_HTTP
if(Curl_connect_ongoing(data->conn))
- multistate(data, CURLM_STATE_WAITPROXYCONNECT);
- else
-#endif
- multistate(data, CURLM_STATE_WAITCONNECT);
- }
- }
- }
-
+ multistate(data, CURLM_STATE_WAITPROXYCONNECT);
+ else
+#endif
+ multistate(data, CURLM_STATE_WAITCONNECT);
+ }
+ }
+ }
+
if(result) {
- /* failure detected */
+ /* failure detected */
stream_error = TRUE;
- break;
- }
- }
- break;
-
-#ifndef CURL_DISABLE_HTTP
- case CURLM_STATE_WAITPROXYCONNECT:
- /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
+ break;
+ }
+ }
+ break;
+
+#ifndef CURL_DISABLE_HTTP
+ case CURLM_STATE_WAITPROXYCONNECT:
+ /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
DEBUGASSERT(data->conn);
result = Curl_http_connect(data->conn, &protocol_connected);
#ifndef CURL_DISABLE_PROXY
@@ -1805,8 +1805,8 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
/* connect back to proxy again */
result = CURLE_OK;
multi_done(data, CURLE_OK, FALSE);
- multistate(data, CURLM_STATE_CONNECT);
- }
+ multistate(data, CURLM_STATE_CONNECT);
+ }
else
#endif
if(!result) {
@@ -1823,10 +1823,10 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
}
else
stream_error = TRUE;
- break;
-#endif
-
- case CURLM_STATE_WAITCONNECT:
+ break;
+#endif
+
+ case CURLM_STATE_WAITCONNECT:
/* awaiting a completion of an asynch TCP connect */
DEBUGASSERT(data->conn);
result = Curl_is_connected(data->conn, FIRSTSOCKET, &connected);
@@ -1851,16 +1851,16 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
#else
multistate(data, CURLM_STATE_SENDPROTOCONNECT);
#endif
- }
+ }
else if(result) {
- /* failure detected */
+ /* failure detected */
Curl_posttransfer(data);
multi_done(data, result, TRUE);
stream_error = TRUE;
- break;
- }
+ break;
+ }
break;
-
+
case CURLM_STATE_SENDPROTOCONNECT:
result = protocol_connect(data->conn, &protocol_connected);
if(!result && !protocol_connected)
@@ -1870,187 +1870,187 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
/* protocol connect has completed, go WAITDO or DO */
multistate(data, CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
- }
+ }
else {
/* failure detected */
Curl_posttransfer(data);
multi_done(data, result, TRUE);
stream_error = TRUE;
}
- break;
-
- case CURLM_STATE_PROTOCONNECT:
- /* protocol-specific connect phase */
+ break;
+
+ case CURLM_STATE_PROTOCONNECT:
+ /* protocol-specific connect phase */
result = protocol_connecting(data->conn, &protocol_connected);
if(!result && protocol_connected) {
- /* after the connect has completed, go WAITDO or DO */
+ /* after the connect has completed, go WAITDO or DO */
multistate(data, CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
- }
+ }
else if(result) {
- /* failure detected */
- Curl_posttransfer(data);
+ /* failure detected */
+ Curl_posttransfer(data);
multi_done(data, result, TRUE);
stream_error = TRUE;
- }
- break;
-
- case CURLM_STATE_DO:
- if(data->set.connect_only) {
- /* keep connection open for application to use the socket */
+ }
+ break;
+
+ case CURLM_STATE_DO:
+ if(data->set.connect_only) {
+ /* keep connection open for application to use the socket */
connkeep(data->conn, "CONNECT_ONLY");
- multistate(data, CURLM_STATE_DONE);
+ multistate(data, CURLM_STATE_DONE);
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
- }
- else {
- /* Perform the protocol's DO action */
+ }
+ else {
+ /* Perform the protocol's DO action */
result = multi_do(data, &dophase_done);
-
+
/* When multi_do() returns failure, data->conn might be NULL! */
-
+
if(!result) {
- if(!dophase_done) {
+ if(!dophase_done) {
#ifndef CURL_DISABLE_FTP
- /* some steps needed for wildcard matching */
+ /* some steps needed for wildcard matching */
if(data->state.wildcardmatch) {
- struct WildcardData *wc = &data->wildcard;
- if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
- /* skip some states if it is important */
+ struct WildcardData *wc = &data->wildcard;
+ if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
+ /* skip some states if it is important */
multi_done(data, CURLE_OK, FALSE);
- multistate(data, CURLM_STATE_DONE);
+ multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
- break;
- }
- }
+ break;
+ }
+ }
#endif
- /* DO was not completed in one function call, we must continue
- DOING... */
- multistate(data, CURLM_STATE_DOING);
+ /* DO was not completed in one function call, we must continue
+ DOING... */
+ multistate(data, CURLM_STATE_DOING);
rc = CURLM_OK;
- }
-
- /* after DO, go DO_DONE... or DO_MORE */
+ }
+
+ /* after DO, go DO_DONE... or DO_MORE */
else if(data->conn->bits.do_more) {
- /* we're supposed to do more, but we need to sit down, relax
- and wait a little while first */
- multistate(data, CURLM_STATE_DO_MORE);
+ /* we're supposed to do more, but we need to sit down, relax
+ and wait a little while first */
+ multistate(data, CURLM_STATE_DO_MORE);
rc = CURLM_OK;
- }
- else {
- /* we're done with the DO, now DO_DONE */
- multistate(data, CURLM_STATE_DO_DONE);
+ }
+ else {
+ /* we're done with the DO, now DO_DONE */
+ multistate(data, CURLM_STATE_DO_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
- }
- }
+ }
+ }
else if((CURLE_SEND_ERROR == result) &&
data->conn->bits.reuse) {
- /*
- * In this situation, a connection that we were trying to use
- * may have unexpectedly died. If possible, send the connection
- * back to the CONNECT phase so we can try again.
- */
- char *newurl = NULL;
+ /*
+ * In this situation, a connection that we were trying to use
+ * may have unexpectedly died. If possible, send the connection
+ * back to the CONNECT phase so we can try again.
+ */
+ char *newurl = NULL;
followtype follow = FOLLOW_NONE;
- CURLcode drc;
-
+ CURLcode drc;
+
drc = Curl_retry_request(data->conn, &newurl);
- if(drc) {
- /* a failure here pretty much implies an out of memory */
+ if(drc) {
+ /* a failure here pretty much implies an out of memory */
result = drc;
stream_error = TRUE;
- }
-
- Curl_posttransfer(data);
+ }
+
+ Curl_posttransfer(data);
drc = multi_done(data, result, FALSE);
-
- /* When set to retry the connection, we must to go back to
- * the CONNECT state */
+
+ /* When set to retry the connection, we must to go back to
+ * the CONNECT state */
if(newurl) {
if(!drc || (drc == CURLE_SEND_ERROR)) {
- follow = FOLLOW_RETRY;
- drc = Curl_follow(data, newurl, follow);
+ follow = FOLLOW_RETRY;
+ drc = Curl_follow(data, newurl, follow);
if(!drc) {
- multistate(data, CURLM_STATE_CONNECT);
+ multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
result = CURLE_OK;
- }
- else {
- /* Follow failed */
+ }
+ else {
+ /* Follow failed */
result = drc;
- }
- }
- else {
- /* done didn't return OK or SEND_ERROR */
+ }
+ }
+ else {
+ /* done didn't return OK or SEND_ERROR */
result = drc;
- }
- }
- else {
- /* Have error handler disconnect conn if we can't retry */
+ }
+ }
+ else {
+ /* Have error handler disconnect conn if we can't retry */
stream_error = TRUE;
- }
+ }
free(newurl);
- }
- else {
- /* failure detected */
- Curl_posttransfer(data);
+ }
+ else {
+ /* failure detected */
+ Curl_posttransfer(data);
if(data->conn)
multi_done(data, result, FALSE);
stream_error = TRUE;
- }
- }
- break;
-
- case CURLM_STATE_DOING:
- /* we continue DOING until the DO phase is complete */
+ }
+ }
+ break;
+
+ case CURLM_STATE_DOING:
+ /* we continue DOING until the DO phase is complete */
DEBUGASSERT(data->conn);
result = protocol_doing(data->conn, &dophase_done);
if(!result) {
- if(dophase_done) {
- /* after DO, go DO_DONE or DO_MORE */
+ if(dophase_done) {
+ /* after DO, go DO_DONE or DO_MORE */
multistate(data, data->conn->bits.do_more?
- CURLM_STATE_DO_MORE:
- CURLM_STATE_DO_DONE);
+ CURLM_STATE_DO_MORE:
+ CURLM_STATE_DO_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
- } /* dophase_done */
- }
- else {
- /* failure detected */
- Curl_posttransfer(data);
+ } /* dophase_done */
+ }
+ else {
+ /* failure detected */
+ Curl_posttransfer(data);
multi_done(data, result, FALSE);
stream_error = TRUE;
- }
- break;
-
- case CURLM_STATE_DO_MORE:
- /*
- * When we are connected, DO MORE and then go DO_DONE
- */
+ }
+ break;
+
+ case CURLM_STATE_DO_MORE:
+ /*
+ * When we are connected, DO MORE and then go DO_DONE
+ */
DEBUGASSERT(data->conn);
result = multi_do_more(data->conn, &control);
-
+
if(!result) {
- if(control) {
- /* if positive, advance to DO_DONE
- if negative, go back to DOING */
+ if(control) {
+ /* if positive, advance to DO_DONE
+ if negative, go back to DOING */
multistate(data, control == 1?
- CURLM_STATE_DO_DONE:
- CURLM_STATE_DOING);
+ CURLM_STATE_DO_DONE:
+ CURLM_STATE_DOING);
rc = CURLM_CALL_MULTI_PERFORM;
- }
- else
- /* stay in DO_MORE */
+ }
+ else
+ /* stay in DO_MORE */
rc = CURLM_OK;
- }
- else {
- /* failure detected */
- Curl_posttransfer(data);
+ }
+ else {
+ /* failure detected */
+ Curl_posttransfer(data);
multi_done(data, result, FALSE);
stream_error = TRUE;
- }
- break;
-
- case CURLM_STATE_DO_DONE:
+ }
+ break;
+
+ case CURLM_STATE_DO_DONE:
DEBUGASSERT(data->conn);
if(data->conn->bits.multiplex)
/* Check if we can move pending requests to send pipe */
@@ -2071,16 +2071,16 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
multistate(data, CURLM_STATE_DONE);
}
rc = CURLM_CALL_MULTI_PERFORM;
- break;
-
- case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
+ break;
+
+ case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
DEBUGASSERT(data->conn);
- /* if both rates are within spec, resume transfer */
+ /* if both rates are within spec, resume transfer */
if(Curl_pgrsUpdate(data->conn))
result = CURLE_ABORTED_BY_CALLBACK;
- else
+ else
result = Curl_speedcheck(data, *nowp);
-
+
if(!result) {
send_timeout_ms = 0;
if(data->set.max_send_speed > 0)
@@ -2109,15 +2109,15 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
else
Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
}
- break;
-
- case CURLM_STATE_PERFORM:
+ break;
+
+ case CURLM_STATE_PERFORM:
{
- char *newurl = NULL;
- bool retry = FALSE;
+ char *newurl = NULL;
+ bool retry = FALSE;
bool comeback = FALSE;
DEBUGASSERT(data->state.buffer);
- /* check if over send speed */
+ /* check if over send speed */
send_timeout_ms = 0;
if(data->set.max_send_speed > 0)
send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
@@ -2125,8 +2125,8 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
data->set.max_send_speed,
data->progress.ul_limit_start,
*nowp);
-
- /* check if over recv speed */
+
+ /* check if over recv speed */
recv_timeout_ms = 0;
if(data->set.max_recv_speed > 0)
recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
@@ -2134,42 +2134,42 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
data->set.max_recv_speed,
data->progress.dl_limit_start,
*nowp);
-
+
if(send_timeout_ms || recv_timeout_ms) {
Curl_ratelimit(data, *nowp);
- multistate(data, CURLM_STATE_TOOFAST);
+ multistate(data, CURLM_STATE_TOOFAST);
if(send_timeout_ms >= recv_timeout_ms)
Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST);
else
Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST);
- break;
- }
-
- /* read/write data if it is ready to do so */
+ break;
+ }
+
+ /* read/write data if it is ready to do so */
result = Curl_readwrite(data->conn, data, &done, &comeback);
-
+
if(done || (result == CURLE_RECV_ERROR)) {
- /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
- * condition and the server closed the re-used connection exactly when
- * we wanted to use it, so figure out if that is indeed the case.
- */
+ /* If CURLE_RECV_ERROR happens early enough, we assume it was a race
+ * condition and the server closed the re-used connection exactly when
+ * we wanted to use it, so figure out if that is indeed the case.
+ */
CURLcode ret = Curl_retry_request(data->conn, &newurl);
- if(!ret)
- retry = (newurl)?TRUE:FALSE;
+ if(!ret)
+ retry = (newurl)?TRUE:FALSE;
else if(!result)
result = ret;
-
- if(retry) {
- /* if we are to retry, set the result to OK and consider the
- request as done */
+
+ if(retry) {
+ /* if we are to retry, set the result to OK and consider the
+ request as done */
result = CURLE_OK;
- done = TRUE;
- }
- }
+ done = TRUE;
+ }
+ }
else if((CURLE_HTTP2_STREAM == result) &&
Curl_h2_http_1_1_error(data->conn)) {
CURLcode ret = Curl_retry_request(data->conn, &newurl);
-
+
if(!ret) {
infof(data, "Downgrades to HTTP/1.1!\n");
data->set.httpversion = CURL_HTTP_VERSION_1_1;
@@ -2189,72 +2189,72 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
}
if(result) {
- /*
- * The transfer phase returned error, we mark the connection to get
- * closed to prevent being re-used. This is because we can't possibly
- * know if the connection is in a good shape or not now. Unless it is
- * a protocol which uses two "channels" like FTP, as then the error
- * happened in the data connection.
- */
-
+ /*
+ * The transfer phase returned error, we mark the connection to get
+ * closed to prevent being re-used. This is because we can't possibly
+ * know if the connection is in a good shape or not now. Unless it is
+ * a protocol which uses two "channels" like FTP, as then the error
+ * happened in the data connection.
+ */
+
if(!(data->conn->handler->flags & PROTOPT_DUAL) &&
result != CURLE_HTTP2_STREAM)
streamclose(data->conn, "Transfer returned error");
-
- Curl_posttransfer(data);
+
+ Curl_posttransfer(data);
multi_done(data, result, TRUE);
- }
- else if(done) {
+ }
+ else if(done) {
followtype follow = FOLLOW_NONE;
-
- /* call this even if the readwrite function returned error */
- Curl_posttransfer(data);
-
- /* When we follow redirects or is set to retry the connection, we must
- to go back to the CONNECT state */
- if(data->req.newurl || retry) {
- if(!retry) {
- /* if the URL is a follow-location and not just a retried request
- then figure out the URL here */
+
+ /* call this even if the readwrite function returned error */
+ Curl_posttransfer(data);
+
+ /* When we follow redirects or is set to retry the connection, we must
+ to go back to the CONNECT state */
+ if(data->req.newurl || retry) {
+ if(!retry) {
+ /* if the URL is a follow-location and not just a retried request
+ then figure out the URL here */
free(newurl);
- newurl = data->req.newurl;
- data->req.newurl = NULL;
- follow = FOLLOW_REDIR;
- }
- else
- follow = FOLLOW_RETRY;
+ newurl = data->req.newurl;
+ data->req.newurl = NULL;
+ follow = FOLLOW_REDIR;
+ }
+ else
+ follow = FOLLOW_RETRY;
(void)multi_done(data, CURLE_OK, FALSE);
/* multi_done() might return CURLE_GOT_NOTHING */
result = Curl_follow(data, newurl, follow);
if(!result) {
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
- }
+ }
free(newurl);
- }
- else {
- /* after the transfer is done, go DONE */
-
- /* but first check to see if we got a location info even though we're
- not following redirects */
- if(data->req.location) {
+ }
+ else {
+ /* after the transfer is done, go DONE */
+
+ /* but first check to see if we got a location info even though we're
+ not following redirects */
+ if(data->req.location) {
free(newurl);
- newurl = data->req.location;
- data->req.location = NULL;
+ newurl = data->req.location;
+ data->req.location = NULL;
result = Curl_follow(data, newurl, FOLLOW_FAKE);
free(newurl);
if(result) {
stream_error = TRUE;
result = multi_done(data, result, TRUE);
}
- }
-
+ }
+
if(!result) {
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
}
- }
- }
+ }
+ }
else if(comeback) {
/* This avoids CURLM_CALL_MULTI_PERFORM so that a very fast transfer
won't get stuck on this transfer at the expense of other concurrent
@@ -2262,13 +2262,13 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
Curl_expire(data, 0, EXPIRE_RUN_NOW);
rc = CURLM_OK;
}
- break;
+ break;
}
-
- case CURLM_STATE_DONE:
- /* this state is highly transient, so run another loop after this */
+
+ case CURLM_STATE_DONE:
+ /* this state is highly transient, so run another loop after this */
rc = CURLM_CALL_MULTI_PERFORM;
-
+
if(data->conn) {
CURLcode res;
@@ -2276,71 +2276,71 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
/* Check if we can move pending requests to connection */
process_pending_handles(multi); /* multiplexing */
- /* post-transfer command */
+ /* post-transfer command */
res = multi_done(data, result, FALSE);
/* allow a previously set error code take precedence */
if(!result)
result = res;
- /*
+ /*
* If there are other handles on the connection, multi_done won't set
* conn to NULL. In such a case, curl_multi_remove_handle() can
- * access free'd data, if the connection is free'd and the handle
- * removed before we perform the processing in CURLM_STATE_COMPLETED
- */
+ * access free'd data, if the connection is free'd and the handle
+ * removed before we perform the processing in CURLM_STATE_COMPLETED
+ */
Curl_detach_connnection(data);
- }
-
+ }
+
#ifndef CURL_DISABLE_FTP
if(data->state.wildcardmatch) {
- if(data->wildcard.state != CURLWC_DONE) {
- /* if a wildcard is set and we are not ending -> lets start again
- with CURLM_STATE_INIT */
- multistate(data, CURLM_STATE_INIT);
- break;
- }
- }
+ if(data->wildcard.state != CURLWC_DONE) {
+ /* if a wildcard is set and we are not ending -> lets start again
+ with CURLM_STATE_INIT */
+ multistate(data, CURLM_STATE_INIT);
+ break;
+ }
+ }
#endif
- /* after we have DONE what we're supposed to do, go COMPLETED, and
+ /* after we have DONE what we're supposed to do, go COMPLETED, and
it doesn't matter what the multi_done() returned! */
- multistate(data, CURLM_STATE_COMPLETED);
- break;
-
- case CURLM_STATE_COMPLETED:
- break;
-
- case CURLM_STATE_MSGSENT:
+ multistate(data, CURLM_STATE_COMPLETED);
+ break;
+
+ case CURLM_STATE_COMPLETED:
+ break;
+
+ case CURLM_STATE_MSGSENT:
data->result = result;
- return CURLM_OK; /* do nothing */
-
- default:
- return CURLM_INTERNAL_ERROR;
- }
+ return CURLM_OK; /* do nothing */
+
+ default:
+ return CURLM_INTERNAL_ERROR;
+ }
statemachine_end:
-
- if(data->mstate < CURLM_STATE_COMPLETED) {
+
+ if(data->mstate < CURLM_STATE_COMPLETED) {
if(result) {
- /*
- * If an error was returned, and we aren't in completed state now,
- * then we go to completed and consider this transfer aborted.
- */
-
- /* NOTE: no attempt to disconnect connections must be made
- in the case blocks above - cleanup happens only here */
-
+ /*
+ * If an error was returned, and we aren't in completed state now,
+ * then we go to completed and consider this transfer aborted.
+ */
+
+ /* NOTE: no attempt to disconnect connections must be made
+ in the case blocks above - cleanup happens only here */
+
/* Check if we can move pending requests to send pipe */
process_pending_handles(multi); /* connection */
-
+
if(data->conn) {
if(stream_error) {
/* Don't attempt to send data over a connection that timed out */
bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
struct connectdata *conn = data->conn;
-
+
/* This is where we make sure that the conn pointer is reset.
- We don't have to do this in every case block above where a
- failure is detected */
+ We don't have to do this in every case block above where a
+ failure is detected */
Curl_detach_connnection(data);
/* remove connection from cache */
@@ -2348,30 +2348,30 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
/* disconnect properly */
Curl_disconnect(data, conn, dead_connection);
- }
- }
- else if(data->mstate == CURLM_STATE_CONNECT) {
- /* Curl_connect() failed */
- (void)Curl_posttransfer(data);
- }
-
- multistate(data, CURLM_STATE_COMPLETED);
+ }
+ }
+ else if(data->mstate == CURLM_STATE_CONNECT) {
+ /* Curl_connect() failed */
+ (void)Curl_posttransfer(data);
+ }
+
+ multistate(data, CURLM_STATE_COMPLETED);
rc = CURLM_CALL_MULTI_PERFORM;
- }
- /* if there's still a connection to use, call the progress function */
+ }
+ /* if there's still a connection to use, call the progress function */
else if(data->conn && Curl_pgrsUpdate(data->conn)) {
- /* aborted due to progress callback return code must close the
- connection */
+ /* aborted due to progress callback return code must close the
+ connection */
result = CURLE_ABORTED_BY_CALLBACK;
streamclose(data->conn, "Aborted by callback");
-
- /* if not yet in DONE state, go there, otherwise COMPLETED */
- multistate(data, (data->mstate < CURLM_STATE_DONE)?
- CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
+
+ /* if not yet in DONE state, go there, otherwise COMPLETED */
+ multistate(data, (data->mstate < CURLM_STATE_DONE)?
+ CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
rc = CURLM_CALL_MULTI_PERFORM;
- }
- }
-
+ }
+ }
+
if(CURLM_STATE_COMPLETED == data->mstate) {
if(data->set.fmultidone) {
/* signal via callback instead */
@@ -2380,117 +2380,117 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
else {
/* now fill in the Curl_message with this info */
msg = &data->msg;
-
+
msg->extmsg.msg = CURLMSG_DONE;
msg->extmsg.easy_handle = data;
msg->extmsg.data.result = result;
-
+
rc = multi_addmsg(multi, msg);
DEBUGASSERT(!data->conn);
}
multistate(data, CURLM_STATE_MSGSENT);
}
} while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE));
-
+
data->result = result;
return rc;
-}
-
-
+}
+
+
CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
-{
+{
struct Curl_easy *data;
CURLMcode returncode = CURLM_OK;
- struct Curl_tree *t;
+ struct Curl_tree *t;
struct curltime now = Curl_now();
-
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
+
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
data = multi->easyp;
- while(data) {
- CURLMcode result;
+ while(data) {
+ CURLMcode result;
SIGPIPE_VARIABLE(pipe_st);
-
+
sigpipe_ignore(data, &pipe_st);
result = multi_runsingle(multi, &now, data);
sigpipe_restore(&pipe_st);
-
- if(result)
- returncode = result;
-
- data = data->next; /* operate on next handle */
- }
-
- /*
- * Simply remove all expired timers from the splay since handles are dealt
- * with unconditionally by this function and curl_multi_timeout() requires
- * that already passed/handled expire times are removed from the splay.
- *
- * It is important that the 'now' value is set at the entry of this function
- * and not for the current time as it may have ticked a little while since
- * then and then we risk this loop to remove timers that actually have not
- * been handled!
- */
- do {
- multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
- if(t)
- /* the removed may have another timeout in queue */
- (void)add_next_timeout(now, multi, t->payload);
-
- } while(t);
-
- *running_handles = multi->num_alive;
-
- if(CURLM_OK >= returncode)
+
+ if(result)
+ returncode = result;
+
+ data = data->next; /* operate on next handle */
+ }
+
+ /*
+ * Simply remove all expired timers from the splay since handles are dealt
+ * with unconditionally by this function and curl_multi_timeout() requires
+ * that already passed/handled expire times are removed from the splay.
+ *
+ * It is important that the 'now' value is set at the entry of this function
+ * and not for the current time as it may have ticked a little while since
+ * then and then we risk this loop to remove timers that actually have not
+ * been handled!
+ */
+ do {
+ multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
+ if(t)
+ /* the removed may have another timeout in queue */
+ (void)add_next_timeout(now, multi, t->payload);
+
+ } while(t);
+
+ *running_handles = multi->num_alive;
+
+ if(CURLM_OK >= returncode)
Curl_update_timer(multi);
-
- return returncode;
-}
-
+
+ return returncode;
+}
+
CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
-{
+{
struct Curl_easy *data;
struct Curl_easy *nextdata;
-
+
if(GOOD_MULTI_HANDLE(multi)) {
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
-
- multi->type = 0; /* not good anymore */
-
+
+ multi->type = 0; /* not good anymore */
+
/* Firsrt remove all remaining easy handles */
- data = multi->easyp;
- while(data) {
+ data = multi->easyp;
+ while(data) {
nextdata = data->next;
if(!data->state.done && data->conn)
/* if DONE was never called for this handle */
(void)multi_done(data, CURLE_OK, TRUE);
- if(data->dns.hostcachetype == HCACHE_MULTI) {
- /* clear out the usage of the shared DNS cache */
- Curl_hostcache_clean(data, data->dns.hostcache);
- data->dns.hostcache = NULL;
- data->dns.hostcachetype = HCACHE_NONE;
- }
-
- /* Clear the pointer to the connection cache */
- data->state.conn_cache = NULL;
- data->multi = NULL; /* clear the association */
-
+ if(data->dns.hostcachetype == HCACHE_MULTI) {
+ /* clear out the usage of the shared DNS cache */
+ Curl_hostcache_clean(data, data->dns.hostcache);
+ data->dns.hostcache = NULL;
+ data->dns.hostcachetype = HCACHE_NONE;
+ }
+
+ /* Clear the pointer to the connection cache */
+ data->state.conn_cache = NULL;
+ data->multi = NULL; /* clear the association */
+
#ifdef USE_LIBPSL
if(data->psl == &multi->psl)
data->psl = NULL;
#endif
- data = nextdata;
- }
-
+ data = nextdata;
+ }
+
/* Close all the connections in the connection cache */
Curl_conncache_close_all_connections(&multi->conn_cache);
-
+
Curl_hash_destroy(&multi->sockhash);
Curl_conncache_destroy(&multi->conn_cache);
Curl_llist_destroy(&multi->msglist, NULL);
@@ -2503,98 +2503,98 @@ CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
sclose(multi->wakeup_pair[0]);
sclose(multi->wakeup_pair[1]);
#endif
- free(multi);
-
- return CURLM_OK;
- }
+ free(multi);
+
+ return CURLM_OK;
+ }
return CURLM_BAD_HANDLE;
-}
-
-/*
- * curl_multi_info_read()
- *
- * This function is the primary way for a multi/multi_socket application to
- * figure out if a transfer has ended. We MUST make this function as fast as
- * possible as it will be polled frequently and we MUST NOT scan any lists in
- * here to figure out things. We must scale fine to thousands of handles and
- * beyond. The current design is fully O(1).
- */
-
+}
+
+/*
+ * curl_multi_info_read()
+ *
+ * This function is the primary way for a multi/multi_socket application to
+ * figure out if a transfer has ended. We MUST make this function as fast as
+ * possible as it will be polled frequently and we MUST NOT scan any lists in
+ * here to figure out things. We must scale fine to thousands of handles and
+ * beyond. The current design is fully O(1).
+ */
+
CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue)
-{
- struct Curl_message *msg;
-
- *msgs_in_queue = 0; /* default to none */
-
+{
+ struct Curl_message *msg;
+
+ *msgs_in_queue = 0; /* default to none */
+
if(GOOD_MULTI_HANDLE(multi) &&
!multi->in_callback &&
Curl_llist_count(&multi->msglist)) {
- /* there is one or more messages in the list */
+ /* there is one or more messages in the list */
struct Curl_llist_element *e;
-
- /* extract the head of the list to return */
+
+ /* extract the head of the list to return */
e = multi->msglist.head;
-
- msg = e->ptr;
-
- /* remove the extracted entry */
+
+ msg = e->ptr;
+
+ /* remove the extracted entry */
Curl_llist_remove(&multi->msglist, e, NULL);
-
+
*msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist));
-
- return &msg->extmsg;
- }
+
+ return &msg->extmsg;
+ }
return NULL;
-}
-
-/*
- * singlesocket() checks what sockets we deal with and their "action state"
- * and if we have a different state in any of those sockets from last time we
- * call the callback accordingly.
- */
+}
+
+/*
+ * singlesocket() checks what sockets we deal with and their "action state"
+ * and if we have a different state in any of those sockets from last time we
+ * call the callback accordingly.
+ */
static CURLMcode singlesocket(struct Curl_multi *multi,
struct Curl_easy *data)
-{
- curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
- int i;
- struct Curl_sh_entry *entry;
- curl_socket_t s;
- int num;
- unsigned int curraction;
+{
+ curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
+ int i;
+ struct Curl_sh_entry *entry;
+ curl_socket_t s;
+ int num;
+ unsigned int curraction;
int actions[MAX_SOCKSPEREASYHANDLE];
-
+
for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++)
- socks[i] = CURL_SOCKET_BAD;
-
- /* Fill in the 'current' struct with the state as it is now: what sockets to
- supervise and for what actions */
+ socks[i] = CURL_SOCKET_BAD;
+
+ /* Fill in the 'current' struct with the state as it is now: what sockets to
+ supervise and for what actions */
curraction = multi_getsock(data, socks);
-
- /* We have 0 .. N sockets already and we get to know about the 0 .. M
- sockets we should have from now on. Detect the differences, remove no
- longer supervised ones and add new ones */
-
- /* walk over the sockets we got right now */
+
+ /* We have 0 .. N sockets already and we get to know about the 0 .. M
+ sockets we should have from now on. Detect the differences, remove no
+ longer supervised ones and add new ones */
+
+ /* walk over the sockets we got right now */
for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) &&
- (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
- i++) {
+ (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
+ i++) {
unsigned int action = CURL_POLL_NONE;
unsigned int prevaction = 0;
unsigned int comboaction;
bool sincebefore = FALSE;
-
- s = socks[i];
-
- /* get it from the hash */
+
+ s = socks[i];
+
+ /* get it from the hash */
entry = sh_getentry(&multi->sockhash, s);
-
- if(curraction & GETSOCK_READSOCK(i))
- action |= CURL_POLL_IN;
- if(curraction & GETSOCK_WRITESOCK(i))
- action |= CURL_POLL_OUT;
-
+
+ if(curraction & GETSOCK_READSOCK(i))
+ action |= CURL_POLL_IN;
+ if(curraction & GETSOCK_WRITESOCK(i))
+ action |= CURL_POLL_OUT;
+
actions[i] = action;
- if(entry) {
+ if(entry) {
/* check if new for this transfer */
int j;
for(j = 0; j< data->numsocks; j++) {
@@ -2604,14 +2604,14 @@ static CURLMcode singlesocket(struct Curl_multi *multi,
break;
}
}
- }
- else {
+ }
+ else {
/* this is a socket we didn't have before, add it to the hash! */
entry = sh_addentry(&multi->sockhash, s);
- if(!entry)
- /* fatal */
+ if(!entry)
+ /* fatal */
return CURLM_OUT_OF_MEMORY;
- }
+ }
if(sincebefore && (prevaction != action)) {
/* Socket was used already, but different action now */
if(prevaction & CURL_POLL_IN)
@@ -2630,7 +2630,7 @@ static CURLMcode singlesocket(struct Curl_multi *multi,
entry->readers++;
if(action & CURL_POLL_OUT)
entry->writers++;
-
+
/* add 'data' to the transfer hash on this socket! */
if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */
sizeof(struct Curl_easy *), data))
@@ -2645,31 +2645,31 @@ static CURLMcode singlesocket(struct Curl_multi *multi,
/* same, continue */
continue;
- if(multi->socket_cb)
+ if(multi->socket_cb)
multi->socket_cb(data, s, comboaction, multi->socket_userp,
- entry->socketp);
-
+ entry->socketp);
+
entry->action = comboaction; /* store the current action state */
- }
-
- num = i; /* number of sockets */
-
- /* when we've walked over all the sockets we should have right now, we must
- make sure to detect sockets that are removed */
+ }
+
+ num = i; /* number of sockets */
+
+ /* when we've walked over all the sockets we should have right now, we must
+ make sure to detect sockets that are removed */
for(i = 0; i< data->numsocks; i++) {
- int j;
+ int j;
bool stillused = FALSE;
- s = data->sockets[i];
+ s = data->sockets[i];
for(j = 0; j < num; j++) {
- if(s == socks[j]) {
- /* this is still supervised */
+ if(s == socks[j]) {
+ /* this is still supervised */
stillused = TRUE;
- break;
- }
- }
+ break;
+ }
+ }
if(stillused)
continue;
-
+
entry = sh_getentry(&multi->sockhash, s);
/* if this is NULL here, the socket has been closed and notified so
already by Curl_multi_closed() */
@@ -2682,12 +2682,12 @@ static CURLMcode singlesocket(struct Curl_multi *multi,
if(oldactions & CURL_POLL_IN)
entry->readers--;
if(!entry->users) {
- if(multi->socket_cb)
+ if(multi->socket_cb)
multi->socket_cb(data, s, CURL_POLL_REMOVE,
- multi->socket_userp,
- entry->socketp);
+ multi->socket_userp,
+ entry->socketp);
sh_delentry(entry, &multi->sockhash, s);
- }
+ }
else {
/* still users, but remove this handle as a user of this socket */
if(Curl_hash_delete(&entry->transfers, (char *)&data,
@@ -2697,31 +2697,31 @@ static CURLMcode singlesocket(struct Curl_multi *multi,
}
}
} /* for loop over numsocks */
-
- memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
+
+ memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
memcpy(data->actions, actions, num*sizeof(int));
- data->numsocks = num;
+ data->numsocks = num;
return CURLM_OK;
-}
-
+}
+
void Curl_updatesocket(struct Curl_easy *data)
{
singlesocket(data->multi, data);
}
-/*
- * Curl_multi_closed()
- *
- * Used by the connect code to tell the multi_socket code that one of the
+/*
+ * Curl_multi_closed()
+ *
+ * Used by the connect code to tell the multi_socket code that one of the
* sockets we were using is about to be closed. This function will then
- * remove it from the sockethash for this handle to make the multi_socket API
- * behave properly, especially for the case when libcurl will create another
- * socket again and it gets the same file descriptor number.
- */
-
+ * remove it from the sockethash for this handle to make the multi_socket API
+ * behave properly, especially for the case when libcurl will create another
+ * socket again and it gets the same file descriptor number.
+ */
+
void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s)
-{
+{
if(data) {
/* if there's still an easy handle associated with this connection */
struct Curl_multi *multi = data->multi;
@@ -2729,115 +2729,115 @@ void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s)
/* this is set if this connection is part of a handle that is added to
a multi handle, and only then this is necessary */
struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
-
+
if(entry) {
if(multi->socket_cb)
multi->socket_cb(data, s, CURL_POLL_REMOVE,
multi->socket_userp,
entry->socketp);
-
+
/* now remove it from the socket hash */
sh_delentry(entry, &multi->sockhash, s);
}
- }
- }
-}
-
-/*
- * add_next_timeout()
- *
+ }
+ }
+}
+
+/*
+ * add_next_timeout()
+ *
* Each Curl_easy has a list of timeouts. The add_next_timeout() is called
- * when it has just been removed from the splay tree because the timeout has
- * expired. This function is then to advance in the list to pick the next
- * timeout to use (skip the already expired ones) and add this node back to
- * the splay tree again.
- *
- * The splay tree only has each sessionhandle as a single node and the nearest
- * timeout is used to sort it on.
- */
+ * when it has just been removed from the splay tree because the timeout has
+ * expired. This function is then to advance in the list to pick the next
+ * timeout to use (skip the already expired ones) and add this node back to
+ * the splay tree again.
+ *
+ * The splay tree only has each sessionhandle as a single node and the nearest
+ * timeout is used to sort it on.
+ */
static CURLMcode add_next_timeout(struct curltime now,
- struct Curl_multi *multi,
+ struct Curl_multi *multi,
struct Curl_easy *d)
-{
+{
struct curltime *tv = &d->state.expiretime;
struct Curl_llist *list = &d->state.timeoutlist;
struct Curl_llist_element *e;
struct time_node *node = NULL;
-
- /* move over the timeout list for this specific handle and remove all
- timeouts that are now passed tense and store the next pending
- timeout in *tv */
+
+ /* move over the timeout list for this specific handle and remove all
+ timeouts that are now passed tense and store the next pending
+ timeout in *tv */
for(e = list->head; e;) {
struct Curl_llist_element *n = e->next;
timediff_t diff;
node = (struct time_node *)e->ptr;
diff = Curl_timediff(node->time, now);
- if(diff <= 0)
- /* remove outdated entry */
- Curl_llist_remove(list, e, NULL);
- else
- /* the list is sorted so get out on the first mismatch */
- break;
- e = n;
- }
- e = list->head;
- if(!e) {
- /* clear the expire times within the handles that we remove from the
- splay tree */
- tv->tv_sec = 0;
- tv->tv_usec = 0;
- }
- else {
- /* copy the first entry to 'tv' */
+ if(diff <= 0)
+ /* remove outdated entry */
+ Curl_llist_remove(list, e, NULL);
+ else
+ /* the list is sorted so get out on the first mismatch */
+ break;
+ e = n;
+ }
+ e = list->head;
+ if(!e) {
+ /* clear the expire times within the handles that we remove from the
+ splay tree */
+ tv->tv_sec = 0;
+ tv->tv_usec = 0;
+ }
+ else {
+ /* copy the first entry to 'tv' */
memcpy(tv, &node->time, sizeof(*tv));
-
+
/* Insert this node again into the splay. Keep the timer in the list in
case we need to recompute future timers. */
- multi->timetree = Curl_splayinsert(*tv, multi->timetree,
- &d->state.timenode);
- }
- return CURLM_OK;
-}
-
-static CURLMcode multi_socket(struct Curl_multi *multi,
- bool checkall,
- curl_socket_t s,
- int ev_bitmask,
- int *running_handles)
-{
- CURLMcode result = CURLM_OK;
+ multi->timetree = Curl_splayinsert(*tv, multi->timetree,
+ &d->state.timenode);
+ }
+ return CURLM_OK;
+}
+
+static CURLMcode multi_socket(struct Curl_multi *multi,
+ bool checkall,
+ curl_socket_t s,
+ int ev_bitmask,
+ int *running_handles)
+{
+ CURLMcode result = CURLM_OK;
struct Curl_easy *data = NULL;
- struct Curl_tree *t;
+ struct Curl_tree *t;
struct curltime now = Curl_now();
-
- if(checkall) {
- /* *perform() deals with running_handles on its own */
- result = curl_multi_perform(multi, running_handles);
-
- /* walk through each easy handle and do the socket state change magic
- and callbacks */
+
+ if(checkall) {
+ /* *perform() deals with running_handles on its own */
+ result = curl_multi_perform(multi, running_handles);
+
+ /* walk through each easy handle and do the socket state change magic
+ and callbacks */
if(result != CURLM_BAD_HANDLE) {
data = multi->easyp;
while(data && !result) {
result = singlesocket(multi, data);
data = data->next;
}
- }
-
- /* or should we fall-through and do the timer-based stuff? */
- return result;
- }
+ }
+
+ /* or should we fall-through and do the timer-based stuff? */
+ return result;
+ }
if(s != CURL_SOCKET_TIMEOUT) {
struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
-
- if(!entry)
- /* Unmatched socket, we can't act on it but we ignore this fact. In
- real-world tests it has been proved that libevent can in fact give
- the application actions even though the socket was just previously
- asked to get removed, so thus we better survive stray socket actions
- and just move on. */
- ;
- else {
+
+ if(!entry)
+ /* Unmatched socket, we can't act on it but we ignore this fact. In
+ real-world tests it has been proved that libevent can in fact give
+ the application actions even though the socket was just previously
+ asked to get removed, so thus we better survive stray socket actions
+ and just move on. */
+ ;
+ else {
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
@@ -2848,24 +2848,24 @@ static CURLMcode multi_socket(struct Curl_multi *multi,
data = (struct Curl_easy *)he->ptr;
DEBUGASSERT(data);
DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER);
-
+
if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK))
/* set socket event bitmask if they're not locked */
data->conn->cselect_bits = ev_bitmask;
-
+
Curl_expire(data, 0, EXPIRE_RUN_NOW);
- }
-
- /* Now we fall-through and do the timer-based stuff, since we don't want
- to force the user to have to deal with timeouts as long as at least
- one connection in fact has traffic. */
-
- data = NULL; /* set data to NULL again to avoid calling
- multi_runsingle() in case there's no need to */
+ }
+
+ /* Now we fall-through and do the timer-based stuff, since we don't want
+ to force the user to have to deal with timeouts as long as at least
+ one connection in fact has traffic. */
+
+ data = NULL; /* set data to NULL again to avoid calling
+ multi_runsingle() in case there's no need to */
now = Curl_now(); /* get a newer time since the multi_runsingle() loop
may have taken some time */
- }
- }
+ }
+ }
else {
/* Asked to run due to time-out. Clear the 'lastcall' variable to force
Curl_update_timer() to trigger a callback to the app again even if the
@@ -2873,103 +2873,103 @@ static CURLMcode multi_socket(struct Curl_multi *multi,
case when the application asks libcurl to run the timeout
prematurely. */
memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
- }
-
- /*
- * The loop following here will go on as long as there are expire-times left
- * to process in the splay and 'data' will be re-assigned for every expired
- * handle we deal with.
- */
- do {
- /* the first loop lap 'data' can be NULL */
- if(data) {
+ }
+
+ /*
+ * The loop following here will go on as long as there are expire-times left
+ * to process in the splay and 'data' will be re-assigned for every expired
+ * handle we deal with.
+ */
+ do {
+ /* the first loop lap 'data' can be NULL */
+ if(data) {
SIGPIPE_VARIABLE(pipe_st);
-
+
sigpipe_ignore(data, &pipe_st);
result = multi_runsingle(multi, &now, data);
sigpipe_restore(&pipe_st);
if(CURLM_OK >= result) {
- /* get the socket(s) and check if the state has been changed since
- last */
+ /* get the socket(s) and check if the state has been changed since
+ last */
result = singlesocket(multi, data);
if(result)
return result;
}
- }
-
- /* Check if there's one (more) expired timer to deal with! This function
- extracts a matching node if there is one */
-
- multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
- if(t) {
- data = t->payload; /* assign this for next loop */
- (void)add_next_timeout(now, multi, t->payload);
- }
-
- } while(t);
-
- *running_handles = multi->num_alive;
- return result;
-}
-
-#undef curl_multi_setopt
+ }
+
+ /* Check if there's one (more) expired timer to deal with! This function
+ extracts a matching node if there is one */
+
+ multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
+ if(t) {
+ data = t->payload; /* assign this for next loop */
+ (void)add_next_timeout(now, multi, t->payload);
+ }
+
+ } while(t);
+
+ *running_handles = multi->num_alive;
+ return result;
+}
+
+#undef curl_multi_setopt
CURLMcode curl_multi_setopt(struct Curl_multi *multi,
- CURLMoption option, ...)
-{
- CURLMcode res = CURLM_OK;
- va_list param;
-
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
+ CURLMoption option, ...)
+{
+ CURLMcode res = CURLM_OK;
+ va_list param;
+
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
- va_start(param, option);
-
- switch(option) {
- case CURLMOPT_SOCKETFUNCTION:
- multi->socket_cb = va_arg(param, curl_socket_callback);
- break;
- case CURLMOPT_SOCKETDATA:
- multi->socket_userp = va_arg(param, void *);
- break;
+ va_start(param, option);
+
+ switch(option) {
+ case CURLMOPT_SOCKETFUNCTION:
+ multi->socket_cb = va_arg(param, curl_socket_callback);
+ break;
+ case CURLMOPT_SOCKETDATA:
+ multi->socket_userp = va_arg(param, void *);
+ break;
case CURLMOPT_PUSHFUNCTION:
multi->push_cb = va_arg(param, curl_push_callback);
break;
case CURLMOPT_PUSHDATA:
multi->push_userp = va_arg(param, void *);
break;
- case CURLMOPT_PIPELINING:
+ case CURLMOPT_PIPELINING:
multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX;
- break;
- case CURLMOPT_TIMERFUNCTION:
- multi->timer_cb = va_arg(param, curl_multi_timer_callback);
- break;
- case CURLMOPT_TIMERDATA:
- multi->timer_userp = va_arg(param, void *);
- break;
- case CURLMOPT_MAXCONNECTS:
- multi->maxconnects = va_arg(param, long);
- break;
- case CURLMOPT_MAX_HOST_CONNECTIONS:
- multi->max_host_connections = va_arg(param, long);
- break;
+ break;
+ case CURLMOPT_TIMERFUNCTION:
+ multi->timer_cb = va_arg(param, curl_multi_timer_callback);
+ break;
+ case CURLMOPT_TIMERDATA:
+ multi->timer_userp = va_arg(param, void *);
+ break;
+ case CURLMOPT_MAXCONNECTS:
+ multi->maxconnects = va_arg(param, long);
+ break;
+ case CURLMOPT_MAX_HOST_CONNECTIONS:
+ multi->max_host_connections = va_arg(param, long);
+ break;
case CURLMOPT_MAX_TOTAL_CONNECTIONS:
multi->max_total_connections = va_arg(param, long);
break;
/* options formerly used for pipelining */
- case CURLMOPT_MAX_PIPELINE_LENGTH:
- break;
- case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
- break;
- case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
- break;
- case CURLMOPT_PIPELINING_SITE_BL:
- break;
- case CURLMOPT_PIPELINING_SERVER_BL:
- break;
+ case CURLMOPT_MAX_PIPELINE_LENGTH:
+ break;
+ case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
+ break;
+ case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
+ break;
+ case CURLMOPT_PIPELINING_SITE_BL:
+ break;
+ case CURLMOPT_PIPELINING_SERVER_BL:
+ break;
case CURLMOPT_MAX_CONCURRENT_STREAMS:
{
long streams = va_arg(param, long);
@@ -2978,149 +2978,149 @@ CURLMcode curl_multi_setopt(struct Curl_multi *multi,
multi->max_concurrent_streams = curlx_sltoui(streams);
}
break;
- default:
- res = CURLM_UNKNOWN_OPTION;
- break;
- }
- va_end(param);
- return res;
-}
-
-/* we define curl_multi_socket() in the public multi.h header */
-#undef curl_multi_socket
-
+ default:
+ res = CURLM_UNKNOWN_OPTION;
+ break;
+ }
+ va_end(param);
+ return res;
+}
+
+/* we define curl_multi_socket() in the public multi.h header */
+#undef curl_multi_socket
+
CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s,
- int *running_handles)
-{
+ int *running_handles)
+{
CURLMcode result;
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
result = multi_socket(multi, FALSE, s, 0, running_handles);
- if(CURLM_OK >= result)
+ if(CURLM_OK >= result)
Curl_update_timer(multi);
- return result;
-}
-
+ return result;
+}
+
CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s,
- int ev_bitmask, int *running_handles)
-{
+ int ev_bitmask, int *running_handles)
+{
CURLMcode result;
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles);
- if(CURLM_OK >= result)
+ if(CURLM_OK >= result)
Curl_update_timer(multi);
- return result;
-}
-
+ return result;
+}
+
CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
-{
+{
CURLMcode result;
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles);
- if(CURLM_OK >= result)
+ if(CURLM_OK >= result)
Curl_update_timer(multi);
- return result;
-}
-
-static CURLMcode multi_timeout(struct Curl_multi *multi,
- long *timeout_ms)
-{
+ return result;
+}
+
+static CURLMcode multi_timeout(struct Curl_multi *multi,
+ long *timeout_ms)
+{
static struct curltime tv_zero = {0, 0};
-
- if(multi->timetree) {
- /* we have a tree of expire times */
+
+ if(multi->timetree) {
+ /* we have a tree of expire times */
struct curltime now = Curl_now();
-
- /* splay the lowest to the bottom */
- multi->timetree = Curl_splay(tv_zero, multi->timetree);
-
- if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
- /* some time left before expiration */
+
+ /* splay the lowest to the bottom */
+ multi->timetree = Curl_splay(tv_zero, multi->timetree);
+
+ if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
+ /* some time left before expiration */
timediff_t diff = Curl_timediff(multi->timetree->key, now);
if(diff <= 0)
- /*
- * Since we only provide millisecond resolution on the returned value
- * and the diff might be less than one millisecond here, we don't
- * return zero as that may cause short bursts of busyloops on fast
- * processors while the diff is still present but less than one
- * millisecond! instead we return 1 until the time is ripe.
- */
+ /*
+ * Since we only provide millisecond resolution on the returned value
+ * and the diff might be less than one millisecond here, we don't
+ * return zero as that may cause short bursts of busyloops on fast
+ * processors while the diff is still present but less than one
+ * millisecond! instead we return 1 until the time is ripe.
+ */
*timeout_ms = 1;
else
/* this should be safe even on 64 bit archs, as we don't use that
overly long timeouts */
*timeout_ms = (long)diff;
- }
- else
- /* 0 means immediately */
- *timeout_ms = 0;
- }
- else
- *timeout_ms = -1;
-
- return CURLM_OK;
-}
-
+ }
+ else
+ /* 0 means immediately */
+ *timeout_ms = 0;
+ }
+ else
+ *timeout_ms = -1;
+
+ return CURLM_OK;
+}
+
CURLMcode curl_multi_timeout(struct Curl_multi *multi,
- long *timeout_ms)
-{
- /* First, make some basic checks that the CURLM handle is a good handle */
- if(!GOOD_MULTI_HANDLE(multi))
- return CURLM_BAD_HANDLE;
-
+ long *timeout_ms)
+{
+ /* First, make some basic checks that the CURLM handle is a good handle */
+ if(!GOOD_MULTI_HANDLE(multi))
+ return CURLM_BAD_HANDLE;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
- return multi_timeout(multi, timeout_ms);
-}
-
-/*
- * Tell the application it should update its timers, if it subscribes to the
- * update timer callback.
- */
+ return multi_timeout(multi, timeout_ms);
+}
+
+/*
+ * Tell the application it should update its timers, if it subscribes to the
+ * update timer callback.
+ */
void Curl_update_timer(struct Curl_multi *multi)
-{
- long timeout_ms;
-
- if(!multi->timer_cb)
+{
+ long timeout_ms;
+
+ if(!multi->timer_cb)
return;
- if(multi_timeout(multi, &timeout_ms)) {
+ if(multi_timeout(multi, &timeout_ms)) {
return;
- }
- if(timeout_ms < 0) {
+ }
+ if(timeout_ms < 0) {
static const struct curltime none = {0, 0};
- if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
- multi->timer_lastcall = none;
- /* there's no timeout now but there was one previously, tell the app to
- disable it */
+ if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
+ multi->timer_lastcall = none;
+ /* there's no timeout now but there was one previously, tell the app to
+ disable it */
multi->timer_cb(multi, -1, multi->timer_userp);
return;
- }
+ }
return;
- }
-
- /* When multi_timeout() is done, multi->timetree points to the node with the
- * timeout we got the (relative) time-out time for. We can thus easily check
- * if this is the same (fixed) time as we got in a previous call and then
- * avoid calling the callback again. */
- if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
+ }
+
+ /* When multi_timeout() is done, multi->timetree points to the node with the
+ * timeout we got the (relative) time-out time for. We can thus easily check
+ * if this is the same (fixed) time as we got in a previous call and then
+ * avoid calling the callback again. */
+ if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
return;
-
- multi->timer_lastcall = multi->timetree->key;
-
+
+ multi->timer_lastcall = multi->timetree->key;
+
multi->timer_cb(multi, timeout_ms, multi->timer_userp);
-}
-
-/*
+}
+
+/*
* multi_deltimeout()
- *
+ *
* Remove a given timestamp from the list of timeouts.
- */
+ */
static void
multi_deltimeout(struct Curl_easy *data, expire_id eid)
-{
+{
struct Curl_llist_element *e;
struct Curl_llist *timeoutlist = &data->state.timeoutlist;
/* find and remove the specific node from the list */
@@ -3131,84 +3131,84 @@ multi_deltimeout(struct Curl_easy *data, expire_id eid)
return;
}
}
-}
-
-/*
- * multi_addtimeout()
- *
- * Add a timestamp to the list of timeouts. Keep the list sorted so that head
- * of list is always the timeout nearest in time.
- *
- */
-static CURLMcode
+}
+
+/*
+ * multi_addtimeout()
+ *
+ * Add a timestamp to the list of timeouts. Keep the list sorted so that head
+ * of list is always the timeout nearest in time.
+ *
+ */
+static CURLMcode
multi_addtimeout(struct Curl_easy *data,
struct curltime *stamp,
expire_id eid)
-{
+{
struct Curl_llist_element *e;
struct time_node *node;
struct Curl_llist_element *prev = NULL;
size_t n;
struct Curl_llist *timeoutlist = &data->state.timeoutlist;
-
+
node = &data->state.expires[eid];
-
+
/* copy the timestamp and id */
memcpy(&node->time, stamp, sizeof(*stamp));
node->eid = eid; /* also marks it as in use */
-
+
n = Curl_llist_count(timeoutlist);
if(n) {
- /* find the correct spot in the list */
- for(e = timeoutlist->head; e; e = e->next) {
+ /* find the correct spot in the list */
+ for(e = timeoutlist->head; e; e = e->next) {
struct time_node *check = (struct time_node *)e->ptr;
timediff_t diff = Curl_timediff(check->time, node->time);
- if(diff > 0)
- break;
- prev = e;
- }
-
- }
- /* else
- this is the first timeout on the list */
-
+ if(diff > 0)
+ break;
+ prev = e;
+ }
+
+ }
+ /* else
+ this is the first timeout on the list */
+
Curl_llist_insert_next(timeoutlist, prev, node, &node->list);
- return CURLM_OK;
-}
-
-/*
- * Curl_expire()
- *
- * given a number of milliseconds from now to use to set the 'act before
- * this'-time for the transfer, to be extracted by curl_multi_timeout()
- *
+ return CURLM_OK;
+}
+
+/*
+ * Curl_expire()
+ *
+ * given a number of milliseconds from now to use to set the 'act before
+ * this'-time for the transfer, to be extracted by curl_multi_timeout()
+ *
* The timeout will be added to a queue of timeouts if it defines a moment in
* time that is later than the current head of queue.
- *
+ *
* Expire replaces a former timeout using the same id if already set.
*/
void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
-{
- struct Curl_multi *multi = data->multi;
+{
+ struct Curl_multi *multi = data->multi;
struct curltime *nowp = &data->state.expiretime;
struct curltime set;
-
- /* this is only interesting while there is still an associated multi struct
- remaining! */
- if(!multi)
- return;
-
+
+ /* this is only interesting while there is still an associated multi struct
+ remaining! */
+ if(!multi)
+ return;
+
DEBUGASSERT(id < EXPIRE_LAST);
-
+
set = Curl_now();
set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */
set.tv_usec += (unsigned int)(milli%1000)*1000;
-
+
if(set.tv_usec >= 1000000) {
set.tv_sec++;
set.tv_usec -= 1000000;
}
-
+
/* Remove any timer with the same id just in case. */
multi_deltimeout(data, id);
@@ -3227,7 +3227,7 @@ void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
/* The current splay tree entry is sooner than this new expiry time.
We don't need to update our splay tree entry. */
return;
- }
+ }
/* Since this is an updated time, we must remove the previous entry from
the splay tree first and then re-add the new value */
@@ -3235,8 +3235,8 @@ void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
&multi->timetree);
if(rc)
infof(data, "Internal error removing splay node = %d\n", rc);
- }
-
+ }
+
/* Indicate that we are in the splay tree and insert the new timer expiry
value since it is our local minimum. */
*nowp = set;
@@ -3244,7 +3244,7 @@ void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id)
multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
&data->state.timenode);
}
-
+
/*
* Curl_expire_done()
*
@@ -3256,7 +3256,7 @@ void Curl_expire_done(struct Curl_easy *data, expire_id id)
/* remove the timer, if there */
multi_deltimeout(data, id);
}
-
+
/*
* Curl_expire_clear()
*
@@ -3266,12 +3266,12 @@ void Curl_expire_clear(struct Curl_easy *data)
{
struct Curl_multi *multi = data->multi;
struct curltime *nowp = &data->state.expiretime;
-
+
/* this is only interesting while there is still an associated multi struct
remaining! */
if(!multi)
return;
-
+
if(nowp->tv_sec || nowp->tv_usec) {
/* Since this is an cleared time, we must remove the previous entry from
the splay tree */
@@ -3286,69 +3286,69 @@ void Curl_expire_clear(struct Curl_easy *data)
/* flush the timeout list too */
while(list->size > 0) {
Curl_llist_remove(list, list->tail, NULL);
- }
-
+ }
+
#ifdef DEBUGBUILD
infof(data, "Expire cleared (transfer %p)\n", data);
#endif
nowp->tv_sec = 0;
nowp->tv_usec = 0;
- }
-}
-
+ }
+}
+
CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
void *hashp)
-{
- struct Curl_sh_entry *there = NULL;
-
+{
+ struct Curl_sh_entry *there = NULL;
+
if(multi->in_callback)
return CURLM_RECURSIVE_API_CALL;
-
+
there = sh_getentry(&multi->sockhash, s);
- if(!there)
- return CURLM_BAD_SOCKET;
-
- there->socketp = hashp;
-
- return CURLM_OK;
-}
-
-size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
-{
- return multi ? multi->max_host_connections : 0;
-}
-
-size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
-{
- return multi ? multi->max_total_connections : 0;
-}
-
+ if(!there)
+ return CURLM_BAD_SOCKET;
+
+ there->socketp = hashp;
+
+ return CURLM_OK;
+}
+
+size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
+{
+ return multi ? multi->max_host_connections : 0;
+}
+
+size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
+{
+ return multi ? multi->max_total_connections : 0;
+}
+
/*
* When information about a connection has appeared, call this!
*/
-
+
void Curl_multiuse_state(struct connectdata *conn,
int bundlestate) /* use BUNDLE_* defines */
-{
+{
DEBUGASSERT(conn);
DEBUGASSERT(conn->bundle);
DEBUGASSERT(conn->data);
DEBUGASSERT(conn->data->multi);
-
+
conn->bundle->multiuse = bundlestate;
process_pending_handles(conn->data->multi);
-}
-
+}
+
static void process_pending_handles(struct Curl_multi *multi)
-{
+{
struct Curl_llist_element *e = multi->pending.head;
if(e) {
struct Curl_easy *data = e->ptr;
-
+
DEBUGASSERT(data->mstate == CURLM_STATE_CONNECT_PEND);
multistate(data, CURLM_STATE_CONNECT);
@@ -3361,9 +3361,9 @@ static void process_pending_handles(struct Curl_multi *multi)
/* mark this as having been in the pending queue */
data->state.previouslypending = TRUE;
- }
-}
-
+ }
+}
+
void Curl_set_in_callback(struct Curl_easy *data, bool value)
{
/* might get called when there is no data pointer! */
@@ -3381,38 +3381,38 @@ bool Curl_is_in_callback(struct Curl_easy *easy)
(easy->multi_easy && easy->multi_easy->in_callback));
}
-#ifdef DEBUGBUILD
+#ifdef DEBUGBUILD
void Curl_multi_dump(struct Curl_multi *multi)
-{
+{
struct Curl_easy *data;
- int i;
- fprintf(stderr, "* Multi status: %d handles, %d alive\n",
- multi->num_easy, multi->num_alive);
+ int i;
+ fprintf(stderr, "* Multi status: %d handles, %d alive\n",
+ multi->num_easy, multi->num_alive);
for(data = multi->easyp; data; data = data->next) {
- if(data->mstate < CURLM_STATE_COMPLETED) {
- /* only display handles that are not completed */
- fprintf(stderr, "handle %p, state %s, %d sockets\n",
- (void *)data,
- statename[data->mstate], data->numsocks);
+ if(data->mstate < CURLM_STATE_COMPLETED) {
+ /* only display handles that are not completed */
+ fprintf(stderr, "handle %p, state %s, %d sockets\n",
+ (void *)data,
+ statename[data->mstate], data->numsocks);
for(i = 0; i < data->numsocks; i++) {
- curl_socket_t s = data->sockets[i];
+ curl_socket_t s = data->sockets[i];
struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
-
- fprintf(stderr, "%d ", (int)s);
- if(!entry) {
- fprintf(stderr, "INTERNAL CONFUSION\n");
- continue;
- }
- fprintf(stderr, "[%s %s] ",
+
+ fprintf(stderr, "%d ", (int)s);
+ if(!entry) {
+ fprintf(stderr, "INTERNAL CONFUSION\n");
+ continue;
+ }
+ fprintf(stderr, "[%s %s] ",
(entry->action&CURL_POLL_IN)?"RECVING":"",
(entry->action&CURL_POLL_OUT)?"SENDING":"");
- }
- if(data->numsocks)
- fprintf(stderr, "\n");
- }
- }
-}
-#endif
+ }
+ if(data->numsocks)
+ fprintf(stderr, "\n");
+ }
+ }
+}
+#endif
unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi)
{
diff --git a/contrib/libs/curl/lib/multihandle.h b/contrib/libs/curl/lib/multihandle.h
index b3a33b041b..de4f74069e 100644
--- a/contrib/libs/curl/lib/multihandle.h
+++ b/contrib/libs/curl/lib/multihandle.h
@@ -1,52 +1,52 @@
-#ifndef HEADER_CURL_MULTIHANDLE_H
-#define HEADER_CURL_MULTIHANDLE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MULTIHANDLE_H
+#define HEADER_CURL_MULTIHANDLE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include "conncache.h"
#include "psl.h"
#include "socketpair.h"
-struct Curl_message {
+struct Curl_message {
struct Curl_llist_element list;
- /* the 'CURLMsg' is the part that is visible to the external user */
- struct CURLMsg extmsg;
-};
-
-/* NOTE: if you add a state here, add the name to the statename[] array as
- well!
-*/
-typedef enum {
- CURLM_STATE_INIT, /* 0 - start in this state */
- CURLM_STATE_CONNECT_PEND, /* 1 - no connections, waiting for one */
- CURLM_STATE_CONNECT, /* 2 - resolve/connect has been sent off */
- CURLM_STATE_WAITRESOLVE, /* 3 - awaiting the resolve to finalize */
+ /* the 'CURLMsg' is the part that is visible to the external user */
+ struct CURLMsg extmsg;
+};
+
+/* NOTE: if you add a state here, add the name to the statename[] array as
+ well!
+*/
+typedef enum {
+ CURLM_STATE_INIT, /* 0 - start in this state */
+ CURLM_STATE_CONNECT_PEND, /* 1 - no connections, waiting for one */
+ CURLM_STATE_CONNECT, /* 2 - resolve/connect has been sent off */
+ CURLM_STATE_WAITRESOLVE, /* 3 - awaiting the resolve to finalize */
CURLM_STATE_WAITCONNECT, /* 4 - awaiting the TCP connect to finalize */
CURLM_STATE_WAITPROXYCONNECT, /* 5 - awaiting HTTPS proxy SSL initialization
to complete and/or proxy CONNECT to
finalize */
CURLM_STATE_SENDPROTOCONNECT, /* 6 - initiate protocol connect procedure */
CURLM_STATE_PROTOCONNECT, /* 7 - completing the protocol-specific connect
- phase */
+ phase */
CURLM_STATE_DO, /* 8 - start send off the request (part 1) */
CURLM_STATE_DOING, /* 9 - sending off the request (part 1) */
CURLM_STATE_DO_MORE, /* 10 - send off the request (part 2) */
@@ -57,14 +57,14 @@ typedef enum {
CURLM_STATE_COMPLETED, /* 15 - operation complete */
CURLM_STATE_MSGSENT, /* 16 - the operation complete message is sent */
CURLM_STATE_LAST /* 17 - not a true state, never use this */
-} CURLMstate;
-
-/* we support N sockets per easy handle. Set the corresponding bit to what
- action we should wait for */
-#define MAX_SOCKSPEREASYHANDLE 5
-#define GETSOCK_READABLE (0x00ff)
-#define GETSOCK_WRITABLE (0xff00)
-
+} CURLMstate;
+
+/* we support N sockets per easy handle. Set the corresponding bit to what
+ action we should wait for */
+#define MAX_SOCKSPEREASYHANDLE 5
+#define GETSOCK_READABLE (0x00ff)
+#define GETSOCK_WRITABLE (0xff00)
+
#define CURLPIPE_ANY (CURLPIPE_MULTIPLEX)
#if defined(USE_SOCKETPAIR) && !defined(USE_BLOCKING_SOCKETS) && \
@@ -75,67 +75,67 @@ typedef enum {
/* value for MAXIMUM CONCURRENT STREAMS upper limit */
#define INITIAL_MAX_CONCURRENT_STREAMS ((1U << 31) - 1)
-/* This is the struct known as CURLM on the outside */
-struct Curl_multi {
- /* First a simple identifier to easier detect if a user mix up
- this multi handle with an easy handle. Set this to CURL_MULTI_HANDLE. */
- long type;
-
+/* This is the struct known as CURLM on the outside */
+struct Curl_multi {
+ /* First a simple identifier to easier detect if a user mix up
+ this multi handle with an easy handle. Set this to CURL_MULTI_HANDLE. */
+ long type;
+
/* We have a doubly-linked list with easy handles */
struct Curl_easy *easyp;
struct Curl_easy *easylp; /* last node */
-
- int num_easy; /* amount of entries in the linked list above. */
- int num_alive; /* amount of easy handles that are added but have not yet
- reached COMPLETE state */
-
+
+ int num_easy; /* amount of entries in the linked list above. */
+ int num_alive; /* amount of easy handles that are added but have not yet
+ reached COMPLETE state */
+
struct Curl_llist msglist; /* a list of messages from completed transfers */
-
+
struct Curl_llist pending; /* Curl_easys that are in the
CURLM_STATE_CONNECT_PEND state */
- /* callback function and user data pointer for the *socket() API */
- curl_socket_callback socket_cb;
- void *socket_userp;
-
+ /* callback function and user data pointer for the *socket() API */
+ curl_socket_callback socket_cb;
+ void *socket_userp;
+
/* callback function and user data pointer for server push */
curl_push_callback push_cb;
void *push_userp;
- /* Hostname cache */
+ /* Hostname cache */
struct Curl_hash hostcache;
-
+
#ifdef USE_LIBPSL
/* PSL cache. */
struct PslCache psl;
#endif
- /* timetree points to the splay-tree of time nodes to figure out expire
- times of all currently set timers */
- struct Curl_tree *timetree;
-
- /* 'sockhash' is the lookup hash for socket descriptor => easy handles (note
- the pluralis form, there can be more than one easy handle waiting on the
- same actual socket) */
+ /* timetree points to the splay-tree of time nodes to figure out expire
+ times of all currently set timers */
+ struct Curl_tree *timetree;
+
+ /* 'sockhash' is the lookup hash for socket descriptor => easy handles (note
+ the pluralis form, there can be more than one easy handle waiting on the
+ same actual socket) */
struct Curl_hash sockhash;
-
- /* Shared connection cache (bundles)*/
+
+ /* Shared connection cache (bundles)*/
struct conncache conn_cache;
-
- long maxconnects; /* if >0, a fixed limit of the maximum number of entries
- we're allowed to grow the connection cache to */
-
- long max_host_connections; /* if >0, a fixed limit of the maximum number
- of connections per host */
-
- long max_total_connections; /* if >0, a fixed limit of the maximum number
- of connections in total */
-
- /* timer callback and user data pointer for the *socket() API */
- curl_multi_timer_callback timer_cb;
- void *timer_userp;
+
+ long maxconnects; /* if >0, a fixed limit of the maximum number of entries
+ we're allowed to grow the connection cache to */
+
+ long max_host_connections; /* if >0, a fixed limit of the maximum number
+ of connections per host */
+
+ long max_total_connections; /* if >0, a fixed limit of the maximum number
+ of connections in total */
+
+ /* timer callback and user data pointer for the *socket() API */
+ curl_multi_timer_callback timer_cb;
+ void *timer_userp;
struct curltime timer_lastcall; /* the fixed time for the timeout for the
- previous callback */
+ previous callback */
unsigned int max_concurrent_streams;
#ifdef ENABLE_WAKEUP
@@ -147,6 +147,6 @@ struct Curl_multi {
bool recheckstate; /* see Curl_multi_connchanged */
bool in_callback; /* true while executing a callback */
bool ipv6_works;
-};
-
-#endif /* HEADER_CURL_MULTIHANDLE_H */
+};
+
+#endif /* HEADER_CURL_MULTIHANDLE_H */
diff --git a/contrib/libs/curl/lib/multiif.h b/contrib/libs/curl/lib/multiif.h
index 55b818f6ea..f0a57d9a6c 100644
--- a/contrib/libs/curl/lib/multiif.h
+++ b/contrib/libs/curl/lib/multiif.h
@@ -1,31 +1,31 @@
-#ifndef HEADER_CURL_MULTIIF_H
-#define HEADER_CURL_MULTIIF_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_MULTIIF_H
+#define HEADER_CURL_MULTIIF_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * Prototypes for library-wide functions provided by multi.c
- */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * Prototypes for library-wide functions provided by multi.c
+ */
+
void Curl_updatesocket(struct Curl_easy *data);
void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id);
void Curl_expire_clear(struct Curl_easy *data);
@@ -38,52 +38,52 @@ bool Curl_multiplex_wanted(const struct Curl_multi *multi);
void Curl_set_in_callback(struct Curl_easy *data, bool value);
bool Curl_is_in_callback(struct Curl_easy *easy);
CURLcode Curl_preconnect(struct Curl_easy *data);
-
-/* Internal version of curl_multi_init() accepts size parameters for the
- socket and connection hashes */
-struct Curl_multi *Curl_multi_handle(int hashsize, int chashsize);
-
-/* the write bits start at bit 16 for the *getsock() bitmap */
-#define GETSOCK_WRITEBITSTART 16
-
-#define GETSOCK_BLANK 0 /* no bits set */
-
-/* set the bit for the given sock number to make the bitmap for writable */
-#define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x)))
-
-/* set the bit for the given sock number to make the bitmap for readable */
-#define GETSOCK_READSOCK(x) (1 << (x))
-
-#ifdef DEBUGBUILD
- /*
- * Curl_multi_dump is not a stable public function, this is only meant to
- * allow easier tracking of the internal handle's state and what sockets
- * they use. Only for research and development DEBUGBUILD enabled builds.
- */
+
+/* Internal version of curl_multi_init() accepts size parameters for the
+ socket and connection hashes */
+struct Curl_multi *Curl_multi_handle(int hashsize, int chashsize);
+
+/* the write bits start at bit 16 for the *getsock() bitmap */
+#define GETSOCK_WRITEBITSTART 16
+
+#define GETSOCK_BLANK 0 /* no bits set */
+
+/* set the bit for the given sock number to make the bitmap for writable */
+#define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x)))
+
+/* set the bit for the given sock number to make the bitmap for readable */
+#define GETSOCK_READSOCK(x) (1 << (x))
+
+#ifdef DEBUGBUILD
+ /*
+ * Curl_multi_dump is not a stable public function, this is only meant to
+ * allow easier tracking of the internal handle's state and what sockets
+ * they use. Only for research and development DEBUGBUILD enabled builds.
+ */
void Curl_multi_dump(struct Curl_multi *multi);
-#endif
-
-/* Return the value of the CURLMOPT_MAX_HOST_CONNECTIONS option */
-size_t Curl_multi_max_host_connections(struct Curl_multi *multi);
-
-/* Return the value of the CURLMOPT_MAX_TOTAL_CONNECTIONS option */
-size_t Curl_multi_max_total_connections(struct Curl_multi *multi);
-
+#endif
+
+/* Return the value of the CURLMOPT_MAX_HOST_CONNECTIONS option */
+size_t Curl_multi_max_host_connections(struct Curl_multi *multi);
+
+/* Return the value of the CURLMOPT_MAX_TOTAL_CONNECTIONS option */
+size_t Curl_multi_max_total_connections(struct Curl_multi *multi);
+
void Curl_multiuse_state(struct connectdata *conn,
int bundlestate); /* use BUNDLE_* defines */
-/*
- * Curl_multi_closed()
- *
- * Used by the connect code to tell the multi_socket code that one of the
+/*
+ * Curl_multi_closed()
+ *
+ * Used by the connect code to tell the multi_socket code that one of the
* sockets we were using is about to be closed. This function will then
- * remove it from the sockethash for this handle to make the multi_socket API
- * behave properly, especially for the case when libcurl will create another
- * socket again and it gets the same file descriptor number.
- */
-
+ * remove it from the sockethash for this handle to make the multi_socket API
+ * behave properly, especially for the case when libcurl will create another
+ * socket again and it gets the same file descriptor number.
+ */
+
void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s);
-
+
/*
* Add a handle and move it into PERFORM state at once. For pushed streams.
*/
@@ -95,4 +95,4 @@ CURLMcode Curl_multi_add_perform(struct Curl_multi *multi,
/* Return the value of the CURLMOPT_MAX_CONCURRENT_STREAMS option */
unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi);
-#endif /* HEADER_CURL_MULTIIF_H */
+#endif /* HEADER_CURL_MULTIIF_H */
diff --git a/contrib/libs/curl/lib/netrc.c b/contrib/libs/curl/lib/netrc.c
index f50b76a3ee..13610bb070 100644
--- a/contrib/libs/curl/lib/netrc.c
+++ b/contrib/libs/curl/lib/netrc.c
@@ -1,65 +1,65 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
#ifndef CURL_DISABLE_NETRC
-
-#ifdef HAVE_PWD_H
-#include <pwd.h>
-#endif
-
-#include <curl/curl.h>
-#include "netrc.h"
+
+#ifdef HAVE_PWD_H
+#include <pwd.h>
+#endif
+
+#include <curl/curl.h>
+#include "netrc.h"
#include "strtok.h"
#include "strcase.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* Get user and password from .netrc when given a machine name */
-
-enum host_lookup_state {
- NOTHING,
- HOSTFOUND, /* the 'machine' keyword was found */
- HOSTVALID /* this is "our" machine! */
-};
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* Get user and password from .netrc when given a machine name */
+
+enum host_lookup_state {
+ NOTHING,
+ HOSTFOUND, /* the 'machine' keyword was found */
+ HOSTVALID /* this is "our" machine! */
+};
+
#define NETRC_FILE_MISSING 1
#define NETRC_FAILED -1
#define NETRC_SUCCESS 0
-/*
+/*
* Returns zero on success.
- */
+ */
static int parsenetrc(const char *host,
char **loginp,
char **passwordp,
bool *login_changed,
bool *password_changed,
char *netrcfile)
-{
- FILE *file;
+{
+ FILE *file;
int retcode = NETRC_FILE_MISSING;
char *login = *loginp;
char *password = *passwordp;
@@ -67,64 +67,64 @@ static int parsenetrc(const char *host,
bool login_alloc = FALSE;
bool password_alloc = FALSE;
enum host_lookup_state state = NOTHING;
-
+
char state_login = 0; /* Found a login keyword */
char state_password = 0; /* Found a password keyword */
int state_our_login = FALSE; /* With specific_login, found *our* login
name */
-
+
DEBUGASSERT(netrcfile);
-
+
file = fopen(netrcfile, FOPEN_READTEXT);
- if(file) {
- char *tok;
- char *tok_buf;
+ if(file) {
+ char *tok;
+ char *tok_buf;
bool done = FALSE;
char netrcbuffer[4096];
- int netrcbuffsize = (int)sizeof(netrcbuffer);
-
- while(!done && fgets(netrcbuffer, netrcbuffsize, file)) {
+ int netrcbuffsize = (int)sizeof(netrcbuffer);
+
+ while(!done && fgets(netrcbuffer, netrcbuffsize, file)) {
tok = strtok_r(netrcbuffer, " \t\n", &tok_buf);
if(tok && *tok == '#')
/* treat an initial hash as a comment line */
continue;
while(tok) {
-
+
if((login && *login) && (password && *password)) {
done = TRUE;
- break;
- }
-
- switch(state) {
- case NOTHING:
+ break;
+ }
+
+ switch(state) {
+ case NOTHING:
if(strcasecompare("machine", tok)) {
- /* the next tok is the machine name, this is in itself the
- delimiter that starts the stuff entered for this machine,
- after this we need to search for 'login' and
- 'password'. */
+ /* the next tok is the machine name, this is in itself the
+ delimiter that starts the stuff entered for this machine,
+ after this we need to search for 'login' and
+ 'password'. */
state = HOSTFOUND;
- }
+ }
else if(strcasecompare("default", tok)) {
state = HOSTVALID;
retcode = NETRC_SUCCESS; /* we did find our host */
}
- break;
- case HOSTFOUND:
+ break;
+ case HOSTFOUND:
if(strcasecompare(host, tok)) {
- /* and yes, this is our host! */
+ /* and yes, this is our host! */
state = HOSTVALID;
retcode = NETRC_SUCCESS; /* we did find our host */
- }
- else
- /* not our host */
+ }
+ else
+ /* not our host */
state = NOTHING;
- break;
- case HOSTVALID:
- /* we are now parsing sub-keywords concerning "our" host */
- if(state_login) {
- if(specific_login) {
+ break;
+ case HOSTVALID:
+ /* we are now parsing sub-keywords concerning "our" host */
+ if(state_login) {
+ if(specific_login) {
state_our_login = strcasecompare(login, tok);
- }
+ }
else if(!login || strcmp(login, tok)) {
if(login_alloc) {
free(login);
@@ -136,10 +136,10 @@ static int parsenetrc(const char *host,
goto out;
}
login_alloc = TRUE;
- }
+ }
state_login = 0;
- }
- else if(state_password) {
+ }
+ else if(state_password) {
if((state_our_login || !specific_login)
&& (!password || strcmp(password, tok))) {
if(password_alloc) {
@@ -152,25 +152,25 @@ static int parsenetrc(const char *host,
goto out;
}
password_alloc = TRUE;
- }
+ }
state_password = 0;
- }
+ }
else if(strcasecompare("login", tok))
state_login = 1;
else if(strcasecompare("password", tok))
state_password = 1;
else if(strcasecompare("machine", tok)) {
- /* ok, there's machine here go => */
- state = HOSTFOUND;
- state_our_login = FALSE;
- }
- break;
- } /* switch (state) */
-
- tok = strtok_r(NULL, " \t\n", &tok_buf);
- } /* while(tok) */
- } /* while fgets() */
-
+ /* ok, there's machine here go => */
+ state = HOSTFOUND;
+ state_our_login = FALSE;
+ }
+ break;
+ } /* switch (state) */
+
+ tok = strtok_r(NULL, " \t\n", &tok_buf);
+ } /* while(tok) */
+ } /* while fgets() */
+
out:
if(!retcode) {
/* success */
@@ -195,11 +195,11 @@ static int parsenetrc(const char *host,
if(password_alloc)
free(password);
}
- fclose(file);
- }
-
- return retcode;
-}
+ fclose(file);
+ }
+
+ return retcode;
+}
/*
* @unittest: 1304
diff --git a/contrib/libs/curl/lib/netrc.h b/contrib/libs/curl/lib/netrc.h
index 10d366ae0f..4938a5916a 100644
--- a/contrib/libs/curl/lib/netrc.h
+++ b/contrib/libs/curl/lib/netrc.h
@@ -1,45 +1,45 @@
-#ifndef HEADER_CURL_NETRC_H
-#define HEADER_CURL_NETRC_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_NETRC_H
+#define HEADER_CURL_NETRC_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include "curl_setup.h"
#ifndef CURL_DISABLE_NETRC
-/* returns -1 on failure, 0 if the host is found, 1 is the host isn't found */
-int Curl_parsenetrc(const char *host,
- char **loginp,
- char **passwordp,
+/* returns -1 on failure, 0 if the host is found, 1 is the host isn't found */
+int Curl_parsenetrc(const char *host,
+ char **loginp,
+ char **passwordp,
bool *login_changed,
bool *password_changed,
- char *filename);
- /* Assume: (*passwordp)[0]=0, host[0] != 0.
- * If (*loginp)[0] = 0, search for login and password within a machine
- * section in the netrc.
- * If (*loginp)[0] != 0, search for password within machine and login.
- */
+ char *filename);
+ /* Assume: (*passwordp)[0]=0, host[0] != 0.
+ * If (*loginp)[0] = 0, search for login and password within a machine
+ * section in the netrc.
+ * If (*loginp)[0] != 0, search for password within machine and login.
+ */
#else
/* disabled */
#define Curl_parsenetrc(a,b,c,d,e,f) 1
#endif
-
-#endif /* HEADER_CURL_NETRC_H */
+
+#endif /* HEADER_CURL_NETRC_H */
diff --git a/contrib/libs/curl/lib/non-ascii.c b/contrib/libs/curl/lib/non-ascii.c
index 732d656684..30c240b637 100644
--- a/contrib/libs/curl/lib/non-ascii.c
+++ b/contrib/libs/curl/lib/non-ascii.c
@@ -1,332 +1,332 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef CURL_DOES_CONVERSIONS
-
-#include <curl/curl.h>
-
-#include "non-ascii.h"
-#include "formdata.h"
-#include "sendf.h"
-#include "urldata.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef CURL_DOES_CONVERSIONS
+
+#include <curl/curl.h>
+
+#include "non-ascii.h"
+#include "formdata.h"
+#include "sendf.h"
+#include "urldata.h"
#include "multiif.h"
-
-#include "curl_memory.h"
-/* The last #include file should be: */
-#include "memdebug.h"
-
-#ifdef HAVE_ICONV
-#include <iconv.h>
-/* set default codesets for iconv */
-#ifndef CURL_ICONV_CODESET_OF_NETWORK
-#define CURL_ICONV_CODESET_OF_NETWORK "ISO8859-1"
-#endif
-#ifndef CURL_ICONV_CODESET_FOR_UTF8
-#define CURL_ICONV_CODESET_FOR_UTF8 "UTF-8"
-#endif
-#define ICONV_ERROR (size_t)-1
-#endif /* HAVE_ICONV */
-
-/*
- * Curl_convert_clone() returns a malloced copy of the source string (if
- * returning CURLE_OK), with the data converted to network format.
- */
+
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+#ifdef HAVE_ICONV
+#include <iconv.h>
+/* set default codesets for iconv */
+#ifndef CURL_ICONV_CODESET_OF_NETWORK
+#define CURL_ICONV_CODESET_OF_NETWORK "ISO8859-1"
+#endif
+#ifndef CURL_ICONV_CODESET_FOR_UTF8
+#define CURL_ICONV_CODESET_FOR_UTF8 "UTF-8"
+#endif
+#define ICONV_ERROR (size_t)-1
+#endif /* HAVE_ICONV */
+
+/*
+ * Curl_convert_clone() returns a malloced copy of the source string (if
+ * returning CURLE_OK), with the data converted to network format.
+ */
CURLcode Curl_convert_clone(struct Curl_easy *data,
- const char *indata,
- size_t insize,
- char **outbuf)
-{
- char *convbuf;
- CURLcode result;
-
- convbuf = malloc(insize);
- if(!convbuf)
- return CURLE_OUT_OF_MEMORY;
-
- memcpy(convbuf, indata, insize);
- result = Curl_convert_to_network(data, convbuf, insize);
- if(result) {
- free(convbuf);
- return result;
- }
-
- *outbuf = convbuf; /* return the converted buffer */
-
- return CURLE_OK;
-}
-
-/*
- * Curl_convert_to_network() is an internal function for performing ASCII
+ const char *indata,
+ size_t insize,
+ char **outbuf)
+{
+ char *convbuf;
+ CURLcode result;
+
+ convbuf = malloc(insize);
+ if(!convbuf)
+ return CURLE_OUT_OF_MEMORY;
+
+ memcpy(convbuf, indata, insize);
+ result = Curl_convert_to_network(data, convbuf, insize);
+ if(result) {
+ free(convbuf);
+ return result;
+ }
+
+ *outbuf = convbuf; /* return the converted buffer */
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_convert_to_network() is an internal function for performing ASCII
* conversions on non-ASCII platforms. It converts the buffer _in place_.
- */
+ */
CURLcode Curl_convert_to_network(struct Curl_easy *data,
- char *buffer, size_t length)
-{
+ char *buffer, size_t length)
+{
if(data && data->set.convtonetwork) {
- /* use translation callback */
+ /* use translation callback */
CURLcode result;
Curl_set_in_callback(data, true);
result = data->set.convtonetwork(buffer, length);
Curl_set_in_callback(data, false);
if(result) {
- failf(data,
- "CURLOPT_CONV_TO_NETWORK_FUNCTION callback returned %d: %s",
+ failf(data,
+ "CURLOPT_CONV_TO_NETWORK_FUNCTION callback returned %d: %s",
(int)result, curl_easy_strerror(result));
- }
+ }
return result;
- }
- else {
-#ifdef HAVE_ICONV
- /* do the translation ourselves */
+ }
+ else {
+#ifdef HAVE_ICONV
+ /* do the translation ourselves */
iconv_t tmpcd = (iconv_t) -1;
iconv_t *cd = &tmpcd;
- char *input_ptr, *output_ptr;
- size_t in_bytes, out_bytes, rc;
-
- /* open an iconv conversion descriptor if necessary */
+ char *input_ptr, *output_ptr;
+ size_t in_bytes, out_bytes, rc;
+
+ /* open an iconv conversion descriptor if necessary */
if(data)
cd = &data->outbound_cd;
if(*cd == (iconv_t)-1) {
*cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
CURL_ICONV_CODESET_OF_HOST);
if(*cd == (iconv_t)-1) {
- failf(data,
- "The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
- CURL_ICONV_CODESET_OF_NETWORK,
- CURL_ICONV_CODESET_OF_HOST,
+ failf(data,
+ "The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
+ CURL_ICONV_CODESET_OF_NETWORK,
+ CURL_ICONV_CODESET_OF_HOST,
errno, strerror(errno));
- return CURLE_CONV_FAILED;
- }
- }
- /* call iconv */
- input_ptr = output_ptr = buffer;
- in_bytes = out_bytes = length;
+ return CURLE_CONV_FAILED;
+ }
+ }
+ /* call iconv */
+ input_ptr = output_ptr = buffer;
+ in_bytes = out_bytes = length;
rc = iconv(*cd, &input_ptr, &in_bytes,
- &output_ptr, &out_bytes);
+ &output_ptr, &out_bytes);
if(!data)
iconv_close(tmpcd);
- if((rc == ICONV_ERROR) || (in_bytes != 0)) {
- failf(data,
- "The Curl_convert_to_network iconv call failed with errno %i: %s",
+ if((rc == ICONV_ERROR) || (in_bytes != 0)) {
+ failf(data,
+ "The Curl_convert_to_network iconv call failed with errno %i: %s",
errno, strerror(errno));
- return CURLE_CONV_FAILED;
- }
-#else
- failf(data, "CURLOPT_CONV_TO_NETWORK_FUNCTION callback required");
- return CURLE_CONV_REQD;
-#endif /* HAVE_ICONV */
- }
-
- return CURLE_OK;
-}
-
-/*
- * Curl_convert_from_network() is an internal function for performing ASCII
+ return CURLE_CONV_FAILED;
+ }
+#else
+ failf(data, "CURLOPT_CONV_TO_NETWORK_FUNCTION callback required");
+ return CURLE_CONV_REQD;
+#endif /* HAVE_ICONV */
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_convert_from_network() is an internal function for performing ASCII
* conversions on non-ASCII platforms. It converts the buffer _in place_.
- */
+ */
CURLcode Curl_convert_from_network(struct Curl_easy *data,
- char *buffer, size_t length)
-{
+ char *buffer, size_t length)
+{
if(data && data->set.convfromnetwork) {
- /* use translation callback */
+ /* use translation callback */
CURLcode result;
Curl_set_in_callback(data, true);
result = data->set.convfromnetwork(buffer, length);
Curl_set_in_callback(data, false);
if(result) {
- failf(data,
- "CURLOPT_CONV_FROM_NETWORK_FUNCTION callback returned %d: %s",
+ failf(data,
+ "CURLOPT_CONV_FROM_NETWORK_FUNCTION callback returned %d: %s",
(int)result, curl_easy_strerror(result));
- }
+ }
return result;
- }
- else {
-#ifdef HAVE_ICONV
- /* do the translation ourselves */
+ }
+ else {
+#ifdef HAVE_ICONV
+ /* do the translation ourselves */
iconv_t tmpcd = (iconv_t) -1;
iconv_t *cd = &tmpcd;
- char *input_ptr, *output_ptr;
- size_t in_bytes, out_bytes, rc;
-
- /* open an iconv conversion descriptor if necessary */
+ char *input_ptr, *output_ptr;
+ size_t in_bytes, out_bytes, rc;
+
+ /* open an iconv conversion descriptor if necessary */
if(data)
cd = &data->inbound_cd;
if(*cd == (iconv_t)-1) {
*cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_OF_NETWORK);
if(*cd == (iconv_t)-1) {
- failf(data,
- "The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
- CURL_ICONV_CODESET_OF_HOST,
- CURL_ICONV_CODESET_OF_NETWORK,
+ failf(data,
+ "The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
+ CURL_ICONV_CODESET_OF_HOST,
+ CURL_ICONV_CODESET_OF_NETWORK,
errno, strerror(errno));
- return CURLE_CONV_FAILED;
- }
- }
- /* call iconv */
- input_ptr = output_ptr = buffer;
- in_bytes = out_bytes = length;
+ return CURLE_CONV_FAILED;
+ }
+ }
+ /* call iconv */
+ input_ptr = output_ptr = buffer;
+ in_bytes = out_bytes = length;
rc = iconv(*cd, &input_ptr, &in_bytes,
- &output_ptr, &out_bytes);
+ &output_ptr, &out_bytes);
if(!data)
iconv_close(tmpcd);
- if((rc == ICONV_ERROR) || (in_bytes != 0)) {
- failf(data,
- "Curl_convert_from_network iconv call failed with errno %i: %s",
+ if((rc == ICONV_ERROR) || (in_bytes != 0)) {
+ failf(data,
+ "Curl_convert_from_network iconv call failed with errno %i: %s",
errno, strerror(errno));
- return CURLE_CONV_FAILED;
- }
-#else
- failf(data, "CURLOPT_CONV_FROM_NETWORK_FUNCTION callback required");
- return CURLE_CONV_REQD;
-#endif /* HAVE_ICONV */
- }
-
- return CURLE_OK;
-}
-
-/*
- * Curl_convert_from_utf8() is an internal function for performing UTF-8
- * conversions on non-ASCII platforms.
- */
+ return CURLE_CONV_FAILED;
+ }
+#else
+ failf(data, "CURLOPT_CONV_FROM_NETWORK_FUNCTION callback required");
+ return CURLE_CONV_REQD;
+#endif /* HAVE_ICONV */
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_convert_from_utf8() is an internal function for performing UTF-8
+ * conversions on non-ASCII platforms.
+ */
CURLcode Curl_convert_from_utf8(struct Curl_easy *data,
- char *buffer, size_t length)
-{
+ char *buffer, size_t length)
+{
if(data && data->set.convfromutf8) {
- /* use translation callback */
+ /* use translation callback */
CURLcode result;
Curl_set_in_callback(data, true);
result = data->set.convfromutf8(buffer, length);
Curl_set_in_callback(data, false);
if(result) {
- failf(data,
- "CURLOPT_CONV_FROM_UTF8_FUNCTION callback returned %d: %s",
+ failf(data,
+ "CURLOPT_CONV_FROM_UTF8_FUNCTION callback returned %d: %s",
(int)result, curl_easy_strerror(result));
- }
+ }
return result;
- }
- else {
-#ifdef HAVE_ICONV
- /* do the translation ourselves */
+ }
+ else {
+#ifdef HAVE_ICONV
+ /* do the translation ourselves */
iconv_t tmpcd = (iconv_t) -1;
iconv_t *cd = &tmpcd;
char *input_ptr;
- char *output_ptr;
- size_t in_bytes, out_bytes, rc;
-
- /* open an iconv conversion descriptor if necessary */
+ char *output_ptr;
+ size_t in_bytes, out_bytes, rc;
+
+ /* open an iconv conversion descriptor if necessary */
if(data)
cd = &data->utf8_cd;
if(*cd == (iconv_t)-1) {
*cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_FOR_UTF8);
if(*cd == (iconv_t)-1) {
- failf(data,
- "The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
- CURL_ICONV_CODESET_OF_HOST,
- CURL_ICONV_CODESET_FOR_UTF8,
+ failf(data,
+ "The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
+ CURL_ICONV_CODESET_OF_HOST,
+ CURL_ICONV_CODESET_FOR_UTF8,
errno, strerror(errno));
- return CURLE_CONV_FAILED;
- }
- }
- /* call iconv */
- input_ptr = output_ptr = buffer;
- in_bytes = out_bytes = length;
+ return CURLE_CONV_FAILED;
+ }
+ }
+ /* call iconv */
+ input_ptr = output_ptr = buffer;
+ in_bytes = out_bytes = length;
rc = iconv(*cd, &input_ptr, &in_bytes,
- &output_ptr, &out_bytes);
+ &output_ptr, &out_bytes);
if(!data)
iconv_close(tmpcd);
- if((rc == ICONV_ERROR) || (in_bytes != 0)) {
- failf(data,
- "The Curl_convert_from_utf8 iconv call failed with errno %i: %s",
+ if((rc == ICONV_ERROR) || (in_bytes != 0)) {
+ failf(data,
+ "The Curl_convert_from_utf8 iconv call failed with errno %i: %s",
errno, strerror(errno));
- return CURLE_CONV_FAILED;
- }
- if(output_ptr < input_ptr) {
- /* null terminate the now shorter output string */
- *output_ptr = 0x00;
- }
-#else
- failf(data, "CURLOPT_CONV_FROM_UTF8_FUNCTION callback required");
- return CURLE_CONV_REQD;
-#endif /* HAVE_ICONV */
- }
-
- return CURLE_OK;
-}
-
-/*
+ return CURLE_CONV_FAILED;
+ }
+ if(output_ptr < input_ptr) {
+ /* null terminate the now shorter output string */
+ *output_ptr = 0x00;
+ }
+#else
+ failf(data, "CURLOPT_CONV_FROM_UTF8_FUNCTION callback required");
+ return CURLE_CONV_REQD;
+#endif /* HAVE_ICONV */
+ }
+
+ return CURLE_OK;
+}
+
+/*
* Init conversion stuff for a Curl_easy
- */
+ */
void Curl_convert_init(struct Curl_easy *data)
-{
-#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
- /* conversion descriptors for iconv calls */
- data->outbound_cd = (iconv_t)-1;
- data->inbound_cd = (iconv_t)-1;
- data->utf8_cd = (iconv_t)-1;
-#else
- (void)data;
-#endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
-}
-
-/*
+{
+#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
+ /* conversion descriptors for iconv calls */
+ data->outbound_cd = (iconv_t)-1;
+ data->inbound_cd = (iconv_t)-1;
+ data->utf8_cd = (iconv_t)-1;
+#else
+ (void)data;
+#endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
+}
+
+/*
* Setup conversion stuff for a Curl_easy
- */
+ */
void Curl_convert_setup(struct Curl_easy *data)
-{
- data->inbound_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
- CURL_ICONV_CODESET_OF_NETWORK);
- data->outbound_cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
- CURL_ICONV_CODESET_OF_HOST);
- data->utf8_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
- CURL_ICONV_CODESET_FOR_UTF8);
-}
-
-/*
+{
+ data->inbound_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
+ CURL_ICONV_CODESET_OF_NETWORK);
+ data->outbound_cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
+ CURL_ICONV_CODESET_OF_HOST);
+ data->utf8_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
+ CURL_ICONV_CODESET_FOR_UTF8);
+}
+
+/*
* Close conversion stuff for a Curl_easy
- */
-
+ */
+
void Curl_convert_close(struct Curl_easy *data)
-{
-#ifdef HAVE_ICONV
- /* close iconv conversion descriptors */
- if(data->inbound_cd != (iconv_t)-1) {
- iconv_close(data->inbound_cd);
- }
- if(data->outbound_cd != (iconv_t)-1) {
- iconv_close(data->outbound_cd);
- }
- if(data->utf8_cd != (iconv_t)-1) {
- iconv_close(data->utf8_cd);
- }
-#else
- (void)data;
-#endif /* HAVE_ICONV */
-}
-
-#endif /* CURL_DOES_CONVERSIONS */
+{
+#ifdef HAVE_ICONV
+ /* close iconv conversion descriptors */
+ if(data->inbound_cd != (iconv_t)-1) {
+ iconv_close(data->inbound_cd);
+ }
+ if(data->outbound_cd != (iconv_t)-1) {
+ iconv_close(data->outbound_cd);
+ }
+ if(data->utf8_cd != (iconv_t)-1) {
+ iconv_close(data->utf8_cd);
+ }
+#else
+ (void)data;
+#endif /* HAVE_ICONV */
+}
+
+#endif /* CURL_DOES_CONVERSIONS */
diff --git a/contrib/libs/curl/lib/non-ascii.h b/contrib/libs/curl/lib/non-ascii.h
index 56f3507dd0..458e8ef091 100644
--- a/contrib/libs/curl/lib/non-ascii.h
+++ b/contrib/libs/curl/lib/non-ascii.h
@@ -1,61 +1,61 @@
-#ifndef HEADER_CURL_NON_ASCII_H
-#define HEADER_CURL_NON_ASCII_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_NON_ASCII_H
+#define HEADER_CURL_NON_ASCII_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#ifdef CURL_DOES_CONVERSIONS
-
-#include "urldata.h"
-
-/*
- * Curl_convert_clone() returns a malloced copy of the source string (if
- * returning CURLE_OK), with the data converted to network format.
- *
- * If no conversion was needed *outbuf may be NULL.
- */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#ifdef CURL_DOES_CONVERSIONS
+
+#include "urldata.h"
+
+/*
+ * Curl_convert_clone() returns a malloced copy of the source string (if
+ * returning CURLE_OK), with the data converted to network format.
+ *
+ * If no conversion was needed *outbuf may be NULL.
+ */
CURLcode Curl_convert_clone(struct Curl_easy *data,
- const char *indata,
- size_t insize,
- char **outbuf);
-
+ const char *indata,
+ size_t insize,
+ char **outbuf);
+
void Curl_convert_init(struct Curl_easy *data);
void Curl_convert_setup(struct Curl_easy *data);
void Curl_convert_close(struct Curl_easy *data);
-
+
CURLcode Curl_convert_to_network(struct Curl_easy *data,
- char *buffer, size_t length);
+ char *buffer, size_t length);
CURLcode Curl_convert_from_network(struct Curl_easy *data,
- char *buffer, size_t length);
+ char *buffer, size_t length);
CURLcode Curl_convert_from_utf8(struct Curl_easy *data,
- char *buffer, size_t length);
-#else
-#define Curl_convert_clone(a,b,c,d) ((void)a, CURLE_OK)
-#define Curl_convert_init(x) Curl_nop_stmt
-#define Curl_convert_setup(x) Curl_nop_stmt
-#define Curl_convert_close(x) Curl_nop_stmt
-#define Curl_convert_to_network(a,b,c) ((void)a, CURLE_OK)
-#define Curl_convert_from_network(a,b,c) ((void)a, CURLE_OK)
-#define Curl_convert_from_utf8(a,b,c) ((void)a, CURLE_OK)
-#endif
-
-#endif /* HEADER_CURL_NON_ASCII_H */
+ char *buffer, size_t length);
+#else
+#define Curl_convert_clone(a,b,c,d) ((void)a, CURLE_OK)
+#define Curl_convert_init(x) Curl_nop_stmt
+#define Curl_convert_setup(x) Curl_nop_stmt
+#define Curl_convert_close(x) Curl_nop_stmt
+#define Curl_convert_to_network(a,b,c) ((void)a, CURLE_OK)
+#define Curl_convert_from_network(a,b,c) ((void)a, CURLE_OK)
+#define Curl_convert_from_utf8(a,b,c) ((void)a, CURLE_OK)
+#endif
+
+#endif /* HEADER_CURL_NON_ASCII_H */
diff --git a/contrib/libs/curl/lib/nonblock.c b/contrib/libs/curl/lib/nonblock.c
index 6fe2ef6df6..4a7bde504f 100644
--- a/contrib/libs/curl/lib/nonblock.c
+++ b/contrib/libs/curl/lib/nonblock.c
@@ -1,91 +1,91 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-
-#if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
-#include <sys/filio.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#include "nonblock.h"
-
-/*
- * curlx_nonblock() set the given socket to either blocking or non-blocking
- * mode based on the 'nonblock' boolean argument. This function is highly
- * portable.
- */
-int curlx_nonblock(curl_socket_t sockfd, /* operate on this */
- int nonblock /* TRUE or FALSE */)
-{
-#if defined(USE_BLOCKING_SOCKETS)
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
+#include <sys/filio.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#include "nonblock.h"
+
+/*
+ * curlx_nonblock() set the given socket to either blocking or non-blocking
+ * mode based on the 'nonblock' boolean argument. This function is highly
+ * portable.
+ */
+int curlx_nonblock(curl_socket_t sockfd, /* operate on this */
+ int nonblock /* TRUE or FALSE */)
+{
+#if defined(USE_BLOCKING_SOCKETS)
(void)sockfd;
(void)nonblock;
- return 0; /* returns success */
-
-#elif defined(HAVE_FCNTL_O_NONBLOCK)
-
- /* most recent unix versions */
- int flags;
- flags = sfcntl(sockfd, F_GETFL, 0);
- if(nonblock)
- return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
+ return 0; /* returns success */
+
+#elif defined(HAVE_FCNTL_O_NONBLOCK)
+
+ /* most recent unix versions */
+ int flags;
+ flags = sfcntl(sockfd, F_GETFL, 0);
+ if(nonblock)
+ return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
return sfcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
-
-#elif defined(HAVE_IOCTL_FIONBIO)
-
- /* older unix versions */
- int flags = nonblock ? 1 : 0;
- return ioctl(sockfd, FIONBIO, &flags);
-
-#elif defined(HAVE_IOCTLSOCKET_FIONBIO)
-
- /* Windows */
- unsigned long flags = nonblock ? 1UL : 0UL;
- return ioctlsocket(sockfd, FIONBIO, &flags);
-
-#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
-
- /* Amiga */
- long flags = nonblock ? 1L : 0L;
+
+#elif defined(HAVE_IOCTL_FIONBIO)
+
+ /* older unix versions */
+ int flags = nonblock ? 1 : 0;
+ return ioctl(sockfd, FIONBIO, &flags);
+
+#elif defined(HAVE_IOCTLSOCKET_FIONBIO)
+
+ /* Windows */
+ unsigned long flags = nonblock ? 1UL : 0UL;
+ return ioctlsocket(sockfd, FIONBIO, &flags);
+
+#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
+
+ /* Amiga */
+ long flags = nonblock ? 1L : 0L;
return IoctlSocket(sockfd, FIONBIO, (char *)&flags);
-
-#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
-
- /* BeOS */
- long b = nonblock ? 1L : 0L;
- return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
-
-#else
-# error "no non-blocking method was found/used/set"
-#endif
-}
+
+#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
+
+ /* BeOS */
+ long b = nonblock ? 1L : 0L;
+ return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
+
+#else
+# error "no non-blocking method was found/used/set"
+#endif
+}
diff --git a/contrib/libs/curl/lib/nonblock.h b/contrib/libs/curl/lib/nonblock.h
index 2ecd407f4e..761dab4f6d 100644
--- a/contrib/libs/curl/lib/nonblock.h
+++ b/contrib/libs/curl/lib/nonblock.h
@@ -1,30 +1,30 @@
-#ifndef HEADER_CURL_NONBLOCK_H
-#define HEADER_CURL_NONBLOCK_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_NONBLOCK_H
+#define HEADER_CURL_NONBLOCK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <curl/curl.h> /* for curl_socket_t */
-
-int curlx_nonblock(curl_socket_t sockfd, /* operate on this */
- int nonblock /* TRUE or FALSE */);
-
-#endif /* HEADER_CURL_NONBLOCK_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <curl/curl.h> /* for curl_socket_t */
+
+int curlx_nonblock(curl_socket_t sockfd, /* operate on this */
+ int nonblock /* TRUE or FALSE */);
+
+#endif /* HEADER_CURL_NONBLOCK_H */
diff --git a/contrib/libs/curl/lib/openldap.c b/contrib/libs/curl/lib/openldap.c
index 6263d138fe..f8e3150308 100644
--- a/contrib/libs/curl/lib/openldap.c
+++ b/contrib/libs/curl/lib/openldap.c
@@ -1,56 +1,56 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
- * Copyright (C) 2010, Howard Chu, <hyc@openldap.org>
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2010, Howard Chu, <hyc@openldap.org>
* Copyright (C) 2011 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if !defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)
-
-/*
- * Notice that USE_OPENLDAP is only a source code selection switch. When
- * libcurl is built with USE_OPENLDAP defined the libcurl source code that
- * gets compiled is the code from openldap.c, otherwise the code that gets
- * compiled is the code from ldap.c.
- *
- * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
- * might be required for compilation and runtime. In order to use ancient
- * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
- */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)
+
+/*
+ * Notice that USE_OPENLDAP is only a source code selection switch. When
+ * libcurl is built with USE_OPENLDAP defined the libcurl source code that
+ * gets compiled is the code from openldap.c, otherwise the code that gets
+ * compiled is the code from ldap.c.
+ *
+ * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
+ * might be required for compilation and runtime. In order to use ancient
+ * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
+ */
+
#error #include <ldap.h>
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "sendf.h"
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "sendf.h"
#include "vtls/vtls.h"
-#include "transfer.h"
-#include "curl_ldap.h"
+#include "transfer.h"
+#include "curl_ldap.h"
#include "curl_base64.h"
#include "connect.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
+#include "curl_memory.h"
#include "memdebug.h"
-
+
/*
* Uncommenting this will enable the built-in debug logging of the openldap
* library. The debug log level can be set using the CURL_OPENLDAP_TRACE
@@ -69,159 +69,159 @@
* CURL_OPENLDAP_TRACE=65535 for all debug message levels.
*/
/* #define CURL_OPENLDAP_DEBUG */
-
-#ifndef _LDAP_PVT_H
-extern int ldap_pvt_url_scheme2proto(const char *);
-extern int ldap_init_fd(ber_socket_t fd, int proto, const char *url,
- LDAP **ld);
-#endif
-
+
+#ifndef _LDAP_PVT_H
+extern int ldap_pvt_url_scheme2proto(const char *);
+extern int ldap_init_fd(ber_socket_t fd, int proto, const char *url,
+ LDAP **ld);
+#endif
+
static CURLcode ldap_setup_connection(struct connectdata *conn);
-static CURLcode ldap_do(struct connectdata *conn, bool *done);
-static CURLcode ldap_done(struct connectdata *conn, CURLcode, bool);
-static CURLcode ldap_connect(struct connectdata *conn, bool *done);
-static CURLcode ldap_connecting(struct connectdata *conn, bool *done);
-static CURLcode ldap_disconnect(struct connectdata *conn, bool dead);
-
-static Curl_recv ldap_recv;
-
-/*
- * LDAP protocol handler.
- */
-
-const struct Curl_handler Curl_handler_ldap = {
- "LDAP", /* scheme */
+static CURLcode ldap_do(struct connectdata *conn, bool *done);
+static CURLcode ldap_done(struct connectdata *conn, CURLcode, bool);
+static CURLcode ldap_connect(struct connectdata *conn, bool *done);
+static CURLcode ldap_connecting(struct connectdata *conn, bool *done);
+static CURLcode ldap_disconnect(struct connectdata *conn, bool dead);
+
+static Curl_recv ldap_recv;
+
+/*
+ * LDAP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_ldap = {
+ "LDAP", /* scheme */
ldap_setup_connection, /* setup_connection */
- ldap_do, /* do_it */
- ldap_done, /* done */
- ZERO_NULL, /* do_more */
- ldap_connect, /* connect_it */
- ldap_connecting, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ldap_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ ldap_do, /* do_it */
+ ldap_done, /* done */
+ ZERO_NULL, /* do_more */
+ ldap_connect, /* connect_it */
+ ldap_connecting, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ldap_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_LDAP, /* defport */
- CURLPROTO_LDAP, /* protocol */
+ PORT_LDAP, /* defport */
+ CURLPROTO_LDAP, /* protocol */
CURLPROTO_LDAP, /* family */
- PROTOPT_NONE /* flags */
-};
-
-#ifdef USE_SSL
-/*
- * LDAPS protocol handler.
- */
-
-const struct Curl_handler Curl_handler_ldaps = {
- "LDAPS", /* scheme */
+ PROTOPT_NONE /* flags */
+};
+
+#ifdef USE_SSL
+/*
+ * LDAPS protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_ldaps = {
+ "LDAPS", /* scheme */
ldap_setup_connection, /* setup_connection */
- ldap_do, /* do_it */
- ldap_done, /* done */
- ZERO_NULL, /* do_more */
- ldap_connect, /* connect_it */
- ldap_connecting, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ldap_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+ ldap_do, /* do_it */
+ ldap_done, /* done */
+ ZERO_NULL, /* do_more */
+ ldap_connect, /* connect_it */
+ ldap_connecting, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ldap_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_LDAPS, /* defport */
+ PORT_LDAPS, /* defport */
CURLPROTO_LDAPS, /* protocol */
CURLPROTO_LDAP, /* family */
- PROTOPT_SSL /* flags */
-};
-#endif
-
-static const char *url_errs[] = {
- "success",
- "out of memory",
- "bad parameter",
- "unrecognized scheme",
- "unbalanced delimiter",
- "bad URL",
- "bad host or port",
- "bad or missing attributes",
- "bad or missing scope",
- "bad or missing filter",
- "bad or missing extensions"
-};
-
+ PROTOPT_SSL /* flags */
+};
+#endif
+
+static const char *url_errs[] = {
+ "success",
+ "out of memory",
+ "bad parameter",
+ "unrecognized scheme",
+ "unbalanced delimiter",
+ "bad URL",
+ "bad host or port",
+ "bad or missing attributes",
+ "bad or missing scope",
+ "bad or missing filter",
+ "bad or missing extensions"
+};
+
struct ldapconninfo {
- LDAP *ld;
- Curl_recv *recv; /* for stacking SSL handler */
- Curl_send *send;
- int proto;
- int msgid;
- bool ssldone;
- bool sslinst;
- bool didbind;
+ LDAP *ld;
+ Curl_recv *recv; /* for stacking SSL handler */
+ Curl_send *send;
+ int proto;
+ int msgid;
+ bool ssldone;
+ bool sslinst;
+ bool didbind;
};
-
+
struct ldapreqinfo {
- int msgid;
- int nument;
+ int msgid;
+ int nument;
};
-
+
static CURLcode ldap_setup_connection(struct connectdata *conn)
-{
+{
struct ldapconninfo *li;
- LDAPURLDesc *lud;
+ LDAPURLDesc *lud;
struct Curl_easy *data = conn->data;
- int rc, proto;
- CURLcode status;
-
- rc = ldap_url_parse(data->change.url, &lud);
- if(rc != LDAP_URL_SUCCESS) {
- const char *msg = "url parsing problem";
- status = CURLE_URL_MALFORMAT;
- if(rc > LDAP_URL_SUCCESS && rc <= LDAP_URL_ERR_BADEXTS) {
- if(rc == LDAP_URL_ERR_MEM)
- status = CURLE_OUT_OF_MEMORY;
- msg = url_errs[rc];
- }
- failf(conn->data, "LDAP local: %s", msg);
- return status;
- }
- proto = ldap_pvt_url_scheme2proto(lud->lud_scheme);
- ldap_free_urldesc(lud);
-
+ int rc, proto;
+ CURLcode status;
+
+ rc = ldap_url_parse(data->change.url, &lud);
+ if(rc != LDAP_URL_SUCCESS) {
+ const char *msg = "url parsing problem";
+ status = CURLE_URL_MALFORMAT;
+ if(rc > LDAP_URL_SUCCESS && rc <= LDAP_URL_ERR_BADEXTS) {
+ if(rc == LDAP_URL_ERR_MEM)
+ status = CURLE_OUT_OF_MEMORY;
+ msg = url_errs[rc];
+ }
+ failf(conn->data, "LDAP local: %s", msg);
+ return status;
+ }
+ proto = ldap_pvt_url_scheme2proto(lud->lud_scheme);
+ ldap_free_urldesc(lud);
+
li = calloc(1, sizeof(struct ldapconninfo));
- if(!li)
- return CURLE_OUT_OF_MEMORY;
- li->proto = proto;
+ if(!li)
+ return CURLE_OUT_OF_MEMORY;
+ li->proto = proto;
conn->proto.ldapc = li;
connkeep(conn, "OpenLDAP default");
- return CURLE_OK;
-}
-
-#ifdef USE_SSL
-static Sockbuf_IO ldapsb_tls;
-#endif
-
-static CURLcode ldap_connect(struct connectdata *conn, bool *done)
-{
+ return CURLE_OK;
+}
+
+#ifdef USE_SSL
+static Sockbuf_IO ldapsb_tls;
+#endif
+
+static CURLcode ldap_connect(struct connectdata *conn, bool *done)
+{
struct ldapconninfo *li = conn->proto.ldapc;
struct Curl_easy *data = conn->data;
- int rc, proto = LDAP_VERSION3;
+ int rc, proto = LDAP_VERSION3;
char hosturl[1024];
char *ptr;
- (void)done;
-
- strcpy(hosturl, "ldap");
+ (void)done;
+
+ strcpy(hosturl, "ldap");
ptr = hosturl + 4;
- if(conn->handler->flags & PROTOPT_SSL)
- *ptr++ = 's';
+ if(conn->handler->flags & PROTOPT_SSL)
+ *ptr++ = 's';
msnprintf(ptr, sizeof(hosturl)-(ptr-hosturl), "://%s:%d",
conn->host.name, conn->remote_port);
-
+
#ifdef CURL_OPENLDAP_DEBUG
static int do_trace = 0;
const char *env = getenv("CURL_OPENLDAP_TRACE");
@@ -231,287 +231,287 @@ static CURLcode ldap_connect(struct connectdata *conn, bool *done)
}
#endif
- rc = ldap_init_fd(conn->sock[FIRSTSOCKET], li->proto, hosturl, &li->ld);
- if(rc) {
- failf(data, "LDAP local: Cannot connect to %s, %s",
- hosturl, ldap_err2string(rc));
- return CURLE_COULDNT_CONNECT;
- }
-
- ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
-
-#ifdef USE_SSL
- if(conn->handler->flags & PROTOPT_SSL) {
+ rc = ldap_init_fd(conn->sock[FIRSTSOCKET], li->proto, hosturl, &li->ld);
+ if(rc) {
+ failf(data, "LDAP local: Cannot connect to %s, %s",
+ hosturl, ldap_err2string(rc));
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
+
+#ifdef USE_SSL
+ if(conn->handler->flags & PROTOPT_SSL) {
CURLcode result;
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &li->ssldone);
if(result)
return result;
- }
-#endif
-
- return CURLE_OK;
-}
-
-static CURLcode ldap_connecting(struct connectdata *conn, bool *done)
-{
+ }
+#endif
+
+ return CURLE_OK;
+}
+
+static CURLcode ldap_connecting(struct connectdata *conn, bool *done)
+{
struct ldapconninfo *li = conn->proto.ldapc;
struct Curl_easy *data = conn->data;
LDAPMessage *msg = NULL;
struct timeval tv = {0, 1}, *tvp;
- int rc, err;
- char *info = NULL;
-
-#ifdef USE_SSL
- if(conn->handler->flags & PROTOPT_SSL) {
- /* Is the SSL handshake complete yet? */
- if(!li->ssldone) {
+ int rc, err;
+ char *info = NULL;
+
+#ifdef USE_SSL
+ if(conn->handler->flags & PROTOPT_SSL) {
+ /* Is the SSL handshake complete yet? */
+ if(!li->ssldone) {
CURLcode result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET,
&li->ssldone);
if(result || !li->ssldone)
return result;
- }
-
- /* Have we installed the libcurl SSL handlers into the sockbuf yet? */
- if(!li->sslinst) {
- Sockbuf *sb;
- ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb);
- ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, conn);
- li->sslinst = TRUE;
- li->recv = conn->recv[FIRSTSOCKET];
- li->send = conn->send[FIRSTSOCKET];
- }
- }
-#endif
-
- tvp = &tv;
-
+ }
+
+ /* Have we installed the libcurl SSL handlers into the sockbuf yet? */
+ if(!li->sslinst) {
+ Sockbuf *sb;
+ ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb);
+ ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, conn);
+ li->sslinst = TRUE;
+ li->recv = conn->recv[FIRSTSOCKET];
+ li->send = conn->send[FIRSTSOCKET];
+ }
+ }
+#endif
+
+ tvp = &tv;
+
retry:
- if(!li->didbind) {
- char *binddn;
- struct berval passwd;
-
- if(conn->bits.user_passwd) {
- binddn = conn->user;
- passwd.bv_val = conn->passwd;
- passwd.bv_len = strlen(passwd.bv_val);
- }
- else {
- binddn = NULL;
- passwd.bv_val = NULL;
- passwd.bv_len = 0;
- }
- rc = ldap_sasl_bind(li->ld, binddn, LDAP_SASL_SIMPLE, &passwd,
- NULL, NULL, &li->msgid);
- if(rc)
- return CURLE_LDAP_CANNOT_BIND;
- li->didbind = TRUE;
- if(tvp)
- return CURLE_OK;
- }
-
+ if(!li->didbind) {
+ char *binddn;
+ struct berval passwd;
+
+ if(conn->bits.user_passwd) {
+ binddn = conn->user;
+ passwd.bv_val = conn->passwd;
+ passwd.bv_len = strlen(passwd.bv_val);
+ }
+ else {
+ binddn = NULL;
+ passwd.bv_val = NULL;
+ passwd.bv_len = 0;
+ }
+ rc = ldap_sasl_bind(li->ld, binddn, LDAP_SASL_SIMPLE, &passwd,
+ NULL, NULL, &li->msgid);
+ if(rc)
+ return CURLE_LDAP_CANNOT_BIND;
+ li->didbind = TRUE;
+ if(tvp)
+ return CURLE_OK;
+ }
+
rc = ldap_result(li->ld, li->msgid, LDAP_MSG_ONE, tvp, &msg);
- if(rc < 0) {
- failf(data, "LDAP local: bind ldap_result %s", ldap_err2string(rc));
- return CURLE_LDAP_CANNOT_BIND;
- }
- if(rc == 0) {
- /* timed out */
- return CURLE_OK;
- }
+ if(rc < 0) {
+ failf(data, "LDAP local: bind ldap_result %s", ldap_err2string(rc));
+ return CURLE_LDAP_CANNOT_BIND;
+ }
+ if(rc == 0) {
+ /* timed out */
+ return CURLE_OK;
+ }
rc = ldap_parse_result(li->ld, msg, &err, NULL, &info, NULL, NULL, 1);
- if(rc) {
- failf(data, "LDAP local: bind ldap_parse_result %s", ldap_err2string(rc));
- return CURLE_LDAP_CANNOT_BIND;
- }
-
- /* Try to fallback to LDAPv2? */
- if(err == LDAP_PROTOCOL_ERROR) {
- int proto;
- ldap_get_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
- if(proto == LDAP_VERSION3) {
- if(info) {
- ldap_memfree(info);
- info = NULL;
- }
- proto = LDAP_VERSION2;
- ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
- li->didbind = FALSE;
- goto retry;
- }
- }
-
- if(err) {
- failf(data, "LDAP remote: bind failed %s %s", ldap_err2string(rc),
- info ? info : "");
- if(info)
- ldap_memfree(info);
- return CURLE_LOGIN_DENIED;
- }
-
- if(info)
- ldap_memfree(info);
- conn->recv[FIRSTSOCKET] = ldap_recv;
- *done = TRUE;
-
- return CURLE_OK;
-}
-
-static CURLcode ldap_disconnect(struct connectdata *conn, bool dead_connection)
-{
+ if(rc) {
+ failf(data, "LDAP local: bind ldap_parse_result %s", ldap_err2string(rc));
+ return CURLE_LDAP_CANNOT_BIND;
+ }
+
+ /* Try to fallback to LDAPv2? */
+ if(err == LDAP_PROTOCOL_ERROR) {
+ int proto;
+ ldap_get_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
+ if(proto == LDAP_VERSION3) {
+ if(info) {
+ ldap_memfree(info);
+ info = NULL;
+ }
+ proto = LDAP_VERSION2;
+ ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
+ li->didbind = FALSE;
+ goto retry;
+ }
+ }
+
+ if(err) {
+ failf(data, "LDAP remote: bind failed %s %s", ldap_err2string(rc),
+ info ? info : "");
+ if(info)
+ ldap_memfree(info);
+ return CURLE_LOGIN_DENIED;
+ }
+
+ if(info)
+ ldap_memfree(info);
+ conn->recv[FIRSTSOCKET] = ldap_recv;
+ *done = TRUE;
+
+ return CURLE_OK;
+}
+
+static CURLcode ldap_disconnect(struct connectdata *conn, bool dead_connection)
+{
struct ldapconninfo *li = conn->proto.ldapc;
- (void) dead_connection;
-
- if(li) {
- if(li->ld) {
- ldap_unbind_ext(li->ld, NULL, NULL);
- li->ld = NULL;
- }
+ (void) dead_connection;
+
+ if(li) {
+ if(li->ld) {
+ ldap_unbind_ext(li->ld, NULL, NULL);
+ li->ld = NULL;
+ }
conn->proto.ldapc = NULL;
- free(li);
- }
- return CURLE_OK;
-}
-
-static CURLcode ldap_do(struct connectdata *conn, bool *done)
-{
+ free(li);
+ }
+ return CURLE_OK;
+}
+
+static CURLcode ldap_do(struct connectdata *conn, bool *done)
+{
struct ldapconninfo *li = conn->proto.ldapc;
struct ldapreqinfo *lr;
- CURLcode status = CURLE_OK;
- int rc = 0;
- LDAPURLDesc *ludp = NULL;
- int msgid;
+ CURLcode status = CURLE_OK;
+ int rc = 0;
+ LDAPURLDesc *ludp = NULL;
+ int msgid;
struct Curl_easy *data = conn->data;
-
+
connkeep(conn, "OpenLDAP do");
-
- infof(data, "LDAP local: %s\n", data->change.url);
-
- rc = ldap_url_parse(data->change.url, &ludp);
- if(rc != LDAP_URL_SUCCESS) {
- const char *msg = "url parsing problem";
- status = CURLE_URL_MALFORMAT;
- if(rc > LDAP_URL_SUCCESS && rc <= LDAP_URL_ERR_BADEXTS) {
- if(rc == LDAP_URL_ERR_MEM)
- status = CURLE_OUT_OF_MEMORY;
- msg = url_errs[rc];
- }
- failf(conn->data, "LDAP local: %s", msg);
- return status;
- }
-
- rc = ldap_search_ext(li->ld, ludp->lud_dn, ludp->lud_scope,
- ludp->lud_filter, ludp->lud_attrs, 0,
- NULL, NULL, NULL, 0, &msgid);
- ldap_free_urldesc(ludp);
- if(rc != LDAP_SUCCESS) {
- failf(data, "LDAP local: ldap_search_ext %s", ldap_err2string(rc));
- return CURLE_LDAP_SEARCH_FAILED;
- }
+
+ infof(data, "LDAP local: %s\n", data->change.url);
+
+ rc = ldap_url_parse(data->change.url, &ludp);
+ if(rc != LDAP_URL_SUCCESS) {
+ const char *msg = "url parsing problem";
+ status = CURLE_URL_MALFORMAT;
+ if(rc > LDAP_URL_SUCCESS && rc <= LDAP_URL_ERR_BADEXTS) {
+ if(rc == LDAP_URL_ERR_MEM)
+ status = CURLE_OUT_OF_MEMORY;
+ msg = url_errs[rc];
+ }
+ failf(conn->data, "LDAP local: %s", msg);
+ return status;
+ }
+
+ rc = ldap_search_ext(li->ld, ludp->lud_dn, ludp->lud_scope,
+ ludp->lud_filter, ludp->lud_attrs, 0,
+ NULL, NULL, NULL, 0, &msgid);
+ ldap_free_urldesc(ludp);
+ if(rc != LDAP_SUCCESS) {
+ failf(data, "LDAP local: ldap_search_ext %s", ldap_err2string(rc));
+ return CURLE_LDAP_SEARCH_FAILED;
+ }
lr = calloc(1, sizeof(struct ldapreqinfo));
- if(!lr)
- return CURLE_OUT_OF_MEMORY;
- lr->msgid = msgid;
+ if(!lr)
+ return CURLE_OUT_OF_MEMORY;
+ lr->msgid = msgid;
data->req.p.ldap = lr;
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
- *done = TRUE;
- return CURLE_OK;
-}
-
-static CURLcode ldap_done(struct connectdata *conn, CURLcode res,
- bool premature)
-{
+ *done = TRUE;
+ return CURLE_OK;
+}
+
+static CURLcode ldap_done(struct connectdata *conn, CURLcode res,
+ bool premature)
+{
struct ldapreqinfo *lr = conn->data->req.p.ldap;
- (void)res;
- (void)premature;
-
- if(lr) {
- /* if there was a search in progress, abandon it */
- if(lr->msgid) {
+ (void)res;
+ (void)premature;
+
+ if(lr) {
+ /* if there was a search in progress, abandon it */
+ if(lr->msgid) {
struct ldapconninfo *li = conn->proto.ldapc;
- ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL);
- lr->msgid = 0;
- }
+ ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL);
+ lr->msgid = 0;
+ }
conn->data->req.p.ldap = NULL;
- free(lr);
- }
-
- return CURLE_OK;
-}
-
-static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
- size_t len, CURLcode *err)
-{
+ free(lr);
+ }
+
+ return CURLE_OK;
+}
+
+static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
+ size_t len, CURLcode *err)
+{
struct ldapconninfo *li = conn->proto.ldapc;
struct Curl_easy *data = conn->data;
struct ldapreqinfo *lr = data->req.p.ldap;
- int rc, ret;
+ int rc, ret;
LDAPMessage *msg = NULL;
- LDAPMessage *ent;
- BerElement *ber = NULL;
+ LDAPMessage *ent;
+ BerElement *ber = NULL;
struct timeval tv = {0, 1};
- (void)len;
- (void)buf;
- (void)sockindex;
-
+ (void)len;
+ (void)buf;
+ (void)sockindex;
+
rc = ldap_result(li->ld, lr->msgid, LDAP_MSG_RECEIVED, &tv, &msg);
- if(rc < 0) {
- failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc));
- *err = CURLE_RECV_ERROR;
- return -1;
- }
-
- *err = CURLE_AGAIN;
- ret = -1;
-
- /* timed out */
+ if(rc < 0) {
+ failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc));
+ *err = CURLE_RECV_ERROR;
+ return -1;
+ }
+
+ *err = CURLE_AGAIN;
+ ret = -1;
+
+ /* timed out */
if(!msg)
- return ret;
-
+ return ret;
+
for(ent = ldap_first_message(li->ld, msg); ent;
ent = ldap_next_message(li->ld, ent)) {
struct berval bv, *bvals;
- int binary = 0, msgtype;
+ int binary = 0, msgtype;
CURLcode writeerr;
-
- msgtype = ldap_msgtype(ent);
- if(msgtype == LDAP_RES_SEARCH_RESULT) {
- int code;
- char *info = NULL;
- rc = ldap_parse_result(li->ld, ent, &code, NULL, &info, NULL, NULL, 0);
- if(rc) {
- failf(data, "LDAP local: search ldap_parse_result %s",
- ldap_err2string(rc));
- *err = CURLE_LDAP_SEARCH_FAILED;
- }
- else if(code && code != LDAP_SIZELIMIT_EXCEEDED) {
- failf(data, "LDAP remote: search failed %s %s", ldap_err2string(rc),
- info ? info : "");
- *err = CURLE_LDAP_SEARCH_FAILED;
- }
- else {
- /* successful */
- if(code == LDAP_SIZELIMIT_EXCEEDED)
- infof(data, "There are more than %d entries\n", lr->nument);
- data->req.size = data->req.bytecount;
- *err = CURLE_OK;
- ret = 0;
- }
- lr->msgid = 0;
- ldap_memfree(info);
- break;
- }
- else if(msgtype != LDAP_RES_SEARCH_ENTRY)
- continue;
-
- lr->nument++;
- rc = ldap_get_dn_ber(li->ld, ent, &ber, &bv);
- if(rc < 0) {
- *err = CURLE_RECV_ERROR;
- return -1;
- }
+
+ msgtype = ldap_msgtype(ent);
+ if(msgtype == LDAP_RES_SEARCH_RESULT) {
+ int code;
+ char *info = NULL;
+ rc = ldap_parse_result(li->ld, ent, &code, NULL, &info, NULL, NULL, 0);
+ if(rc) {
+ failf(data, "LDAP local: search ldap_parse_result %s",
+ ldap_err2string(rc));
+ *err = CURLE_LDAP_SEARCH_FAILED;
+ }
+ else if(code && code != LDAP_SIZELIMIT_EXCEEDED) {
+ failf(data, "LDAP remote: search failed %s %s", ldap_err2string(rc),
+ info ? info : "");
+ *err = CURLE_LDAP_SEARCH_FAILED;
+ }
+ else {
+ /* successful */
+ if(code == LDAP_SIZELIMIT_EXCEEDED)
+ infof(data, "There are more than %d entries\n", lr->nument);
+ data->req.size = data->req.bytecount;
+ *err = CURLE_OK;
+ ret = 0;
+ }
+ lr->msgid = 0;
+ ldap_memfree(info);
+ break;
+ }
+ else if(msgtype != LDAP_RES_SEARCH_ENTRY)
+ continue;
+
+ lr->nument++;
+ rc = ldap_get_dn_ber(li->ld, ent, &ber, &bv);
+ if(rc < 0) {
+ *err = CURLE_RECV_ERROR;
+ return -1;
+ }
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4);
if(writeerr) {
*err = writeerr;
@@ -530,21 +530,21 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
*err = writeerr;
return -1;
}
- data->req.bytecount += bv.bv_len + 5;
-
+ data->req.bytecount += bv.bv_len + 5;
+
for(rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, &bvals);
rc == LDAP_SUCCESS;
rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, &bvals)) {
- int i;
-
+ int i;
+
if(bv.bv_val == NULL)
break;
-
- if(bv.bv_len > 7 && !strncmp(bv.bv_val + bv.bv_len - 7, ";binary", 7))
- binary = 1;
- else
- binary = 0;
-
+
+ if(bv.bv_len > 7 && !strncmp(bv.bv_val + bv.bv_len - 7, ";binary", 7))
+ binary = 1;
+ else
+ binary = 0;
+
if(bvals == NULL) {
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1);
if(writeerr) {
@@ -567,7 +567,7 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
}
for(i = 0; bvals[i].bv_val != NULL; i++) {
- int binval = 0;
+ int binval = 0;
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1);
if(writeerr) {
*err = writeerr;
@@ -586,39 +586,39 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
*err = writeerr;
return -1;
}
- data->req.bytecount += bv.bv_len + 2;
-
- if(!binary) {
- /* check for leading or trailing whitespace */
- if(ISSPACE(bvals[i].bv_val[0]) ||
+ data->req.bytecount += bv.bv_len + 2;
+
+ if(!binary) {
+ /* check for leading or trailing whitespace */
+ if(ISSPACE(bvals[i].bv_val[0]) ||
ISSPACE(bvals[i].bv_val[bvals[i].bv_len-1]))
- binval = 1;
- else {
- /* check for unprintable characters */
- unsigned int j;
+ binval = 1;
+ else {
+ /* check for unprintable characters */
+ unsigned int j;
for(j = 0; j<bvals[i].bv_len; j++)
- if(!ISPRINT(bvals[i].bv_val[j])) {
- binval = 1;
- break;
- }
- }
- }
- if(binary || binval) {
- char *val_b64 = NULL;
- size_t val_b64_sz = 0;
- /* Binary value, encode to base64. */
- CURLcode error = Curl_base64_encode(data,
- bvals[i].bv_val,
- bvals[i].bv_len,
- &val_b64,
- &val_b64_sz);
- if(error) {
- ber_memfree(bvals);
- ber_free(ber, 0);
+ if(!ISPRINT(bvals[i].bv_val[j])) {
+ binval = 1;
+ break;
+ }
+ }
+ }
+ if(binary || binval) {
+ char *val_b64 = NULL;
+ size_t val_b64_sz = 0;
+ /* Binary value, encode to base64. */
+ CURLcode error = Curl_base64_encode(data,
+ bvals[i].bv_val,
+ bvals[i].bv_len,
+ &val_b64,
+ &val_b64_sz);
+ if(error) {
+ ber_memfree(bvals);
+ ber_free(ber, 0);
ldap_msgfree(msg);
- *err = error;
- return -1;
- }
+ *err = error;
+ return -1;
+ }
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY,
(char *)": ", 2);
if(writeerr) {
@@ -626,19 +626,19 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
return -1;
}
- data->req.bytecount += 2;
- if(val_b64_sz > 0) {
+ data->req.bytecount += 2;
+ if(val_b64_sz > 0) {
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, val_b64,
val_b64_sz);
if(writeerr) {
*err = writeerr;
return -1;
}
- free(val_b64);
- data->req.bytecount += val_b64_sz;
- }
- }
- else {
+ free(val_b64);
+ data->req.bytecount += val_b64_sz;
+ }
+ }
+ else {
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)" ", 1);
if(writeerr) {
*err = writeerr;
@@ -652,109 +652,109 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
return -1;
}
- data->req.bytecount += bvals[i].bv_len + 1;
- }
+ data->req.bytecount += bvals[i].bv_len + 1;
+ }
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0);
if(writeerr) {
*err = writeerr;
return -1;
}
- data->req.bytecount++;
- }
- ber_memfree(bvals);
+ data->req.bytecount++;
+ }
+ ber_memfree(bvals);
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0);
if(writeerr) {
*err = writeerr;
return -1;
}
- data->req.bytecount++;
- }
+ data->req.bytecount++;
+ }
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0);
if(writeerr) {
*err = writeerr;
return -1;
}
- data->req.bytecount++;
- ber_free(ber, 0);
- }
+ data->req.bytecount++;
+ ber_free(ber, 0);
+ }
ldap_msgfree(msg);
- return ret;
-}
-
-#ifdef USE_SSL
-static int
-ldapsb_tls_setup(Sockbuf_IO_Desc *sbiod, void *arg)
-{
- sbiod->sbiod_pvt = arg;
- return 0;
-}
-
-static int
-ldapsb_tls_remove(Sockbuf_IO_Desc *sbiod)
-{
- sbiod->sbiod_pvt = NULL;
- return 0;
-}
-
-/* We don't need to do anything because libcurl does it already */
-static int
-ldapsb_tls_close(Sockbuf_IO_Desc *sbiod)
-{
- (void)sbiod;
- return 0;
-}
-
-static int
-ldapsb_tls_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg)
-{
- (void)arg;
- if(opt == LBER_SB_OPT_DATA_READY) {
- struct connectdata *conn = sbiod->sbiod_pvt;
- return Curl_ssl_data_pending(conn, FIRSTSOCKET);
- }
- return 0;
-}
-
-static ber_slen_t
-ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
-{
- struct connectdata *conn = sbiod->sbiod_pvt;
+ return ret;
+}
+
+#ifdef USE_SSL
+static int
+ldapsb_tls_setup(Sockbuf_IO_Desc *sbiod, void *arg)
+{
+ sbiod->sbiod_pvt = arg;
+ return 0;
+}
+
+static int
+ldapsb_tls_remove(Sockbuf_IO_Desc *sbiod)
+{
+ sbiod->sbiod_pvt = NULL;
+ return 0;
+}
+
+/* We don't need to do anything because libcurl does it already */
+static int
+ldapsb_tls_close(Sockbuf_IO_Desc *sbiod)
+{
+ (void)sbiod;
+ return 0;
+}
+
+static int
+ldapsb_tls_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg)
+{
+ (void)arg;
+ if(opt == LBER_SB_OPT_DATA_READY) {
+ struct connectdata *conn = sbiod->sbiod_pvt;
+ return Curl_ssl_data_pending(conn, FIRSTSOCKET);
+ }
+ return 0;
+}
+
+static ber_slen_t
+ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
+{
+ struct connectdata *conn = sbiod->sbiod_pvt;
struct ldapconninfo *li = conn->proto.ldapc;
- ber_slen_t ret;
- CURLcode err = CURLE_RECV_ERROR;
-
+ ber_slen_t ret;
+ CURLcode err = CURLE_RECV_ERROR;
+
ret = (li->recv)(conn, FIRSTSOCKET, buf, len, &err);
- if(ret < 0 && err == CURLE_AGAIN) {
- SET_SOCKERRNO(EWOULDBLOCK);
- }
- return ret;
-}
-
-static ber_slen_t
-ldapsb_tls_write(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
-{
- struct connectdata *conn = sbiod->sbiod_pvt;
+ if(ret < 0 && err == CURLE_AGAIN) {
+ SET_SOCKERRNO(EWOULDBLOCK);
+ }
+ return ret;
+}
+
+static ber_slen_t
+ldapsb_tls_write(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
+{
+ struct connectdata *conn = sbiod->sbiod_pvt;
struct ldapconninfo *li = conn->proto.ldapc;
- ber_slen_t ret;
- CURLcode err = CURLE_SEND_ERROR;
-
+ ber_slen_t ret;
+ CURLcode err = CURLE_SEND_ERROR;
+
ret = (li->send)(conn, FIRSTSOCKET, buf, len, &err);
- if(ret < 0 && err == CURLE_AGAIN) {
- SET_SOCKERRNO(EWOULDBLOCK);
- }
- return ret;
-}
-
-static Sockbuf_IO ldapsb_tls =
-{
- ldapsb_tls_setup,
- ldapsb_tls_remove,
- ldapsb_tls_ctrl,
- ldapsb_tls_read,
- ldapsb_tls_write,
- ldapsb_tls_close
-};
-#endif /* USE_SSL */
-
-#endif /* !CURL_DISABLE_LDAP && USE_OPENLDAP */
+ if(ret < 0 && err == CURLE_AGAIN) {
+ SET_SOCKERRNO(EWOULDBLOCK);
+ }
+ return ret;
+}
+
+static Sockbuf_IO ldapsb_tls =
+{
+ ldapsb_tls_setup,
+ ldapsb_tls_remove,
+ ldapsb_tls_ctrl,
+ ldapsb_tls_read,
+ ldapsb_tls_write,
+ ldapsb_tls_close
+};
+#endif /* USE_SSL */
+
+#endif /* !CURL_DISABLE_LDAP && USE_OPENLDAP */
diff --git a/contrib/libs/curl/lib/parsedate.c b/contrib/libs/curl/lib/parsedate.c
index 375529f3f7..3c38f2c4c2 100644
--- a/contrib/libs/curl/lib/parsedate.c
+++ b/contrib/libs/curl/lib/parsedate.c
@@ -1,105 +1,105 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-/*
- A brief summary of the date string formats this parser groks:
-
- RFC 2616 3.3.1
-
- Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
- Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
- Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
-
- we support dates without week day name:
-
- 06 Nov 1994 08:49:37 GMT
- 06-Nov-94 08:49:37 GMT
- Nov 6 08:49:37 1994
-
- without the time zone:
-
- 06 Nov 1994 08:49:37
- 06-Nov-94 08:49:37
-
- weird order:
-
- 1994 Nov 6 08:49:37 (GNU date fails)
- GMT 08:49:37 06-Nov-94 Sunday
- 94 6 Nov 08:49:37 (GNU date fails)
-
- time left out:
-
- 1994 Nov 6
- 06-Nov-94
- Sun Nov 6 94
-
- unusual separators:
-
- 1994.Nov.6
- Sun/Nov/6/94/GMT
-
- commonly used time zone names:
-
- Sun, 06 Nov 1994 08:49:37 CET
- 06 Nov 1994 08:49:37 EST
-
- time zones specified using RFC822 style:
-
- Sun, 12 Sep 2004 15:05:58 -0700
- Sat, 11 Sep 2004 21:32:11 +0200
-
- compact numerical date strings:
-
- 20040912 15:05:58 -0700
- 20040911 +0200
-
-*/
-
-#include "curl_setup.h"
-
-#include <limits.h>
-
-#include <curl/curl.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+/*
+ A brief summary of the date string formats this parser groks:
+
+ RFC 2616 3.3.1
+
+ Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
+ Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
+ Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
+
+ we support dates without week day name:
+
+ 06 Nov 1994 08:49:37 GMT
+ 06-Nov-94 08:49:37 GMT
+ Nov 6 08:49:37 1994
+
+ without the time zone:
+
+ 06 Nov 1994 08:49:37
+ 06-Nov-94 08:49:37
+
+ weird order:
+
+ 1994 Nov 6 08:49:37 (GNU date fails)
+ GMT 08:49:37 06-Nov-94 Sunday
+ 94 6 Nov 08:49:37 (GNU date fails)
+
+ time left out:
+
+ 1994 Nov 6
+ 06-Nov-94
+ Sun Nov 6 94
+
+ unusual separators:
+
+ 1994.Nov.6
+ Sun/Nov/6/94/GMT
+
+ commonly used time zone names:
+
+ Sun, 06 Nov 1994 08:49:37 CET
+ 06 Nov 1994 08:49:37 EST
+
+ time zones specified using RFC822 style:
+
+ Sun, 12 Sep 2004 15:05:58 -0700
+ Sat, 11 Sep 2004 21:32:11 +0200
+
+ compact numerical date strings:
+
+ 20040912 15:05:58 -0700
+ 20040911 +0200
+
+*/
+
+#include "curl_setup.h"
+
+#include <limits.h>
+
+#include <curl/curl.h>
#include "strcase.h"
-#include "warnless.h"
-#include "parsedate.h"
-
-/*
- * parsedate()
- *
- * Returns:
- *
- * PARSEDATE_OK - a fine conversion
- * PARSEDATE_FAIL - failed to convert
- * PARSEDATE_LATER - time overflow at the far end of time_t
- * PARSEDATE_SOONER - time underflow at the low end of time_t
- */
-
-static int parsedate(const char *date, time_t *output);
-
-#define PARSEDATE_OK 0
-#define PARSEDATE_FAIL -1
-#define PARSEDATE_LATER 1
-#define PARSEDATE_SOONER 2
-
+#include "warnless.h"
+#include "parsedate.h"
+
+/*
+ * parsedate()
+ *
+ * Returns:
+ *
+ * PARSEDATE_OK - a fine conversion
+ * PARSEDATE_FAIL - failed to convert
+ * PARSEDATE_LATER - time overflow at the far end of time_t
+ * PARSEDATE_SOONER - time underflow at the low end of time_t
+ */
+
+static int parsedate(const char *date, time_t *output);
+
+#define PARSEDATE_OK 0
+#define PARSEDATE_FAIL -1
+#define PARSEDATE_LATER 1
+#define PARSEDATE_SOONER 2
+
#if !defined(CURL_DISABLE_PARSEDATE) || !defined(CURL_DISABLE_FTP) || \
!defined(CURL_DISABLE_FILE)
/* These names are also used by FTP and FILE code */
@@ -120,58 +120,58 @@ struct tzinfo {
int offset; /* +/- in minutes */
};
-/* Here's a bunch of frequently used time zone names. These were supported
- by the old getdate parser. */
-#define tDAYZONE -60 /* offset for daylight savings time */
-static const struct tzinfo tz[]= {
- {"GMT", 0}, /* Greenwich Mean */
+/* Here's a bunch of frequently used time zone names. These were supported
+ by the old getdate parser. */
+#define tDAYZONE -60 /* offset for daylight savings time */
+static const struct tzinfo tz[]= {
+ {"GMT", 0}, /* Greenwich Mean */
{"UT", 0}, /* Universal Time */
- {"UTC", 0}, /* Universal (Coordinated) */
- {"WET", 0}, /* Western European */
- {"BST", 0 tDAYZONE}, /* British Summer */
- {"WAT", 60}, /* West Africa */
- {"AST", 240}, /* Atlantic Standard */
- {"ADT", 240 tDAYZONE}, /* Atlantic Daylight */
- {"EST", 300}, /* Eastern Standard */
- {"EDT", 300 tDAYZONE}, /* Eastern Daylight */
- {"CST", 360}, /* Central Standard */
- {"CDT", 360 tDAYZONE}, /* Central Daylight */
- {"MST", 420}, /* Mountain Standard */
- {"MDT", 420 tDAYZONE}, /* Mountain Daylight */
- {"PST", 480}, /* Pacific Standard */
- {"PDT", 480 tDAYZONE}, /* Pacific Daylight */
- {"YST", 540}, /* Yukon Standard */
- {"YDT", 540 tDAYZONE}, /* Yukon Daylight */
- {"HST", 600}, /* Hawaii Standard */
- {"HDT", 600 tDAYZONE}, /* Hawaii Daylight */
- {"CAT", 600}, /* Central Alaska */
- {"AHST", 600}, /* Alaska-Hawaii Standard */
- {"NT", 660}, /* Nome */
- {"IDLW", 720}, /* International Date Line West */
- {"CET", -60}, /* Central European */
- {"MET", -60}, /* Middle European */
- {"MEWT", -60}, /* Middle European Winter */
- {"MEST", -60 tDAYZONE}, /* Middle European Summer */
- {"CEST", -60 tDAYZONE}, /* Central European Summer */
- {"MESZ", -60 tDAYZONE}, /* Middle European Summer */
- {"FWT", -60}, /* French Winter */
- {"FST", -60 tDAYZONE}, /* French Summer */
- {"EET", -120}, /* Eastern Europe, USSR Zone 1 */
- {"WAST", -420}, /* West Australian Standard */
- {"WADT", -420 tDAYZONE}, /* West Australian Daylight */
- {"CCT", -480}, /* China Coast, USSR Zone 7 */
- {"JST", -540}, /* Japan Standard, USSR Zone 8 */
- {"EAST", -600}, /* Eastern Australian Standard */
- {"EADT", -600 tDAYZONE}, /* Eastern Australian Daylight */
- {"GST", -600}, /* Guam Standard, USSR Zone 9 */
- {"NZT", -720}, /* New Zealand */
- {"NZST", -720}, /* New Zealand Standard */
- {"NZDT", -720 tDAYZONE}, /* New Zealand Daylight */
- {"IDLE", -720}, /* International Date Line East */
- /* Next up: Military timezone names. RFC822 allowed these, but (as noted in
- RFC 1123) had their signs wrong. Here we use the correct signs to match
- actual military usage.
- */
+ {"UTC", 0}, /* Universal (Coordinated) */
+ {"WET", 0}, /* Western European */
+ {"BST", 0 tDAYZONE}, /* British Summer */
+ {"WAT", 60}, /* West Africa */
+ {"AST", 240}, /* Atlantic Standard */
+ {"ADT", 240 tDAYZONE}, /* Atlantic Daylight */
+ {"EST", 300}, /* Eastern Standard */
+ {"EDT", 300 tDAYZONE}, /* Eastern Daylight */
+ {"CST", 360}, /* Central Standard */
+ {"CDT", 360 tDAYZONE}, /* Central Daylight */
+ {"MST", 420}, /* Mountain Standard */
+ {"MDT", 420 tDAYZONE}, /* Mountain Daylight */
+ {"PST", 480}, /* Pacific Standard */
+ {"PDT", 480 tDAYZONE}, /* Pacific Daylight */
+ {"YST", 540}, /* Yukon Standard */
+ {"YDT", 540 tDAYZONE}, /* Yukon Daylight */
+ {"HST", 600}, /* Hawaii Standard */
+ {"HDT", 600 tDAYZONE}, /* Hawaii Daylight */
+ {"CAT", 600}, /* Central Alaska */
+ {"AHST", 600}, /* Alaska-Hawaii Standard */
+ {"NT", 660}, /* Nome */
+ {"IDLW", 720}, /* International Date Line West */
+ {"CET", -60}, /* Central European */
+ {"MET", -60}, /* Middle European */
+ {"MEWT", -60}, /* Middle European Winter */
+ {"MEST", -60 tDAYZONE}, /* Middle European Summer */
+ {"CEST", -60 tDAYZONE}, /* Central European Summer */
+ {"MESZ", -60 tDAYZONE}, /* Middle European Summer */
+ {"FWT", -60}, /* French Winter */
+ {"FST", -60 tDAYZONE}, /* French Summer */
+ {"EET", -120}, /* Eastern Europe, USSR Zone 1 */
+ {"WAST", -420}, /* West Australian Standard */
+ {"WADT", -420 tDAYZONE}, /* West Australian Daylight */
+ {"CCT", -480}, /* China Coast, USSR Zone 7 */
+ {"JST", -540}, /* Japan Standard, USSR Zone 8 */
+ {"EAST", -600}, /* Eastern Australian Standard */
+ {"EADT", -600 tDAYZONE}, /* Eastern Australian Daylight */
+ {"GST", -600}, /* Guam Standard, USSR Zone 9 */
+ {"NZT", -720}, /* New Zealand */
+ {"NZST", -720}, /* New Zealand Standard */
+ {"NZDT", -720 tDAYZONE}, /* New Zealand Daylight */
+ {"IDLE", -720}, /* International Date Line East */
+ /* Next up: Military timezone names. RFC822 allowed these, but (as noted in
+ RFC 1123) had their signs wrong. Here we use the correct signs to match
+ actual military usage.
+ */
{"A", 1 * 60}, /* Alpha */
{"B", 2 * 60}, /* Bravo */
{"C", 3 * 60}, /* Charlie */
@@ -181,131 +181,131 @@ static const struct tzinfo tz[]= {
{"G", 7 * 60}, /* Golf */
{"H", 8 * 60}, /* Hotel */
{"I", 9 * 60}, /* India */
- /* "J", Juliet is not used as a timezone, to indicate the observer's local
- time */
+ /* "J", Juliet is not used as a timezone, to indicate the observer's local
+ time */
{"K", 10 * 60}, /* Kilo */
{"L", 11 * 60}, /* Lima */
{"M", 12 * 60}, /* Mike */
- {"N", -1 * 60}, /* November */
- {"O", -2 * 60}, /* Oscar */
- {"P", -3 * 60}, /* Papa */
- {"Q", -4 * 60}, /* Quebec */
- {"R", -5 * 60}, /* Romeo */
- {"S", -6 * 60}, /* Sierra */
- {"T", -7 * 60}, /* Tango */
- {"U", -8 * 60}, /* Uniform */
- {"V", -9 * 60}, /* Victor */
- {"W", -10 * 60}, /* Whiskey */
- {"X", -11 * 60}, /* X-ray */
- {"Y", -12 * 60}, /* Yankee */
- {"Z", 0}, /* Zulu, zero meridian, a.k.a. UTC */
-};
-
-/* returns:
- -1 no day
- 0 monday - 6 sunday
-*/
-
-static int checkday(const char *check, size_t len)
-{
- int i;
- const char * const *what;
+ {"N", -1 * 60}, /* November */
+ {"O", -2 * 60}, /* Oscar */
+ {"P", -3 * 60}, /* Papa */
+ {"Q", -4 * 60}, /* Quebec */
+ {"R", -5 * 60}, /* Romeo */
+ {"S", -6 * 60}, /* Sierra */
+ {"T", -7 * 60}, /* Tango */
+ {"U", -8 * 60}, /* Uniform */
+ {"V", -9 * 60}, /* Victor */
+ {"W", -10 * 60}, /* Whiskey */
+ {"X", -11 * 60}, /* X-ray */
+ {"Y", -12 * 60}, /* Yankee */
+ {"Z", 0}, /* Zulu, zero meridian, a.k.a. UTC */
+};
+
+/* returns:
+ -1 no day
+ 0 monday - 6 sunday
+*/
+
+static int checkday(const char *check, size_t len)
+{
+ int i;
+ const char * const *what;
bool found = FALSE;
- if(len > 3)
- what = &weekday[0];
- else
- what = &Curl_wkday[0];
+ if(len > 3)
+ what = &weekday[0];
+ else
+ what = &Curl_wkday[0];
for(i = 0; i<7; i++) {
if(strcasecompare(check, what[0])) {
found = TRUE;
- break;
- }
- what++;
- }
- return found?i:-1;
-}
-
-static int checkmonth(const char *check)
-{
- int i;
- const char * const *what;
+ break;
+ }
+ what++;
+ }
+ return found?i:-1;
+}
+
+static int checkmonth(const char *check)
+{
+ int i;
+ const char * const *what;
bool found = FALSE;
-
- what = &Curl_month[0];
+
+ what = &Curl_month[0];
for(i = 0; i<12; i++) {
if(strcasecompare(check, what[0])) {
found = TRUE;
- break;
- }
- what++;
- }
- return found?i:-1; /* return the offset or -1, no real offset is -1 */
-}
-
-/* return the time zone offset between GMT and the input one, in number
- of seconds or -1 if the timezone wasn't found/legal */
-
-static int checktz(const char *check)
-{
- unsigned int i;
- const struct tzinfo *what;
+ break;
+ }
+ what++;
+ }
+ return found?i:-1; /* return the offset or -1, no real offset is -1 */
+}
+
+/* return the time zone offset between GMT and the input one, in number
+ of seconds or -1 if the timezone wasn't found/legal */
+
+static int checktz(const char *check)
+{
+ unsigned int i;
+ const struct tzinfo *what;
bool found = FALSE;
-
- what = tz;
+
+ what = tz;
for(i = 0; i< sizeof(tz)/sizeof(tz[0]); i++) {
if(strcasecompare(check, what->name)) {
found = TRUE;
- break;
- }
- what++;
- }
- return found?what->offset*60:-1;
-}
-
-static void skip(const char **date)
-{
- /* skip everything that aren't letters or digits */
- while(**date && !ISALNUM(**date))
- (*date)++;
-}
-
-enum assume {
- DATE_MDAY,
- DATE_YEAR,
- DATE_TIME
-};
-
+ break;
+ }
+ what++;
+ }
+ return found?what->offset*60:-1;
+}
+
+static void skip(const char **date)
+{
+ /* skip everything that aren't letters or digits */
+ while(**date && !ISALNUM(**date))
+ (*date)++;
+}
+
+enum assume {
+ DATE_MDAY,
+ DATE_YEAR,
+ DATE_TIME
+};
+
/*
* time2epoch: time stamp to seconds since epoch in GMT time zone. Similar to
* mktime but for GMT only.
- */
+ */
static time_t time2epoch(int sec, int min, int hour,
int mday, int mon, int year)
-{
- static const int month_days_cumulative [12] =
- { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+{
+ static const int month_days_cumulative [12] =
+ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
int leap_days = year - (mon <= 1);
- leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400)
- - (1969 / 4) + (1969 / 100) - (1969 / 400));
+ leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400)
+ - (1969 / 4) + (1969 / 100) - (1969 / 400));
return ((((time_t) (year - 1970) * 365
+ leap_days + month_days_cumulative[mon] + mday - 1) * 24
+ hour) * 60 + min) * 60 + sec;
-}
-
-/*
- * parsedate()
- *
- * Returns:
- *
- * PARSEDATE_OK - a fine conversion
- * PARSEDATE_FAIL - failed to convert
- * PARSEDATE_LATER - time overflow at the far end of time_t
- * PARSEDATE_SOONER - time underflow at the low end of time_t
- */
-
-static int parsedate(const char *date, time_t *output)
-{
- time_t t = 0;
+}
+
+/*
+ * parsedate()
+ *
+ * Returns:
+ *
+ * PARSEDATE_OK - a fine conversion
+ * PARSEDATE_FAIL - failed to convert
+ * PARSEDATE_LATER - time overflow at the far end of time_t
+ * PARSEDATE_SOONER - time underflow at the low end of time_t
+ */
+
+static int parsedate(const char *date, time_t *output)
+{
+ time_t t = 0;
int wdaynum = -1; /* day of the week number, 0-6 (mon-sun) */
int monnum = -1; /* month of the year number, 0-11 */
int mdaynum = -1; /* day of month, 1 - 31 */
@@ -314,159 +314,159 @@ static int parsedate(const char *date, time_t *output)
int secnum = -1;
int yearnum = -1;
int tzoff = -1;
- enum assume dignext = DATE_MDAY;
- const char *indate = date; /* save the original pointer */
- int part = 0; /* max 6 parts */
-
- while(*date && (part < 6)) {
+ enum assume dignext = DATE_MDAY;
+ const char *indate = date; /* save the original pointer */
+ int part = 0; /* max 6 parts */
+
+ while(*date && (part < 6)) {
bool found = FALSE;
-
- skip(&date);
-
- if(ISALPHA(*date)) {
- /* a name coming up */
- char buf[32]="";
- size_t len;
+
+ skip(&date);
+
+ if(ISALPHA(*date)) {
+ /* a name coming up */
+ char buf[32]="";
+ size_t len;
if(sscanf(date, "%31[ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz]", buf))
len = strlen(buf);
else
len = 0;
-
- if(wdaynum == -1) {
- wdaynum = checkday(buf, len);
- if(wdaynum != -1)
- found = TRUE;
- }
- if(!found && (monnum == -1)) {
- monnum = checkmonth(buf);
- if(monnum != -1)
- found = TRUE;
- }
-
- if(!found && (tzoff == -1)) {
- /* this just must be a time zone string */
- tzoff = checktz(buf);
- if(tzoff != -1)
- found = TRUE;
- }
-
- if(!found)
- return PARSEDATE_FAIL; /* bad string */
-
- date += len;
- }
- else if(ISDIGIT(*date)) {
- /* a digit */
- int val;
- char *end;
+
+ if(wdaynum == -1) {
+ wdaynum = checkday(buf, len);
+ if(wdaynum != -1)
+ found = TRUE;
+ }
+ if(!found && (monnum == -1)) {
+ monnum = checkmonth(buf);
+ if(monnum != -1)
+ found = TRUE;
+ }
+
+ if(!found && (tzoff == -1)) {
+ /* this just must be a time zone string */
+ tzoff = checktz(buf);
+ if(tzoff != -1)
+ found = TRUE;
+ }
+
+ if(!found)
+ return PARSEDATE_FAIL; /* bad string */
+
+ date += len;
+ }
+ else if(ISDIGIT(*date)) {
+ /* a digit */
+ int val;
+ char *end;
int len = 0;
- if((secnum == -1) &&
+ if((secnum == -1) &&
(3 == sscanf(date, "%02d:%02d:%02d%n",
&hournum, &minnum, &secnum, &len))) {
- /* time stamp! */
+ /* time stamp! */
date += len;
- }
- else if((secnum == -1) &&
+ }
+ else if((secnum == -1) &&
(2 == sscanf(date, "%02d:%02d%n", &hournum, &minnum, &len))) {
- /* time stamp without seconds */
+ /* time stamp without seconds */
date += len;
- secnum = 0;
- }
- else {
- long lval;
- int error;
- int old_errno;
-
+ secnum = 0;
+ }
+ else {
+ long lval;
+ int error;
+ int old_errno;
+
old_errno = errno;
errno = 0;
- lval = strtol(date, &end, 10);
+ lval = strtol(date, &end, 10);
error = errno;
if(errno != old_errno)
errno = old_errno;
-
- if(error)
- return PARSEDATE_FAIL;
-
+
+ if(error)
+ return PARSEDATE_FAIL;
+
#if LONG_MAX != INT_MAX
- if((lval > (long)INT_MAX) || (lval < (long)INT_MIN))
- return PARSEDATE_FAIL;
+ if((lval > (long)INT_MAX) || (lval < (long)INT_MIN))
+ return PARSEDATE_FAIL;
#endif
-
- val = curlx_sltosi(lval);
-
- if((tzoff == -1) &&
- ((end - date) == 4) &&
- (val <= 1400) &&
- (indate< date) &&
- ((date[-1] == '+' || date[-1] == '-'))) {
- /* four digits and a value less than or equal to 1400 (to take into
- account all sorts of funny time zone diffs) and it is preceded
- with a plus or minus. This is a time zone indication. 1400 is
- picked since +1300 is frequently used and +1400 is mentioned as
- an edge number in the document "ISO C 200X Proposal: Timezone
- Functions" at http://david.tribble.com/text/c0xtimezone.html If
- anyone has a more authoritative source for the exact maximum time
- zone offsets, please speak up! */
- found = TRUE;
- tzoff = (val/100 * 60 + val%100)*60;
-
- /* the + and - prefix indicates the local time compared to GMT,
+
+ val = curlx_sltosi(lval);
+
+ if((tzoff == -1) &&
+ ((end - date) == 4) &&
+ (val <= 1400) &&
+ (indate< date) &&
+ ((date[-1] == '+' || date[-1] == '-'))) {
+ /* four digits and a value less than or equal to 1400 (to take into
+ account all sorts of funny time zone diffs) and it is preceded
+ with a plus or minus. This is a time zone indication. 1400 is
+ picked since +1300 is frequently used and +1400 is mentioned as
+ an edge number in the document "ISO C 200X Proposal: Timezone
+ Functions" at http://david.tribble.com/text/c0xtimezone.html If
+ anyone has a more authoritative source for the exact maximum time
+ zone offsets, please speak up! */
+ found = TRUE;
+ tzoff = (val/100 * 60 + val%100)*60;
+
+ /* the + and - prefix indicates the local time compared to GMT,
this we need their reversed math to get what we want */
- tzoff = date[-1]=='+'?-tzoff:tzoff;
- }
-
- if(((end - date) == 8) &&
- (yearnum == -1) &&
- (monnum == -1) &&
- (mdaynum == -1)) {
- /* 8 digits, no year, month or day yet. This is YYYYMMDD */
- found = TRUE;
- yearnum = val/10000;
- monnum = (val%10000)/100-1; /* month is 0 - 11 */
- mdaynum = val%100;
- }
-
- if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) {
- if((val > 0) && (val<32)) {
- mdaynum = val;
- found = TRUE;
- }
- dignext = DATE_YEAR;
- }
-
- if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) {
- yearnum = val;
- found = TRUE;
+ tzoff = date[-1]=='+'?-tzoff:tzoff;
+ }
+
+ if(((end - date) == 8) &&
+ (yearnum == -1) &&
+ (monnum == -1) &&
+ (mdaynum == -1)) {
+ /* 8 digits, no year, month or day yet. This is YYYYMMDD */
+ found = TRUE;
+ yearnum = val/10000;
+ monnum = (val%10000)/100-1; /* month is 0 - 11 */
+ mdaynum = val%100;
+ }
+
+ if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) {
+ if((val > 0) && (val<32)) {
+ mdaynum = val;
+ found = TRUE;
+ }
+ dignext = DATE_YEAR;
+ }
+
+ if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) {
+ yearnum = val;
+ found = TRUE;
if(yearnum < 100) {
- if(yearnum > 70)
- yearnum += 1900;
- else
- yearnum += 2000;
- }
- if(mdaynum == -1)
- dignext = DATE_MDAY;
- }
-
- if(!found)
- return PARSEDATE_FAIL;
-
- date = end;
- }
- }
-
- part++;
- }
-
- if(-1 == secnum)
- secnum = minnum = hournum = 0; /* no time, make it zero */
-
- if((-1 == mdaynum) ||
- (-1 == monnum) ||
- (-1 == yearnum))
- /* lacks vital info, fail */
- return PARSEDATE_FAIL;
-
+ if(yearnum > 70)
+ yearnum += 1900;
+ else
+ yearnum += 2000;
+ }
+ if(mdaynum == -1)
+ dignext = DATE_MDAY;
+ }
+
+ if(!found)
+ return PARSEDATE_FAIL;
+
+ date = end;
+ }
+ }
+
+ part++;
+ }
+
+ if(-1 == secnum)
+ secnum = minnum = hournum = 0; /* no time, make it zero */
+
+ if((-1 == mdaynum) ||
+ (-1 == monnum) ||
+ (-1 == yearnum))
+ /* lacks vital info, fail */
+ return PARSEDATE_FAIL;
+
#ifdef HAVE_TIME_T_UNSIGNED
if(yearnum < 1970) {
/* only positive numbers cannot return earlier */
@@ -485,47 +485,47 @@ static int parsedate(const char *date, time_t *output)
}
#else
/* a signed 32 bit time_t can only hold dates to the beginning of 2038 */
- if(yearnum > 2037) {
+ if(yearnum > 2037) {
*output = TIME_T_MAX;
- return PARSEDATE_LATER;
- }
+ return PARSEDATE_LATER;
+ }
if(yearnum < 1903) {
*output = TIME_T_MIN;
- return PARSEDATE_SOONER;
- }
+ return PARSEDATE_SOONER;
+ }
#endif
-
+
#else
/* The Gregorian calendar was introduced 1582 */
if(yearnum < 1583)
return PARSEDATE_FAIL;
#endif
- if((mdaynum > 31) || (monnum > 11) ||
- (hournum > 23) || (minnum > 59) || (secnum > 60))
- return PARSEDATE_FAIL; /* clearly an illegal date */
-
+ if((mdaynum > 31) || (monnum > 11) ||
+ (hournum > 23) || (minnum > 59) || (secnum > 60))
+ return PARSEDATE_FAIL; /* clearly an illegal date */
+
/* time2epoch() returns a time_t. time_t is often 32 bits, sometimes even on
architectures that feature 64 bit 'long' but ultimately time_t is the
correct data type to use.
- */
+ */
t = time2epoch(secnum, minnum, hournum, mdaynum, monnum, yearnum);
-
+
/* Add the time zone diff between local time zone and GMT. */
if(tzoff == -1)
tzoff = 0;
-
+
if((tzoff > 0) && (t > TIME_T_MAX - tzoff)) {
*output = TIME_T_MAX;
return PARSEDATE_LATER; /* time_t overflow */
}
-
+
t += tzoff;
-
- *output = t;
-
- return PARSEDATE_OK;
-}
+
+ *output = t;
+
+ return PARSEDATE_OK;
+}
#else
/* disabled */
static int parsedate(const char *date, time_t *output)
@@ -535,23 +535,23 @@ static int parsedate(const char *date, time_t *output)
return PARSEDATE_OK; /* a lie */
}
#endif
-
-time_t curl_getdate(const char *p, const time_t *now)
-{
+
+time_t curl_getdate(const char *p, const time_t *now)
+{
time_t parsed = -1;
- int rc = parsedate(p, &parsed);
- (void)now; /* legacy argument from the past that we ignore */
-
+ int rc = parsedate(p, &parsed);
+ (void)now; /* legacy argument from the past that we ignore */
+
if(rc == PARSEDATE_OK) {
if(parsed == -1)
/* avoid returning -1 for a working scenario */
parsed++;
- return parsed;
- }
- /* everything else is fail */
- return -1;
-}
-
+ return parsed;
+ }
+ /* everything else is fail */
+ return -1;
+}
+
/* Curl_getdate_capped() differs from curl_getdate() in that this will return
TIME_T_MAX in case the parsed time value was too big, instead of an
error. */
@@ -576,26 +576,26 @@ time_t Curl_getdate_capped(const char *p)
/* UNREACHABLE */
}
-/*
- * Curl_gmtime() is a gmtime() replacement for portability. Do not use the
- * gmtime_r() or gmtime() functions anywhere else but here.
- *
- */
-
-CURLcode Curl_gmtime(time_t intime, struct tm *store)
-{
- const struct tm *tm;
-#ifdef HAVE_GMTIME_R
- /* thread-safe version */
- tm = (struct tm *)gmtime_r(&intime, store);
-#else
+/*
+ * Curl_gmtime() is a gmtime() replacement for portability. Do not use the
+ * gmtime_r() or gmtime() functions anywhere else but here.
+ *
+ */
+
+CURLcode Curl_gmtime(time_t intime, struct tm *store)
+{
+ const struct tm *tm;
+#ifdef HAVE_GMTIME_R
+ /* thread-safe version */
+ tm = (struct tm *)gmtime_r(&intime, store);
+#else
/* !checksrc! disable BANNEDFUNC 1 */
- tm = gmtime(&intime);
- if(tm)
- *store = *tm; /* copy the pointed struct to the local copy */
-#endif
-
- if(!tm)
- return CURLE_BAD_FUNCTION_ARGUMENT;
- return CURLE_OK;
-}
+ tm = gmtime(&intime);
+ if(tm)
+ *store = *tm; /* copy the pointed struct to the local copy */
+#endif
+
+ if(!tm)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ return CURLE_OK;
+}
diff --git a/contrib/libs/curl/lib/parsedate.h b/contrib/libs/curl/lib/parsedate.h
index 9ffedddf62..a99faf9e36 100644
--- a/contrib/libs/curl/lib/parsedate.h
+++ b/contrib/libs/curl/lib/parsedate.h
@@ -1,36 +1,36 @@
-#ifndef HEADER_CURL_PARSEDATE_H
-#define HEADER_CURL_PARSEDATE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_PARSEDATE_H
+#define HEADER_CURL_PARSEDATE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-extern const char * const Curl_wkday[7];
-extern const char * const Curl_month[12];
-
-CURLcode Curl_gmtime(time_t intime, struct tm *store);
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+extern const char * const Curl_wkday[7];
+extern const char * const Curl_month[12];
+
+CURLcode Curl_gmtime(time_t intime, struct tm *store);
+
/* Curl_getdate_capped() differs from curl_getdate() in that this will return
TIME_T_MAX in case the parsed time value was too big, instead of an
error. */
time_t Curl_getdate_capped(const char *p);
-#endif /* HEADER_CURL_PARSEDATE_H */
+#endif /* HEADER_CURL_PARSEDATE_H */
diff --git a/contrib/libs/curl/lib/pingpong.c b/contrib/libs/curl/lib/pingpong.c
index 964d9e6b33..5d6109a7df 100644
--- a/contrib/libs/curl/lib/pingpong.c
+++ b/contrib/libs/curl/lib/pingpong.c
@@ -1,186 +1,186 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * 'pingpong' is for generic back-and-forth support functions used by FTP,
- * IMAP, POP3, SMTP and whatever more that likes them.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "urldata.h"
-#include "sendf.h"
-#include "select.h"
-#include "progress.h"
-#include "speedcheck.h"
-#include "pingpong.h"
-#include "multiif.h"
-#include "non-ascii.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * 'pingpong' is for generic back-and-forth support functions used by FTP,
+ * IMAP, POP3, SMTP and whatever more that likes them.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include "urldata.h"
+#include "sendf.h"
+#include "select.h"
+#include "progress.h"
+#include "speedcheck.h"
+#include "pingpong.h"
+#include "multiif.h"
+#include "non-ascii.h"
#include "vtls/vtls.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-#ifdef USE_PINGPONG
-
-/* Returns timeout in ms. 0 or negative number means the timeout has already
- triggered */
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#ifdef USE_PINGPONG
+
+/* Returns timeout in ms. 0 or negative number means the timeout has already
+ triggered */
timediff_t Curl_pp_state_timeout(struct pingpong *pp, bool disconnecting)
-{
- struct connectdata *conn = pp->conn;
+{
+ struct connectdata *conn = pp->conn;
struct Curl_easy *data = conn->data;
timediff_t timeout_ms; /* in milliseconds */
timediff_t response_time = (data->set.server_response_timeout)?
- data->set.server_response_timeout: pp->response_time;
-
- /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine
- remaining time, or use pp->response because SERVER_RESPONSE_TIMEOUT is
- supposed to govern the response for any given server response, not for
- the time from connect to the given server response. */
-
- /* Without a requested timeout, we only wait 'response_time' seconds for the
- full response to arrive before we bail out */
- timeout_ms = response_time -
+ data->set.server_response_timeout: pp->response_time;
+
+ /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine
+ remaining time, or use pp->response because SERVER_RESPONSE_TIMEOUT is
+ supposed to govern the response for any given server response, not for
+ the time from connect to the given server response. */
+
+ /* Without a requested timeout, we only wait 'response_time' seconds for the
+ full response to arrive before we bail out */
+ timeout_ms = response_time -
Curl_timediff(Curl_now(), pp->response); /* spent time */
-
+
if(data->set.timeout && !disconnecting) {
- /* if timeout is requested, find out how much remaining time we have */
+ /* if timeout is requested, find out how much remaining time we have */
timediff_t timeout2_ms = data->set.timeout - /* timeout time */
Curl_timediff(Curl_now(), conn->now); /* spent time */
-
- /* pick the lowest number */
- timeout_ms = CURLMIN(timeout_ms, timeout2_ms);
- }
-
- return timeout_ms;
-}
-
-/*
- * Curl_pp_statemach()
- */
+
+ /* pick the lowest number */
+ timeout_ms = CURLMIN(timeout_ms, timeout2_ms);
+ }
+
+ return timeout_ms;
+}
+
+/*
+ * Curl_pp_statemach()
+ */
CURLcode Curl_pp_statemach(struct pingpong *pp, bool block,
bool disconnecting)
-{
- struct connectdata *conn = pp->conn;
- curl_socket_t sock = conn->sock[FIRSTSOCKET];
- int rc;
+{
+ struct connectdata *conn = pp->conn;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
+ int rc;
timediff_t interval_ms;
timediff_t timeout_ms = Curl_pp_state_timeout(pp, disconnecting);
struct Curl_easy *data = conn->data;
- CURLcode result = CURLE_OK;
-
+ CURLcode result = CURLE_OK;
+
if(timeout_ms <= 0) {
- failf(data, "server response timeout");
- return CURLE_OPERATION_TIMEDOUT; /* already too little time */
- }
-
- if(block) {
- interval_ms = 1000; /* use 1 second timeout intervals */
- if(timeout_ms < interval_ms)
- interval_ms = timeout_ms;
- }
- else
- interval_ms = 0; /* immediate */
-
+ failf(data, "server response timeout");
+ return CURLE_OPERATION_TIMEDOUT; /* already too little time */
+ }
+
+ if(block) {
+ interval_ms = 1000; /* use 1 second timeout intervals */
+ if(timeout_ms < interval_ms)
+ interval_ms = timeout_ms;
+ }
+ else
+ interval_ms = 0; /* immediate */
+
if(Curl_ssl_data_pending(conn, FIRSTSOCKET))
rc = 1;
else if(Curl_pp_moredata(pp))
- /* We are receiving and there is data in the cache so just read it */
- rc = 1;
- else if(!pp->sendleft && Curl_ssl_data_pending(conn, FIRSTSOCKET))
- /* We are receiving and there is data ready in the SSL library */
- rc = 1;
- else
+ /* We are receiving and there is data in the cache so just read it */
+ rc = 1;
+ else if(!pp->sendleft && Curl_ssl_data_pending(conn, FIRSTSOCKET))
+ /* We are receiving and there is data ready in the SSL library */
+ rc = 1;
+ else
rc = Curl_socket_check(pp->sendleft?CURL_SOCKET_BAD:sock, /* reading */
CURL_SOCKET_BAD,
- pp->sendleft?sock:CURL_SOCKET_BAD, /* writing */
- interval_ms);
-
- if(block) {
- /* if we didn't wait, we don't have to spend time on this now */
- if(Curl_pgrsUpdate(conn))
- result = CURLE_ABORTED_BY_CALLBACK;
- else
+ pp->sendleft?sock:CURL_SOCKET_BAD, /* writing */
+ interval_ms);
+
+ if(block) {
+ /* if we didn't wait, we don't have to spend time on this now */
+ if(Curl_pgrsUpdate(conn))
+ result = CURLE_ABORTED_BY_CALLBACK;
+ else
result = Curl_speedcheck(data, Curl_now());
-
- if(result)
- return result;
- }
-
- if(rc == -1) {
- failf(data, "select/poll error");
- result = CURLE_OUT_OF_MEMORY;
- }
- else if(rc)
- result = pp->statemach_act(conn);
-
- return result;
-}
-
-/* initialize stuff to prepare for reading a fresh new response */
-void Curl_pp_init(struct pingpong *pp)
-{
- struct connectdata *conn = pp->conn;
- pp->nread_resp = 0;
- pp->linestart_resp = conn->data->state.buffer;
- pp->pending_resp = TRUE;
+
+ if(result)
+ return result;
+ }
+
+ if(rc == -1) {
+ failf(data, "select/poll error");
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ else if(rc)
+ result = pp->statemach_act(conn);
+
+ return result;
+}
+
+/* initialize stuff to prepare for reading a fresh new response */
+void Curl_pp_init(struct pingpong *pp)
+{
+ struct connectdata *conn = pp->conn;
+ pp->nread_resp = 0;
+ pp->linestart_resp = conn->data->state.buffer;
+ pp->pending_resp = TRUE;
pp->response = Curl_now(); /* start response time-out now! */
-}
-
+}
+
/* setup for the coming transfer */
void Curl_pp_setup(struct pingpong *pp)
{
Curl_dyn_init(&pp->sendbuf, DYN_PINGPPONG_CMD);
}
-
-/***********************************************************************
- *
- * Curl_pp_vsendf()
- *
+
+/***********************************************************************
+ *
+ * Curl_pp_vsendf()
+ *
* Send the formatted string as a command to a pingpong server. Note that
- * the string should not have any CRLF appended, as this function will
- * append the necessary things itself.
- *
- * made to never block
- */
-CURLcode Curl_pp_vsendf(struct pingpong *pp,
- const char *fmt,
- va_list args)
-{
+ * the string should not have any CRLF appended, as this function will
+ * append the necessary things itself.
+ *
+ * made to never block
+ */
+CURLcode Curl_pp_vsendf(struct pingpong *pp,
+ const char *fmt,
+ va_list args)
+{
ssize_t bytes_written = 0;
- size_t write_len;
- char *s;
+ size_t write_len;
+ char *s;
CURLcode result;
- struct connectdata *conn = pp->conn;
+ struct connectdata *conn = pp->conn;
struct Curl_easy *data;
-
-#ifdef HAVE_GSSAPI
+
+#ifdef HAVE_GSSAPI
enum protection_level data_sec;
-#endif
-
- DEBUGASSERT(pp->sendleft == 0);
- DEBUGASSERT(pp->sendsize == 0);
- DEBUGASSERT(pp->sendthis == NULL);
-
+#endif
+
+ DEBUGASSERT(pp->sendleft == 0);
+ DEBUGASSERT(pp->sendsize == 0);
+ DEBUGASSERT(pp->sendthis == NULL);
+
if(!conn)
/* can't send without a connection! */
return CURLE_SEND_ERROR;
@@ -190,321 +190,321 @@ CURLcode Curl_pp_vsendf(struct pingpong *pp,
result = Curl_dyn_vaddf(&pp->sendbuf, fmt, args);
if(result)
return result;
-
+
/* append CRLF */
result = Curl_dyn_addn(&pp->sendbuf, "\r\n", 2);
if(result)
return result;
-
+
write_len = Curl_dyn_len(&pp->sendbuf);
s = Curl_dyn_ptr(&pp->sendbuf);
- Curl_pp_init(pp);
-
+ Curl_pp_init(pp);
+
result = Curl_convert_to_network(data, s, write_len);
- /* Curl_convert_to_network calls failf if unsuccessful */
+ /* Curl_convert_to_network calls failf if unsuccessful */
if(result)
return result;
-
-#ifdef HAVE_GSSAPI
- conn->data_prot = PROT_CMD;
-#endif
+
+#ifdef HAVE_GSSAPI
+ conn->data_prot = PROT_CMD;
+#endif
result = Curl_write(conn, conn->sock[FIRSTSOCKET], s, write_len,
&bytes_written);
if(result)
return result;
-#ifdef HAVE_GSSAPI
+#ifdef HAVE_GSSAPI
data_sec = conn->data_prot;
- DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST);
- conn->data_prot = data_sec;
-#endif
-
+ DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST);
+ conn->data_prot = data_sec;
+#endif
+
Curl_debug(data, CURLINFO_HEADER_OUT, s, (size_t)bytes_written);
-
- if(bytes_written != (ssize_t)write_len) {
- /* the whole chunk was not sent, keep it around and adjust sizes */
- pp->sendthis = s;
- pp->sendsize = write_len;
- pp->sendleft = write_len - bytes_written;
- }
- else {
- pp->sendthis = NULL;
- pp->sendleft = pp->sendsize = 0;
+
+ if(bytes_written != (ssize_t)write_len) {
+ /* the whole chunk was not sent, keep it around and adjust sizes */
+ pp->sendthis = s;
+ pp->sendsize = write_len;
+ pp->sendleft = write_len - bytes_written;
+ }
+ else {
+ pp->sendthis = NULL;
+ pp->sendleft = pp->sendsize = 0;
pp->response = Curl_now();
- }
-
- return CURLE_OK;
-}
-
-
-/***********************************************************************
- *
- * Curl_pp_sendf()
- *
+ }
+
+ return CURLE_OK;
+}
+
+
+/***********************************************************************
+ *
+ * Curl_pp_sendf()
+ *
* Send the formatted string as a command to a pingpong server. Note that
- * the string should not have any CRLF appended, as this function will
- * append the necessary things itself.
- *
- * made to never block
- */
-CURLcode Curl_pp_sendf(struct pingpong *pp,
- const char *fmt, ...)
-{
+ * the string should not have any CRLF appended, as this function will
+ * append the necessary things itself.
+ *
+ * made to never block
+ */
+CURLcode Curl_pp_sendf(struct pingpong *pp,
+ const char *fmt, ...)
+{
CURLcode result;
- va_list ap;
- va_start(ap, fmt);
-
+ va_list ap;
+ va_start(ap, fmt);
+
result = Curl_pp_vsendf(pp, fmt, ap);
-
- va_end(ap);
-
+
+ va_end(ap);
+
return result;
-}
-
-/*
- * Curl_pp_readresp()
- *
- * Reads a piece of a server response.
- */
-CURLcode Curl_pp_readresp(curl_socket_t sockfd,
- struct pingpong *pp,
- int *code, /* return the server code if done */
- size_t *size) /* size of the response */
-{
- ssize_t perline; /* count bytes per line */
+}
+
+/*
+ * Curl_pp_readresp()
+ *
+ * Reads a piece of a server response.
+ */
+CURLcode Curl_pp_readresp(curl_socket_t sockfd,
+ struct pingpong *pp,
+ int *code, /* return the server code if done */
+ size_t *size) /* size of the response */
+{
+ ssize_t perline; /* count bytes per line */
bool keepon = TRUE;
- ssize_t gotbytes;
- char *ptr;
- struct connectdata *conn = pp->conn;
+ ssize_t gotbytes;
+ char *ptr;
+ struct connectdata *conn = pp->conn;
struct Curl_easy *data = conn->data;
- char * const buf = data->state.buffer;
- CURLcode result = CURLE_OK;
-
- *code = 0; /* 0 for errors or not done */
- *size = 0;
-
+ char * const buf = data->state.buffer;
+ CURLcode result = CURLE_OK;
+
+ *code = 0; /* 0 for errors or not done */
+ *size = 0;
+
ptr = buf + pp->nread_resp;
-
- /* number of bytes in the current line, so far */
- perline = (ssize_t)(ptr-pp->linestart_resp);
-
+
+ /* number of bytes in the current line, so far */
+ perline = (ssize_t)(ptr-pp->linestart_resp);
+
while((pp->nread_resp < (size_t)data->set.buffer_size) &&
(keepon && !result)) {
-
- if(pp->cache) {
- /* we had data in the "cache", copy that instead of doing an actual
- * read
- *
- * pp->cache_size is cast to ssize_t here. This should be safe, because
- * it would have been populated with something of size int to begin
- * with, even though its datatype may be larger than an int.
- */
+
+ if(pp->cache) {
+ /* we had data in the "cache", copy that instead of doing an actual
+ * read
+ *
+ * pp->cache_size is cast to ssize_t here. This should be safe, because
+ * it would have been populated with something of size int to begin
+ * with, even though its datatype may be larger than an int.
+ */
if((ptr + pp->cache_size) > (buf + data->set.buffer_size + 1)) {
failf(data, "cached response data too big to handle");
return CURLE_RECV_ERROR;
}
- memcpy(ptr, pp->cache, pp->cache_size);
- gotbytes = (ssize_t)pp->cache_size;
- free(pp->cache); /* free the cache */
- pp->cache = NULL; /* clear the pointer */
- pp->cache_size = 0; /* zero the size just in case */
- }
- else {
-#ifdef HAVE_GSSAPI
- enum protection_level prot = conn->data_prot;
- conn->data_prot = PROT_CLEAR;
-#endif
+ memcpy(ptr, pp->cache, pp->cache_size);
+ gotbytes = (ssize_t)pp->cache_size;
+ free(pp->cache); /* free the cache */
+ pp->cache = NULL; /* clear the pointer */
+ pp->cache_size = 0; /* zero the size just in case */
+ }
+ else {
+#ifdef HAVE_GSSAPI
+ enum protection_level prot = conn->data_prot;
+ conn->data_prot = PROT_CLEAR;
+#endif
DEBUGASSERT((ptr + data->set.buffer_size - pp->nread_resp) <=
(buf + data->set.buffer_size + 1));
result = Curl_read(conn, sockfd, ptr,
data->set.buffer_size - pp->nread_resp,
&gotbytes);
-#ifdef HAVE_GSSAPI
- DEBUGASSERT(prot > PROT_NONE && prot < PROT_LAST);
- conn->data_prot = prot;
-#endif
+#ifdef HAVE_GSSAPI
+ DEBUGASSERT(prot > PROT_NONE && prot < PROT_LAST);
+ conn->data_prot = prot;
+#endif
if(result == CURLE_AGAIN)
- return CURLE_OK; /* return */
-
+ return CURLE_OK; /* return */
+
if(!result && (gotbytes > 0))
- /* convert from the network encoding */
+ /* convert from the network encoding */
result = Curl_convert_from_network(data, ptr, gotbytes);
- /* Curl_convert_from_network calls failf if unsuccessful */
-
+ /* Curl_convert_from_network calls failf if unsuccessful */
+
if(result)
/* Set outer result variable to this error. */
- keepon = FALSE;
- }
-
- if(!keepon)
- ;
- else if(gotbytes <= 0) {
- keepon = FALSE;
- result = CURLE_RECV_ERROR;
- failf(data, "response reading failed");
- }
- else {
- /* we got a whole chunk of data, which can be anything from one
- * byte to a set of lines and possible just a piece of the last
- * line */
- ssize_t i;
- ssize_t clipamount = 0;
- bool restart = FALSE;
-
- data->req.headerbytecount += (long)gotbytes;
-
- pp->nread_resp += gotbytes;
- for(i = 0; i < gotbytes; ptr++, i++) {
- perline++;
+ keepon = FALSE;
+ }
+
+ if(!keepon)
+ ;
+ else if(gotbytes <= 0) {
+ keepon = FALSE;
+ result = CURLE_RECV_ERROR;
+ failf(data, "response reading failed");
+ }
+ else {
+ /* we got a whole chunk of data, which can be anything from one
+ * byte to a set of lines and possible just a piece of the last
+ * line */
+ ssize_t i;
+ ssize_t clipamount = 0;
+ bool restart = FALSE;
+
+ data->req.headerbytecount += (long)gotbytes;
+
+ pp->nread_resp += gotbytes;
+ for(i = 0; i < gotbytes; ptr++, i++) {
+ perline++;
if(*ptr == '\n') {
- /* a newline is CRLF in pp-talk, so the CR is ignored as
- the line isn't really terminated until the LF comes */
-
- /* output debug output if that is requested */
-#ifdef HAVE_GSSAPI
- if(!conn->sec_complete)
-#endif
+ /* a newline is CRLF in pp-talk, so the CR is ignored as
+ the line isn't really terminated until the LF comes */
+
+ /* output debug output if that is requested */
+#ifdef HAVE_GSSAPI
+ if(!conn->sec_complete)
+#endif
Curl_debug(data, CURLINFO_HEADER_IN,
pp->linestart_resp, (size_t)perline);
-
- /*
- * We pass all response-lines to the callback function registered
- * for "headers". The response lines can be seen as a kind of
- * headers.
- */
- result = Curl_client_write(conn, CLIENTWRITE_HEADER,
- pp->linestart_resp, perline);
- if(result)
- return result;
-
- if(pp->endofresp(conn, pp->linestart_resp, perline, code)) {
- /* This is the end of the last line, copy the last line to the
+
+ /*
+ * We pass all response-lines to the callback function registered
+ * for "headers". The response lines can be seen as a kind of
+ * headers.
+ */
+ result = Curl_client_write(conn, CLIENTWRITE_HEADER,
+ pp->linestart_resp, perline);
+ if(result)
+ return result;
+
+ if(pp->endofresp(conn, pp->linestart_resp, perline, code)) {
+ /* This is the end of the last line, copy the last line to the
start of the buffer and null-terminate, for old times sake */
size_t n = ptr - pp->linestart_resp;
memmove(buf, pp->linestart_resp, n);
buf[n] = 0; /* null-terminate */
keepon = FALSE;
pp->linestart_resp = ptr + 1; /* advance pointer */
- i++; /* skip this before getting out */
-
- *size = pp->nread_resp; /* size of the response */
- pp->nread_resp = 0; /* restart */
- break;
- }
+ i++; /* skip this before getting out */
+
+ *size = pp->nread_resp; /* size of the response */
+ pp->nread_resp = 0; /* restart */
+ break;
+ }
perline = 0; /* line starts over here */
pp->linestart_resp = ptr + 1;
- }
- }
-
- if(!keepon && (i != gotbytes)) {
- /* We found the end of the response lines, but we didn't parse the
- full chunk of data we have read from the server. We therefore need
- to store the rest of the data to be checked on the next invoke as
- it may actually contain another end of response already! */
- clipamount = gotbytes - i;
- restart = TRUE;
- DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing "
- "server response left\n",
- (int)clipamount));
- }
- else if(keepon) {
-
+ }
+ }
+
+ if(!keepon && (i != gotbytes)) {
+ /* We found the end of the response lines, but we didn't parse the
+ full chunk of data we have read from the server. We therefore need
+ to store the rest of the data to be checked on the next invoke as
+ it may actually contain another end of response already! */
+ clipamount = gotbytes - i;
+ restart = TRUE;
+ DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing "
+ "server response left\n",
+ (int)clipamount));
+ }
+ else if(keepon) {
+
if((perline == gotbytes) && (gotbytes > data->set.buffer_size/2)) {
- /* We got an excessive line without newlines and we need to deal
- with it. We keep the first bytes of the line then we throw
- away the rest. */
- infof(data, "Excessive server response line length received, "
- "%zd bytes. Stripping\n", gotbytes);
- restart = TRUE;
-
- /* we keep 40 bytes since all our pingpong protocols are only
- interested in the first piece */
- clipamount = 40;
- }
+ /* We got an excessive line without newlines and we need to deal
+ with it. We keep the first bytes of the line then we throw
+ away the rest. */
+ infof(data, "Excessive server response line length received, "
+ "%zd bytes. Stripping\n", gotbytes);
+ restart = TRUE;
+
+ /* we keep 40 bytes since all our pingpong protocols are only
+ interested in the first piece */
+ clipamount = 40;
+ }
else if(pp->nread_resp > (size_t)data->set.buffer_size/2) {
- /* We got a large chunk of data and there's potentially still
- trailing data to take care of, so we put any such part in the
- "cache", clear the buffer to make space and restart. */
- clipamount = perline;
- restart = TRUE;
- }
- }
- else if(i == gotbytes)
- restart = TRUE;
-
- if(clipamount) {
- pp->cache_size = clipamount;
- pp->cache = malloc(pp->cache_size);
- if(pp->cache)
- memcpy(pp->cache, pp->linestart_resp, pp->cache_size);
- else
- return CURLE_OUT_OF_MEMORY;
- }
- if(restart) {
- /* now reset a few variables to start over nicely from the start of
- the big buffer */
- pp->nread_resp = 0; /* start over from scratch in the buffer */
- ptr = pp->linestart_resp = buf;
- perline = 0;
- }
-
- } /* there was data */
-
- } /* while there's buffer left and loop is requested */
-
- pp->pending_resp = FALSE;
-
- return result;
-}
-
-int Curl_pp_getsock(struct pingpong *pp,
+ /* We got a large chunk of data and there's potentially still
+ trailing data to take care of, so we put any such part in the
+ "cache", clear the buffer to make space and restart. */
+ clipamount = perline;
+ restart = TRUE;
+ }
+ }
+ else if(i == gotbytes)
+ restart = TRUE;
+
+ if(clipamount) {
+ pp->cache_size = clipamount;
+ pp->cache = malloc(pp->cache_size);
+ if(pp->cache)
+ memcpy(pp->cache, pp->linestart_resp, pp->cache_size);
+ else
+ return CURLE_OUT_OF_MEMORY;
+ }
+ if(restart) {
+ /* now reset a few variables to start over nicely from the start of
+ the big buffer */
+ pp->nread_resp = 0; /* start over from scratch in the buffer */
+ ptr = pp->linestart_resp = buf;
+ perline = 0;
+ }
+
+ } /* there was data */
+
+ } /* while there's buffer left and loop is requested */
+
+ pp->pending_resp = FALSE;
+
+ return result;
+}
+
+int Curl_pp_getsock(struct pingpong *pp,
curl_socket_t *socks)
-{
- struct connectdata *conn = pp->conn;
- socks[0] = conn->sock[FIRSTSOCKET];
-
- if(pp->sendleft) {
- /* write mode */
- return GETSOCK_WRITESOCK(0);
- }
-
- /* read mode */
- return GETSOCK_READSOCK(0);
-}
-
-CURLcode Curl_pp_flushsend(struct pingpong *pp)
-{
- /* we have a piece of a command still left to send */
- struct connectdata *conn = pp->conn;
- ssize_t written;
- curl_socket_t sock = conn->sock[FIRSTSOCKET];
+{
+ struct connectdata *conn = pp->conn;
+ socks[0] = conn->sock[FIRSTSOCKET];
+
+ if(pp->sendleft) {
+ /* write mode */
+ return GETSOCK_WRITESOCK(0);
+ }
+
+ /* read mode */
+ return GETSOCK_READSOCK(0);
+}
+
+CURLcode Curl_pp_flushsend(struct pingpong *pp)
+{
+ /* we have a piece of a command still left to send */
+ struct connectdata *conn = pp->conn;
+ ssize_t written;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
CURLcode result = Curl_write(conn, sock, pp->sendthis + pp->sendsize -
pp->sendleft, pp->sendleft, &written);
- if(result)
- return result;
-
- if(written != (ssize_t)pp->sendleft) {
- /* only a fraction was sent */
- pp->sendleft -= written;
- }
- else {
+ if(result)
+ return result;
+
+ if(written != (ssize_t)pp->sendleft) {
+ /* only a fraction was sent */
+ pp->sendleft -= written;
+ }
+ else {
pp->sendthis = NULL;
- pp->sendleft = pp->sendsize = 0;
+ pp->sendleft = pp->sendsize = 0;
pp->response = Curl_now();
- }
- return CURLE_OK;
-}
-
-CURLcode Curl_pp_disconnect(struct pingpong *pp)
-{
+ }
+ return CURLE_OK;
+}
+
+CURLcode Curl_pp_disconnect(struct pingpong *pp)
+{
Curl_dyn_free(&pp->sendbuf);
Curl_safefree(pp->cache);
- return CURLE_OK;
-}
-
-bool Curl_pp_moredata(struct pingpong *pp)
-{
- return (!pp->sendleft && pp->cache && pp->nread_resp < pp->cache_size) ?
+ return CURLE_OK;
+}
+
+bool Curl_pp_moredata(struct pingpong *pp)
+{
+ return (!pp->sendleft && pp->cache && pp->nread_resp < pp->cache_size) ?
TRUE : FALSE;
-}
-
-#endif
+}
+
+#endif
diff --git a/contrib/libs/curl/lib/pingpong.h b/contrib/libs/curl/lib/pingpong.h
index 7b914eb5d8..0d0c74afa0 100644
--- a/contrib/libs/curl/lib/pingpong.h
+++ b/contrib/libs/curl/lib/pingpong.h
@@ -1,153 +1,153 @@
-#ifndef HEADER_CURL_PINGPONG_H
-#define HEADER_CURL_PINGPONG_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_PINGPONG_H
+#define HEADER_CURL_PINGPONG_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_FTP) || \
- !defined(CURL_DISABLE_POP3) || !defined(CURL_DISABLE_SMTP)
-#define USE_PINGPONG
-#endif
-
-/* forward-declaration, this is defined in urldata.h */
-struct connectdata;
-
-typedef enum {
- FTPTRANSFER_BODY, /* yes do transfer a body */
- FTPTRANSFER_INFO, /* do still go through to get info/headers */
- FTPTRANSFER_NONE, /* don't get anything and don't get info */
- FTPTRANSFER_LAST /* end of list marker, never used */
-} curl_pp_transfer;
-
-/*
- * 'pingpong' is the generic struct used for protocols doing server<->client
- * conversations in a back-and-forth style such as FTP, IMAP, POP3, SMTP etc.
- *
- * It holds response cache and non-blocking sending data.
- */
-struct pingpong {
- char *cache; /* data cache between getresponse()-calls */
- size_t cache_size; /* size of cache in bytes */
- size_t nread_resp; /* number of bytes currently read of a server response */
- char *linestart_resp; /* line start pointer for the server response
- reader function */
- bool pending_resp; /* set TRUE when a server response is pending or in
- progress, and is cleared once the last response is
- read */
- char *sendthis; /* allocated pointer to a buffer that is to be sent to the
- server */
- size_t sendleft; /* number of bytes left to send from the sendthis buffer */
- size_t sendsize; /* total size of the sendthis buffer */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_FTP) || \
+ !defined(CURL_DISABLE_POP3) || !defined(CURL_DISABLE_SMTP)
+#define USE_PINGPONG
+#endif
+
+/* forward-declaration, this is defined in urldata.h */
+struct connectdata;
+
+typedef enum {
+ FTPTRANSFER_BODY, /* yes do transfer a body */
+ FTPTRANSFER_INFO, /* do still go through to get info/headers */
+ FTPTRANSFER_NONE, /* don't get anything and don't get info */
+ FTPTRANSFER_LAST /* end of list marker, never used */
+} curl_pp_transfer;
+
+/*
+ * 'pingpong' is the generic struct used for protocols doing server<->client
+ * conversations in a back-and-forth style such as FTP, IMAP, POP3, SMTP etc.
+ *
+ * It holds response cache and non-blocking sending data.
+ */
+struct pingpong {
+ char *cache; /* data cache between getresponse()-calls */
+ size_t cache_size; /* size of cache in bytes */
+ size_t nread_resp; /* number of bytes currently read of a server response */
+ char *linestart_resp; /* line start pointer for the server response
+ reader function */
+ bool pending_resp; /* set TRUE when a server response is pending or in
+ progress, and is cleared once the last response is
+ read */
+ char *sendthis; /* allocated pointer to a buffer that is to be sent to the
+ server */
+ size_t sendleft; /* number of bytes left to send from the sendthis buffer */
+ size_t sendsize; /* total size of the sendthis buffer */
struct curltime response; /* set to Curl_now() when a command has been sent
off, used to time-out response reading */
timediff_t response_time; /* When no timeout is given, this is the amount of
milliseconds we await for a server response. */
- struct connectdata *conn; /* points to the connectdata struct that this
- belongs to */
+ struct connectdata *conn; /* points to the connectdata struct that this
+ belongs to */
struct dynbuf sendbuf;
-
- /* Function pointers the protocols MUST implement and provide for the
- pingpong layer to function */
-
- CURLcode (*statemach_act)(struct connectdata *conn);
-
- bool (*endofresp)(struct connectdata *conn, char *ptr, size_t len,
- int *code);
-};
-
-/*
- * Curl_pp_statemach()
- *
- * called repeatedly until done. Set 'wait' to make it wait a while on the
- * socket if there's no traffic.
- */
+
+ /* Function pointers the protocols MUST implement and provide for the
+ pingpong layer to function */
+
+ CURLcode (*statemach_act)(struct connectdata *conn);
+
+ bool (*endofresp)(struct connectdata *conn, char *ptr, size_t len,
+ int *code);
+};
+
+/*
+ * Curl_pp_statemach()
+ *
+ * called repeatedly until done. Set 'wait' to make it wait a while on the
+ * socket if there's no traffic.
+ */
CURLcode Curl_pp_statemach(struct pingpong *pp, bool block,
bool disconnecting);
-
-/* initialize stuff to prepare for reading a fresh new response */
-void Curl_pp_init(struct pingpong *pp);
-
+
+/* initialize stuff to prepare for reading a fresh new response */
+void Curl_pp_init(struct pingpong *pp);
+
/* setup for the transfer */
void Curl_pp_setup(struct pingpong *pp);
-/* Returns timeout in ms. 0 or negative number means the timeout has already
- triggered */
+/* Returns timeout in ms. 0 or negative number means the timeout has already
+ triggered */
timediff_t Curl_pp_state_timeout(struct pingpong *pp, bool disconnecting);
-
-
-/***********************************************************************
- *
- * Curl_pp_sendf()
- *
+
+
+/***********************************************************************
+ *
+ * Curl_pp_sendf()
+ *
* Send the formatted string as a command to a pingpong server. Note that
- * the string should not have any CRLF appended, as this function will
- * append the necessary things itself.
- *
- * made to never block
- */
-CURLcode Curl_pp_sendf(struct pingpong *pp,
- const char *fmt, ...);
-
-/***********************************************************************
- *
- * Curl_pp_vsendf()
- *
+ * the string should not have any CRLF appended, as this function will
+ * append the necessary things itself.
+ *
+ * made to never block
+ */
+CURLcode Curl_pp_sendf(struct pingpong *pp,
+ const char *fmt, ...);
+
+/***********************************************************************
+ *
+ * Curl_pp_vsendf()
+ *
* Send the formatted string as a command to a pingpong server. Note that
- * the string should not have any CRLF appended, as this function will
- * append the necessary things itself.
- *
- * made to never block
- */
-CURLcode Curl_pp_vsendf(struct pingpong *pp,
- const char *fmt,
- va_list args);
-
-/*
- * Curl_pp_readresp()
- *
- * Reads a piece of a server response.
- */
-CURLcode Curl_pp_readresp(curl_socket_t sockfd,
- struct pingpong *pp,
- int *code, /* return the server code if done */
- size_t *size); /* size of the response */
-
-
-CURLcode Curl_pp_flushsend(struct pingpong *pp);
-
-/* call this when a pingpong connection is disconnected */
-CURLcode Curl_pp_disconnect(struct pingpong *pp);
-
+ * the string should not have any CRLF appended, as this function will
+ * append the necessary things itself.
+ *
+ * made to never block
+ */
+CURLcode Curl_pp_vsendf(struct pingpong *pp,
+ const char *fmt,
+ va_list args);
+
+/*
+ * Curl_pp_readresp()
+ *
+ * Reads a piece of a server response.
+ */
+CURLcode Curl_pp_readresp(curl_socket_t sockfd,
+ struct pingpong *pp,
+ int *code, /* return the server code if done */
+ size_t *size); /* size of the response */
+
+
+CURLcode Curl_pp_flushsend(struct pingpong *pp);
+
+/* call this when a pingpong connection is disconnected */
+CURLcode Curl_pp_disconnect(struct pingpong *pp);
+
int Curl_pp_getsock(struct pingpong *pp, curl_socket_t *socks);
-
-
-/***********************************************************************
- *
- * Curl_pp_moredata()
- *
- * Returns whether there are still more data in the cache and so a call
- * to Curl_pp_readresp() will not block.
- */
-bool Curl_pp_moredata(struct pingpong *pp);
-
-#endif /* HEADER_CURL_PINGPONG_H */
+
+
+/***********************************************************************
+ *
+ * Curl_pp_moredata()
+ *
+ * Returns whether there are still more data in the cache and so a call
+ * to Curl_pp_readresp() will not block.
+ */
+bool Curl_pp_moredata(struct pingpong *pp);
+
+#endif /* HEADER_CURL_PINGPONG_H */
diff --git a/contrib/libs/curl/lib/pop3.c b/contrib/libs/curl/lib/pop3.c
index 9e20a62c8a..e71860e48a 100644
--- a/contrib/libs/curl/lib/pop3.c
+++ b/contrib/libs/curl/lib/pop3.c
@@ -1,167 +1,167 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * RFC1734 POP3 Authentication
- * RFC1939 POP3 protocol
- * RFC2195 CRAM-MD5 authentication
- * RFC2384 POP URL Scheme
- * RFC2449 POP3 Extension Mechanism
- * RFC2595 Using TLS with IMAP, POP3 and ACAP
- * RFC2831 DIGEST-MD5 authentication
- * RFC4422 Simple Authentication and Security Layer (SASL)
- * RFC4616 PLAIN authentication
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * RFC1734 POP3 Authentication
+ * RFC1939 POP3 protocol
+ * RFC2195 CRAM-MD5 authentication
+ * RFC2384 POP URL Scheme
+ * RFC2449 POP3 Extension Mechanism
+ * RFC2595 Using TLS with IMAP, POP3 and ACAP
+ * RFC2831 DIGEST-MD5 authentication
+ * RFC4422 Simple Authentication and Security Layer (SASL)
+ * RFC4616 PLAIN authentication
* RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
- * RFC5034 POP3 SASL Authentication Mechanism
- * RFC6749 OAuth 2.0 Authorization Framework
+ * RFC5034 POP3 SASL Authentication Mechanism
+ * RFC6749 OAuth 2.0 Authorization Framework
* RFC8314 Use of TLS for Email Submission and Access
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_POP3
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_UTSNAME_H
-#include <sys/utsname.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-#include <curl/curl.h>
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "progress.h"
-#include "transfer.h"
-#include "escape.h"
-#include "http.h" /* for HTTP proxy tunnel stuff */
-#include "socks.h"
-#include "pop3.h"
-#include "strtoofft.h"
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_POP3
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_UTSNAME_H
+#include <sys/utsname.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "progress.h"
+#include "transfer.h"
+#include "escape.h"
+#include "http.h" /* for HTTP proxy tunnel stuff */
+#include "socks.h"
+#include "pop3.h"
+#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
-#include "connect.h"
-#include "strerror.h"
-#include "select.h"
-#include "multiif.h"
-#include "url.h"
-#include "curl_sasl.h"
-#include "curl_md5.h"
-#include "warnless.h"
+#include "connect.h"
+#include "strerror.h"
+#include "select.h"
+#include "multiif.h"
+#include "url.h"
+#include "curl_sasl.h"
+#include "curl_md5.h"
+#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* Local API functions */
-static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *done);
-static CURLcode pop3_do(struct connectdata *conn, bool *done);
-static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
- bool premature);
-static CURLcode pop3_connect(struct connectdata *conn, bool *done);
-static CURLcode pop3_disconnect(struct connectdata *conn, bool dead);
-static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done);
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* Local API functions */
+static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *done);
+static CURLcode pop3_do(struct connectdata *conn, bool *done);
+static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
+ bool premature);
+static CURLcode pop3_connect(struct connectdata *conn, bool *done);
+static CURLcode pop3_disconnect(struct connectdata *conn, bool dead);
+static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done);
static int pop3_getsock(struct connectdata *conn, curl_socket_t *socks);
-static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done);
-static CURLcode pop3_setup_connection(struct connectdata *conn);
-static CURLcode pop3_parse_url_options(struct connectdata *conn);
-static CURLcode pop3_parse_url_path(struct connectdata *conn);
-static CURLcode pop3_parse_custom_request(struct connectdata *conn);
+static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done);
+static CURLcode pop3_setup_connection(struct connectdata *conn);
+static CURLcode pop3_parse_url_options(struct connectdata *conn);
+static CURLcode pop3_parse_url_path(struct connectdata *conn);
+static CURLcode pop3_parse_custom_request(struct connectdata *conn);
static CURLcode pop3_perform_auth(struct connectdata *conn, const char *mech,
const char *initresp);
static CURLcode pop3_continue_auth(struct connectdata *conn, const char *resp);
static void pop3_get_message(char *buffer, char **outptr);
-
-/*
- * POP3 protocol handler.
- */
-
-const struct Curl_handler Curl_handler_pop3 = {
- "POP3", /* scheme */
- pop3_setup_connection, /* setup_connection */
- pop3_do, /* do_it */
- pop3_done, /* done */
- ZERO_NULL, /* do_more */
- pop3_connect, /* connect_it */
- pop3_multi_statemach, /* connecting */
- pop3_doing, /* doing */
- pop3_getsock, /* proto_getsock */
- pop3_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- pop3_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+
+/*
+ * POP3 protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_pop3 = {
+ "POP3", /* scheme */
+ pop3_setup_connection, /* setup_connection */
+ pop3_do, /* do_it */
+ pop3_done, /* done */
+ ZERO_NULL, /* do_more */
+ pop3_connect, /* connect_it */
+ pop3_multi_statemach, /* connecting */
+ pop3_doing, /* doing */
+ pop3_getsock, /* proto_getsock */
+ pop3_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ pop3_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_POP3, /* defport */
- CURLPROTO_POP3, /* protocol */
+ PORT_POP3, /* defport */
+ CURLPROTO_POP3, /* protocol */
CURLPROTO_POP3, /* family */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */
PROTOPT_URLOPTIONS
-};
-
-#ifdef USE_SSL
-/*
- * POP3S protocol handler.
- */
-
-const struct Curl_handler Curl_handler_pop3s = {
- "POP3S", /* scheme */
- pop3_setup_connection, /* setup_connection */
- pop3_do, /* do_it */
- pop3_done, /* done */
- ZERO_NULL, /* do_more */
- pop3_connect, /* connect_it */
- pop3_multi_statemach, /* connecting */
- pop3_doing, /* doing */
- pop3_getsock, /* proto_getsock */
- pop3_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- pop3_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+};
+
+#ifdef USE_SSL
+/*
+ * POP3S protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_pop3s = {
+ "POP3S", /* scheme */
+ pop3_setup_connection, /* setup_connection */
+ pop3_do, /* do_it */
+ pop3_done, /* done */
+ ZERO_NULL, /* do_more */
+ pop3_connect, /* connect_it */
+ pop3_multi_statemach, /* connecting */
+ pop3_doing, /* doing */
+ pop3_getsock, /* proto_getsock */
+ pop3_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ pop3_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_POP3S, /* defport */
+ PORT_POP3S, /* defport */
CURLPROTO_POP3S, /* protocol */
CURLPROTO_POP3, /* family */
- PROTOPT_CLOSEACTION | PROTOPT_SSL
+ PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */
-};
-#endif
-
+};
+#endif
+
/* SASL parameters for the pop3 protocol */
static const struct SASLproto saslpop3 = {
"pop", /* The service name */
@@ -171,72 +171,72 @@ static const struct SASLproto saslpop3 = {
pop3_perform_auth, /* Send authentication command */
pop3_continue_auth, /* Send authentication continuation */
pop3_get_message /* Get SASL response message */
-};
-
-#ifdef USE_SSL
-static void pop3_to_pop3s(struct connectdata *conn)
-{
+};
+
+#ifdef USE_SSL
+static void pop3_to_pop3s(struct connectdata *conn)
+{
/* Change the connection handler */
- conn->handler = &Curl_handler_pop3s;
+ conn->handler = &Curl_handler_pop3s;
/* Set the connection's upgraded to TLS flag */
conn->bits.tls_upgraded = TRUE;
-}
-#else
-#define pop3_to_pop3s(x) Curl_nop_stmt
-#endif
-
-/***********************************************************************
- *
- * pop3_endofresp()
- *
- * Checks for an ending POP3 status code at the start of the given string, but
- * also detects the APOP timestamp from the server greeting and various
- * capabilities from the CAPA response including the supported authentication
- * types and allowed SASL mechanisms.
- */
-static bool pop3_endofresp(struct connectdata *conn, char *line, size_t len,
- int *resp)
-{
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-
- /* Do we have an error response? */
- if(len >= 4 && !memcmp("-ERR", line, 4)) {
- *resp = '-';
-
- return TRUE;
- }
-
- /* Are we processing CAPA command responses? */
+}
+#else
+#define pop3_to_pop3s(x) Curl_nop_stmt
+#endif
+
+/***********************************************************************
+ *
+ * pop3_endofresp()
+ *
+ * Checks for an ending POP3 status code at the start of the given string, but
+ * also detects the APOP timestamp from the server greeting and various
+ * capabilities from the CAPA response including the supported authentication
+ * types and allowed SASL mechanisms.
+ */
+static bool pop3_endofresp(struct connectdata *conn, char *line, size_t len,
+ int *resp)
+{
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+
+ /* Do we have an error response? */
+ if(len >= 4 && !memcmp("-ERR", line, 4)) {
+ *resp = '-';
+
+ return TRUE;
+ }
+
+ /* Are we processing CAPA command responses? */
if(pop3c->state == POP3_CAPA) {
- /* Do we have the terminating line? */
+ /* Do we have the terminating line? */
if(len >= 1 && line[0] == '.')
/* Treat the response as a success */
- *resp = '+';
+ *resp = '+';
else
/* Treat the response as an untagged continuation */
*resp = '*';
-
+
return TRUE;
}
-
+
/* Do we have a success response? */
if(len >= 3 && !memcmp("+OK", line, 3)) {
*resp = '+';
-
+
return TRUE;
}
-
+
/* Do we have a continuation response? */
if(len >= 1 && line[0] == '+') {
*resp = '*';
-
+
return TRUE;
}
-
+
return FALSE; /* Nothing for us */
}
-
+
/***********************************************************************
*
* pop3_get_message()
@@ -247,238 +247,238 @@ static void pop3_get_message(char *buffer, char **outptr)
{
size_t len = strlen(buffer);
char *message = NULL;
-
+
if(len > 2) {
/* Find the start of the message */
len -= 2;
for(message = buffer + 2; *message == ' ' || *message == '\t';
message++, len--)
;
-
+
/* Find the end of the message */
for(; len--;)
if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
message[len] != '\t')
break;
-
+
/* Terminate the message */
if(++len) {
message[len] = '\0';
- }
- }
+ }
+ }
else
/* junk input => zero length output */
message = &buffer[len];
-
+
*outptr = message;
-}
-
-/***********************************************************************
- *
- * state()
- *
- * This is the ONLY way to change POP3 state!
- */
-static void state(struct connectdata *conn, pop3state newstate)
-{
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
- /* for debug purposes */
- static const char * const names[] = {
- "STOP",
- "SERVERGREET",
- "CAPA",
- "STARTTLS",
- "UPGRADETLS",
+}
+
+/***********************************************************************
+ *
+ * state()
+ *
+ * This is the ONLY way to change POP3 state!
+ */
+static void state(struct connectdata *conn, pop3state newstate)
+{
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
+ /* for debug purposes */
+ static const char * const names[] = {
+ "STOP",
+ "SERVERGREET",
+ "CAPA",
+ "STARTTLS",
+ "UPGRADETLS",
"AUTH",
- "APOP",
- "USER",
- "PASS",
- "COMMAND",
- "QUIT",
- /* LAST */
- };
-
- if(pop3c->state != newstate)
- infof(conn->data, "POP3 %p state change from %s to %s\n",
- (void *)pop3c, names[pop3c->state], names[newstate]);
-#endif
-
- pop3c->state = newstate;
-}
-
-/***********************************************************************
- *
- * pop3_perform_capa()
- *
- * Sends the CAPA command in order to obtain a list of server side supported
- * capabilities.
- */
-static CURLcode pop3_perform_capa(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-
+ "APOP",
+ "USER",
+ "PASS",
+ "COMMAND",
+ "QUIT",
+ /* LAST */
+ };
+
+ if(pop3c->state != newstate)
+ infof(conn->data, "POP3 %p state change from %s to %s\n",
+ (void *)pop3c, names[pop3c->state], names[newstate]);
+#endif
+
+ pop3c->state = newstate;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform_capa()
+ *
+ * Sends the CAPA command in order to obtain a list of server side supported
+ * capabilities.
+ */
+static CURLcode pop3_perform_capa(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+
pop3c->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */
pop3c->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */
pop3c->tls_supported = FALSE; /* Clear the TLS capability */
-
- /* Send the CAPA command */
- result = Curl_pp_sendf(&pop3c->pp, "%s", "CAPA");
-
- if(!result)
- state(conn, POP3_CAPA);
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_perform_starttls()
- *
- * Sends the STLS command to start the upgrade to TLS.
- */
-static CURLcode pop3_perform_starttls(struct connectdata *conn)
-{
- /* Send the STLS command */
+
+ /* Send the CAPA command */
+ result = Curl_pp_sendf(&pop3c->pp, "%s", "CAPA");
+
+ if(!result)
+ state(conn, POP3_CAPA);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform_starttls()
+ *
+ * Sends the STLS command to start the upgrade to TLS.
+ */
+static CURLcode pop3_perform_starttls(struct connectdata *conn)
+{
+ /* Send the STLS command */
CURLcode result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "STLS");
-
- if(!result)
- state(conn, POP3_STARTTLS);
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_perform_upgrade_tls()
- *
- * Performs the upgrade to TLS.
- */
-static CURLcode pop3_perform_upgrade_tls(struct connectdata *conn)
-{
+
+ if(!result)
+ state(conn, POP3_STARTTLS);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform_upgrade_tls()
+ *
+ * Performs the upgrade to TLS.
+ */
+static CURLcode pop3_perform_upgrade_tls(struct connectdata *conn)
+{
/* Start the SSL connection */
- struct pop3_conn *pop3c = &conn->proto.pop3c;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
CURLcode result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET,
&pop3c->ssldone);
-
- if(!result) {
- if(pop3c->state != POP3_UPGRADETLS)
- state(conn, POP3_UPGRADETLS);
-
- if(pop3c->ssldone) {
- pop3_to_pop3s(conn);
- result = pop3_perform_capa(conn);
- }
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_perform_user()
- *
- * Sends a clear text USER command to authenticate with.
- */
-static CURLcode pop3_perform_user(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
-
- /* Check we have a username and password to authenticate with and end the
- connect phase if we don't */
- if(!conn->bits.user_passwd) {
- state(conn, POP3_STOP);
-
- return result;
- }
-
- /* Send the USER command */
- result = Curl_pp_sendf(&conn->proto.pop3c.pp, "USER %s",
- conn->user ? conn->user : "");
- if(!result)
- state(conn, POP3_USER);
-
- return result;
-}
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
-/***********************************************************************
- *
- * pop3_perform_apop()
- *
- * Sends an APOP command to authenticate with.
- */
-static CURLcode pop3_perform_apop(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
- size_t i;
+
+ if(!result) {
+ if(pop3c->state != POP3_UPGRADETLS)
+ state(conn, POP3_UPGRADETLS);
+
+ if(pop3c->ssldone) {
+ pop3_to_pop3s(conn);
+ result = pop3_perform_capa(conn);
+ }
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform_user()
+ *
+ * Sends a clear text USER command to authenticate with.
+ */
+static CURLcode pop3_perform_user(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+
+ /* Check we have a username and password to authenticate with and end the
+ connect phase if we don't */
+ if(!conn->bits.user_passwd) {
+ state(conn, POP3_STOP);
+
+ return result;
+ }
+
+ /* Send the USER command */
+ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "USER %s",
+ conn->user ? conn->user : "");
+ if(!result)
+ state(conn, POP3_USER);
+
+ return result;
+}
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+/***********************************************************************
+ *
+ * pop3_perform_apop()
+ *
+ * Sends an APOP command to authenticate with.
+ */
+static CURLcode pop3_perform_apop(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+ size_t i;
struct MD5_context *ctxt;
- unsigned char digest[MD5_DIGEST_LEN];
- char secret[2 * MD5_DIGEST_LEN + 1];
-
- /* Check we have a username and password to authenticate with and end the
- connect phase if we don't */
- if(!conn->bits.user_passwd) {
- state(conn, POP3_STOP);
-
- return result;
- }
-
- /* Create the digest */
- ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
- if(!ctxt)
- return CURLE_OUT_OF_MEMORY;
-
- Curl_MD5_update(ctxt, (const unsigned char *) pop3c->apoptimestamp,
- curlx_uztoui(strlen(pop3c->apoptimestamp)));
-
- Curl_MD5_update(ctxt, (const unsigned char *) conn->passwd,
- curlx_uztoui(strlen(conn->passwd)));
-
- /* Finalise the digest */
- Curl_MD5_final(ctxt, digest);
-
- /* Convert the calculated 16 octet digest into a 32 byte hex string */
- for(i = 0; i < MD5_DIGEST_LEN; i++)
+ unsigned char digest[MD5_DIGEST_LEN];
+ char secret[2 * MD5_DIGEST_LEN + 1];
+
+ /* Check we have a username and password to authenticate with and end the
+ connect phase if we don't */
+ if(!conn->bits.user_passwd) {
+ state(conn, POP3_STOP);
+
+ return result;
+ }
+
+ /* Create the digest */
+ ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
+ if(!ctxt)
+ return CURLE_OUT_OF_MEMORY;
+
+ Curl_MD5_update(ctxt, (const unsigned char *) pop3c->apoptimestamp,
+ curlx_uztoui(strlen(pop3c->apoptimestamp)));
+
+ Curl_MD5_update(ctxt, (const unsigned char *) conn->passwd,
+ curlx_uztoui(strlen(conn->passwd)));
+
+ /* Finalise the digest */
+ Curl_MD5_final(ctxt, digest);
+
+ /* Convert the calculated 16 octet digest into a 32 byte hex string */
+ for(i = 0; i < MD5_DIGEST_LEN; i++)
msnprintf(&secret[2 * i], 3, "%02x", digest[i]);
-
- result = Curl_pp_sendf(&pop3c->pp, "APOP %s %s", conn->user, secret);
-
- if(!result)
- state(conn, POP3_APOP);
-
- return result;
-}
-#endif
-
-/***********************************************************************
- *
+
+ result = Curl_pp_sendf(&pop3c->pp, "APOP %s %s", conn->user, secret);
+
+ if(!result)
+ state(conn, POP3_APOP);
+
+ return result;
+}
+#endif
+
+/***********************************************************************
+ *
* pop3_perform_auth()
- *
+ *
* Sends an AUTH command allowing the client to login with the given SASL
* authentication mechanism.
- */
+ */
static CURLcode pop3_perform_auth(struct connectdata *conn,
const char *mech,
const char *initresp)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+
if(initresp) { /* AUTH <mech> ...<crlf> */
/* Send the AUTH command with the initial response */
result = Curl_pp_sendf(&pop3c->pp, "AUTH %s %s", mech, initresp);
- }
+ }
else {
/* Send the AUTH command */
result = Curl_pp_sendf(&pop3c->pp, "AUTH %s", mech);
}
-
+
return result;
}
-
+
/***********************************************************************
*
* pop3_continue_auth()
@@ -489,10 +489,10 @@ static CURLcode pop3_continue_auth(struct connectdata *conn,
const char *resp)
{
struct pop3_conn *pop3c = &conn->proto.pop3c;
-
+
return Curl_pp_sendf(&pop3c->pp, "%s", resp);
}
-
+
/***********************************************************************
*
* pop3_perform_authentication()
@@ -506,117 +506,117 @@ static CURLcode pop3_perform_authentication(struct connectdata *conn)
CURLcode result = CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
saslprogress progress = SASL_IDLE;
-
+
/* Check we have enough data to authenticate with and end the
connect phase if we don't */
if(!Curl_sasl_can_authenticate(&pop3c->sasl, conn)) {
state(conn, POP3_STOP);
return result;
- }
-
+ }
+
if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_SASL) {
/* Calculate the SASL login details */
result = Curl_sasl_start(&pop3c->sasl, conn, FALSE, &progress);
-
+
if(!result)
if(progress == SASL_INPROGRESS)
state(conn, POP3_AUTH);
}
-
+
if(!result && progress == SASL_IDLE) {
-#ifndef CURL_DISABLE_CRYPTO_AUTH
+#ifndef CURL_DISABLE_CRYPTO_AUTH
if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP)
- /* Perform APOP authentication */
- result = pop3_perform_apop(conn);
+ /* Perform APOP authentication */
+ result = pop3_perform_apop(conn);
else
-#endif
+#endif
if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT)
- /* Perform clear text authentication */
- result = pop3_perform_user(conn);
- else {
- /* Other mechanisms not supported */
- infof(conn->data, "No known authentication mechanisms supported!\n");
- result = CURLE_LOGIN_DENIED;
- }
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_perform_command()
- *
- * Sends a POP3 based command.
- */
-static CURLcode pop3_perform_command(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ /* Perform clear text authentication */
+ result = pop3_perform_user(conn);
+ else {
+ /* Other mechanisms not supported */
+ infof(conn->data, "No known authentication mechanisms supported!\n");
+ result = CURLE_LOGIN_DENIED;
+ }
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform_command()
+ *
+ * Sends a POP3 based command.
+ */
+static CURLcode pop3_perform_command(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct POP3 *pop3 = data->req.p.pop3;
- const char *command = NULL;
-
- /* Calculate the default command */
- if(pop3->id[0] == '\0' || conn->data->set.ftp_list_only) {
- command = "LIST";
-
- if(pop3->id[0] != '\0')
- /* Message specific LIST so skip the BODY transfer */
- pop3->transfer = FTPTRANSFER_INFO;
- }
- else
- command = "RETR";
-
- /* Send the command */
- if(pop3->id[0] != '\0')
- result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s %s",
- (pop3->custom && pop3->custom[0] != '\0' ?
- pop3->custom : command), pop3->id);
- else
- result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s",
- (pop3->custom && pop3->custom[0] != '\0' ?
- pop3->custom : command));
-
- if(!result)
- state(conn, POP3_COMMAND);
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_perform_quit()
- *
- * Performs the quit action prior to sclose() be called.
- */
-static CURLcode pop3_perform_quit(struct connectdata *conn)
-{
- /* Send the QUIT command */
+ const char *command = NULL;
+
+ /* Calculate the default command */
+ if(pop3->id[0] == '\0' || conn->data->set.ftp_list_only) {
+ command = "LIST";
+
+ if(pop3->id[0] != '\0')
+ /* Message specific LIST so skip the BODY transfer */
+ pop3->transfer = FTPTRANSFER_INFO;
+ }
+ else
+ command = "RETR";
+
+ /* Send the command */
+ if(pop3->id[0] != '\0')
+ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s %s",
+ (pop3->custom && pop3->custom[0] != '\0' ?
+ pop3->custom : command), pop3->id);
+ else
+ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s",
+ (pop3->custom && pop3->custom[0] != '\0' ?
+ pop3->custom : command));
+
+ if(!result)
+ state(conn, POP3_COMMAND);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform_quit()
+ *
+ * Performs the quit action prior to sclose() be called.
+ */
+static CURLcode pop3_perform_quit(struct connectdata *conn)
+{
+ /* Send the QUIT command */
CURLcode result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "QUIT");
-
- if(!result)
- state(conn, POP3_QUIT);
-
- return result;
-}
-
-/* For the initial server greeting */
-static CURLcode pop3_state_servergreet_resp(struct connectdata *conn,
- int pop3code,
- pop3state instate)
-{
- CURLcode result = CURLE_OK;
+
+ if(!result)
+ state(conn, POP3_QUIT);
+
+ return result;
+}
+
+/* For the initial server greeting */
+static CURLcode pop3_state_servergreet_resp(struct connectdata *conn,
+ int pop3code,
+ pop3state instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct pop3_conn *pop3c = &conn->proto.pop3c;
const char *line = data->state.buffer;
size_t len = strlen(line);
-
- (void)instate; /* no use for this yet */
-
- if(pop3code != '+') {
- failf(data, "Got unexpected pop3-server response");
+
+ (void)instate; /* no use for this yet */
+
+ if(pop3code != '+') {
+ failf(data, "Got unexpected pop3-server response");
result = CURLE_WEIRD_SERVER_REPLY;
- }
+ }
else {
/* Does the server support APOP authentication? */
if(len >= 4 && line[len - 2] == '>') {
@@ -629,17 +629,17 @@ static CURLcode pop3_state_servergreet_resp(struct connectdata *conn,
char *at;
if(!timestamplen)
break;
-
+
/* Allocate some memory for the timestamp */
pop3c->apoptimestamp = (char *)calloc(1, timestamplen + 1);
-
+
if(!pop3c->apoptimestamp)
break;
-
+
/* Copy the timestamp */
memcpy(pop3c->apoptimestamp, line + i, timestamplen);
pop3c->apoptimestamp[timestamplen] = '\0';
-
+
/* If the timestamp does not contain '@' it is not (as required by
RFC-1939) conformant to the RFC-822 message id syntax, and we
therefore do not use APOP authentication. */
@@ -652,77 +652,77 @@ static CURLcode pop3_state_servergreet_resp(struct connectdata *conn,
break;
}
}
- }
+ }
result = pop3_perform_capa(conn);
- }
-
- return result;
-}
-
+ }
+
+ return result;
+}
+
/* For CAPA responses */
static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code,
pop3state instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct pop3_conn *pop3c = &conn->proto.pop3c;
const char *line = data->state.buffer;
size_t len = strlen(line);
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
/* Do we have a untagged continuation response? */
if(pop3code == '*') {
/* Does the server support the STLS capability? */
if(len >= 4 && !memcmp(line, "STLS", 4))
pop3c->tls_supported = TRUE;
-
+
/* Does the server support clear text authentication? */
else if(len >= 4 && !memcmp(line, "USER", 4))
pop3c->authtypes |= POP3_TYPE_CLEARTEXT;
-
+
/* Does the server support SASL based authentication? */
else if(len >= 5 && !memcmp(line, "SASL ", 5)) {
pop3c->authtypes |= POP3_TYPE_SASL;
-
+
/* Advance past the SASL keyword */
line += 5;
len -= 5;
-
+
/* Loop through the data line */
for(;;) {
size_t llen;
size_t wordlen;
unsigned int mechbit;
-
+
while(len &&
(*line == ' ' || *line == '\t' ||
*line == '\r' || *line == '\n')) {
-
+
line++;
len--;
}
-
+
if(!len)
break;
-
+
/* Extract the word */
for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
line[wordlen] != '\t' && line[wordlen] != '\r' &&
line[wordlen] != '\n';)
wordlen++;
-
+
/* Test the word for a matching authentication mechanism */
mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
if(mechbit && llen == wordlen)
pop3c->sasl.authmechs |= mechbit;
-
+
line += wordlen;
len -= wordlen;
- }
- }
- }
+ }
+ }
+ }
else if(pop3code == '+') {
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested */
@@ -735,57 +735,57 @@ static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code,
else {
failf(data, "STLS not supported.");
result = CURLE_USE_SSL_FAILED;
- }
- }
+ }
+ }
else
result = pop3_perform_authentication(conn);
- }
- else {
+ }
+ else {
/* Clear text is supported when CAPA isn't recognised */
pop3c->authtypes |= POP3_TYPE_CLEARTEXT;
-
+
result = pop3_perform_authentication(conn);
- }
-
- return result;
-}
-
+ }
+
+ return result;
+}
+
/* For STARTTLS responses */
static CURLcode pop3_state_starttls_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(pop3code != '+') {
+
+ (void)instate; /* no use for this yet */
+
+ if(pop3code != '+') {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied");
result = CURLE_USE_SSL_FAILED;
- }
+ }
else
result = pop3_perform_authentication(conn);
- }
+ }
else
result = pop3_perform_upgrade_tls(conn);
-
- return result;
-}
-
+
+ return result;
+}
+
/* For SASL authentication responses */
static CURLcode pop3_state_auth_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct pop3_conn *pop3c = &conn->proto.pop3c;
saslprogress progress;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
result = Curl_sasl_continue(&pop3c->sasl, conn, pop3code, &progress);
if(!result)
switch(progress) {
@@ -798,551 +798,551 @@ static CURLcode pop3_state_auth_resp(struct connectdata *conn,
/* Perform APOP authentication */
result = pop3_perform_apop(conn);
else
-#endif
+#endif
if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT)
/* Perform clear text authentication */
result = pop3_perform_user(conn);
else {
failf(data, "Authentication cancelled");
result = CURLE_LOGIN_DENIED;
- }
+ }
break;
default:
break;
- }
-
- return result;
-}
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
-/* For APOP responses */
-static CURLcode pop3_state_apop_resp(struct connectdata *conn, int pop3code,
- pop3state instate)
-{
- CURLcode result = CURLE_OK;
+ }
+
+ return result;
+}
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+/* For APOP responses */
+static CURLcode pop3_state_apop_resp(struct connectdata *conn, int pop3code,
+ pop3state instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(pop3code != '+') {
- failf(data, "Authentication failed: %d", pop3code);
- result = CURLE_LOGIN_DENIED;
- }
- else
- /* End of connect phase */
- state(conn, POP3_STOP);
-
- return result;
-}
-#endif
-
-/* For USER responses */
-static CURLcode pop3_state_user_resp(struct connectdata *conn, int pop3code,
- pop3state instate)
-{
- CURLcode result = CURLE_OK;
+
+ (void)instate; /* no use for this yet */
+
+ if(pop3code != '+') {
+ failf(data, "Authentication failed: %d", pop3code);
+ result = CURLE_LOGIN_DENIED;
+ }
+ else
+ /* End of connect phase */
+ state(conn, POP3_STOP);
+
+ return result;
+}
+#endif
+
+/* For USER responses */
+static CURLcode pop3_state_user_resp(struct connectdata *conn, int pop3code,
+ pop3state instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(pop3code != '+') {
- failf(data, "Access denied. %c", pop3code);
- result = CURLE_LOGIN_DENIED;
- }
- else
- /* Send the PASS command */
- result = Curl_pp_sendf(&conn->proto.pop3c.pp, "PASS %s",
- conn->passwd ? conn->passwd : "");
- if(!result)
- state(conn, POP3_PASS);
-
- return result;
-}
-
-/* For PASS responses */
-static CURLcode pop3_state_pass_resp(struct connectdata *conn, int pop3code,
- pop3state instate)
-{
- CURLcode result = CURLE_OK;
+
+ (void)instate; /* no use for this yet */
+
+ if(pop3code != '+') {
+ failf(data, "Access denied. %c", pop3code);
+ result = CURLE_LOGIN_DENIED;
+ }
+ else
+ /* Send the PASS command */
+ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "PASS %s",
+ conn->passwd ? conn->passwd : "");
+ if(!result)
+ state(conn, POP3_PASS);
+
+ return result;
+}
+
+/* For PASS responses */
+static CURLcode pop3_state_pass_resp(struct connectdata *conn, int pop3code,
+ pop3state instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(pop3code != '+') {
- failf(data, "Access denied. %c", pop3code);
- result = CURLE_LOGIN_DENIED;
- }
- else
- /* End of connect phase */
- state(conn, POP3_STOP);
-
- return result;
-}
-
-/* For command responses */
-static CURLcode pop3_state_command_resp(struct connectdata *conn,
- int pop3code,
- pop3state instate)
-{
- CURLcode result = CURLE_OK;
+
+ (void)instate; /* no use for this yet */
+
+ if(pop3code != '+') {
+ failf(data, "Access denied. %c", pop3code);
+ result = CURLE_LOGIN_DENIED;
+ }
+ else
+ /* End of connect phase */
+ state(conn, POP3_STOP);
+
+ return result;
+}
+
+/* For command responses */
+static CURLcode pop3_state_command_resp(struct connectdata *conn,
+ int pop3code,
+ pop3state instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct POP3 *pop3 = data->req.p.pop3;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
- struct pingpong *pp = &pop3c->pp;
-
- (void)instate; /* no use for this yet */
-
- if(pop3code != '+') {
- state(conn, POP3_STOP);
- return CURLE_RECV_ERROR;
- }
-
- /* This 'OK' line ends with a CR LF pair which is the two first bytes of the
- EOB string so count this is two matching bytes. This is necessary to make
- the code detect the EOB if the only data than comes now is %2e CR LF like
- when there is no body to return. */
- pop3c->eob = 2;
-
- /* But since this initial CR LF pair is not part of the actual body, we set
- the strip counter here so that these bytes won't be delivered. */
- pop3c->strip = 2;
-
- if(pop3->transfer == FTPTRANSFER_BODY) {
- /* POP3 download */
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+ struct pingpong *pp = &pop3c->pp;
+
+ (void)instate; /* no use for this yet */
+
+ if(pop3code != '+') {
+ state(conn, POP3_STOP);
+ return CURLE_RECV_ERROR;
+ }
+
+ /* This 'OK' line ends with a CR LF pair which is the two first bytes of the
+ EOB string so count this is two matching bytes. This is necessary to make
+ the code detect the EOB if the only data than comes now is %2e CR LF like
+ when there is no body to return. */
+ pop3c->eob = 2;
+
+ /* But since this initial CR LF pair is not part of the actual body, we set
+ the strip counter here so that these bytes won't be delivered. */
+ pop3c->strip = 2;
+
+ if(pop3->transfer == FTPTRANSFER_BODY) {
+ /* POP3 download */
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
-
- if(pp->cache) {
- /* The header "cache" contains a bunch of data that is actually body
- content so send it as such. Note that there may even be additional
- "headers" after the body */
-
- if(!data->set.opt_no_body) {
- result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
- if(result)
- return result;
- }
-
- /* Free the cache */
- Curl_safefree(pp->cache);
-
- /* Reset the cache size */
- pp->cache_size = 0;
- }
- }
-
- /* End of DO phase */
- state(conn, POP3_STOP);
-
- return result;
-}
-
-static CURLcode pop3_statemach_act(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- curl_socket_t sock = conn->sock[FIRSTSOCKET];
- int pop3code;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
- struct pingpong *pp = &pop3c->pp;
- size_t nread = 0;
-
- /* Busy upgrading the connection; right now all I/O is SSL/TLS, not POP3 */
- if(pop3c->state == POP3_UPGRADETLS)
- return pop3_perform_upgrade_tls(conn);
-
- /* Flush any data that needs to be sent */
- if(pp->sendleft)
- return Curl_pp_flushsend(pp);
-
+
+ if(pp->cache) {
+ /* The header "cache" contains a bunch of data that is actually body
+ content so send it as such. Note that there may even be additional
+ "headers" after the body */
+
+ if(!data->set.opt_no_body) {
+ result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
+ if(result)
+ return result;
+ }
+
+ /* Free the cache */
+ Curl_safefree(pp->cache);
+
+ /* Reset the cache size */
+ pp->cache_size = 0;
+ }
+ }
+
+ /* End of DO phase */
+ state(conn, POP3_STOP);
+
+ return result;
+}
+
+static CURLcode pop3_statemach_act(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
+ int pop3code;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+ struct pingpong *pp = &pop3c->pp;
+ size_t nread = 0;
+
+ /* Busy upgrading the connection; right now all I/O is SSL/TLS, not POP3 */
+ if(pop3c->state == POP3_UPGRADETLS)
+ return pop3_perform_upgrade_tls(conn);
+
+ /* Flush any data that needs to be sent */
+ if(pp->sendleft)
+ return Curl_pp_flushsend(pp);
+
do {
/* Read the response from the server */
result = Curl_pp_readresp(sock, pp, &pop3code, &nread);
if(result)
return result;
-
+
if(!pop3code)
break;
- /* We have now received a full POP3 server response */
- switch(pop3c->state) {
- case POP3_SERVERGREET:
- result = pop3_state_servergreet_resp(conn, pop3code, pop3c->state);
- break;
-
- case POP3_CAPA:
- result = pop3_state_capa_resp(conn, pop3code, pop3c->state);
- break;
-
- case POP3_STARTTLS:
- result = pop3_state_starttls_resp(conn, pop3code, pop3c->state);
- break;
-
+ /* We have now received a full POP3 server response */
+ switch(pop3c->state) {
+ case POP3_SERVERGREET:
+ result = pop3_state_servergreet_resp(conn, pop3code, pop3c->state);
+ break;
+
+ case POP3_CAPA:
+ result = pop3_state_capa_resp(conn, pop3code, pop3c->state);
+ break;
+
+ case POP3_STARTTLS:
+ result = pop3_state_starttls_resp(conn, pop3code, pop3c->state);
+ break;
+
case POP3_AUTH:
result = pop3_state_auth_resp(conn, pop3code, pop3c->state);
- break;
-
-#ifndef CURL_DISABLE_CRYPTO_AUTH
- case POP3_APOP:
- result = pop3_state_apop_resp(conn, pop3code, pop3c->state);
- break;
-#endif
-
- case POP3_USER:
- result = pop3_state_user_resp(conn, pop3code, pop3c->state);
- break;
-
- case POP3_PASS:
- result = pop3_state_pass_resp(conn, pop3code, pop3c->state);
- break;
-
- case POP3_COMMAND:
- result = pop3_state_command_resp(conn, pop3code, pop3c->state);
- break;
-
- case POP3_QUIT:
- /* fallthrough, just stop! */
- default:
- /* internal error */
- state(conn, POP3_STOP);
- break;
- }
+ break;
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+ case POP3_APOP:
+ result = pop3_state_apop_resp(conn, pop3code, pop3c->state);
+ break;
+#endif
+
+ case POP3_USER:
+ result = pop3_state_user_resp(conn, pop3code, pop3c->state);
+ break;
+
+ case POP3_PASS:
+ result = pop3_state_pass_resp(conn, pop3code, pop3c->state);
+ break;
+
+ case POP3_COMMAND:
+ result = pop3_state_command_resp(conn, pop3code, pop3c->state);
+ break;
+
+ case POP3_QUIT:
+ /* fallthrough, just stop! */
+ default:
+ /* internal error */
+ state(conn, POP3_STOP);
+ break;
+ }
} while(!result && pop3c->state != POP3_STOP && Curl_pp_moredata(pp));
-
- return result;
-}
-
-/* Called repeatedly until done from multi.c */
-static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-
- if((conn->handler->flags & PROTOPT_SSL) && !pop3c->ssldone) {
- result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &pop3c->ssldone);
- if(result || !pop3c->ssldone)
- return result;
- }
-
+
+ return result;
+}
+
+/* Called repeatedly until done from multi.c */
+static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+
+ if((conn->handler->flags & PROTOPT_SSL) && !pop3c->ssldone) {
+ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &pop3c->ssldone);
+ if(result || !pop3c->ssldone)
+ return result;
+ }
+
result = Curl_pp_statemach(&pop3c->pp, FALSE, FALSE);
- *done = (pop3c->state == POP3_STOP) ? TRUE : FALSE;
-
- return result;
-}
-
+ *done = (pop3c->state == POP3_STOP) ? TRUE : FALSE;
+
+ return result;
+}
+
static CURLcode pop3_block_statemach(struct connectdata *conn,
bool disconnecting)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-
- while(pop3c->state != POP3_STOP && !result)
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+
+ while(pop3c->state != POP3_STOP && !result)
result = Curl_pp_statemach(&pop3c->pp, TRUE, disconnecting);
-
- return result;
-}
-
+
+ return result;
+}
+
/* Allocate and initialize the POP3 struct for the current Curl_easy if
- required */
-static CURLcode pop3_init(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ required */
+static CURLcode pop3_init(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct POP3 *pop3;
-
+ struct POP3 *pop3;
+
pop3 = data->req.p.pop3 = calloc(sizeof(struct POP3), 1);
- if(!pop3)
- result = CURLE_OUT_OF_MEMORY;
-
- return result;
-}
-
-/* For the POP3 "protocol connect" and "doing" phases only */
+ if(!pop3)
+ result = CURLE_OUT_OF_MEMORY;
+
+ return result;
+}
+
+/* For the POP3 "protocol connect" and "doing" phases only */
static int pop3_getsock(struct connectdata *conn, curl_socket_t *socks)
-{
+{
return Curl_pp_getsock(&conn->proto.pop3c.pp, socks);
-}
-
-/***********************************************************************
- *
- * pop3_connect()
- *
- * This function should do everything that is to be considered a part of the
- * connection phase.
- *
- * The variable 'done' points to will be TRUE if the protocol-layer connect
- * phase is done when this function returns, or FALSE if not.
- */
-static CURLcode pop3_connect(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
- struct pingpong *pp = &pop3c->pp;
-
- *done = FALSE; /* default to not done yet */
-
- /* We always support persistent connections in POP3 */
+}
+
+/***********************************************************************
+ *
+ * pop3_connect()
+ *
+ * This function should do everything that is to be considered a part of the
+ * connection phase.
+ *
+ * The variable 'done' points to will be TRUE if the protocol-layer connect
+ * phase is done when this function returns, or FALSE if not.
+ */
+static CURLcode pop3_connect(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+ struct pingpong *pp = &pop3c->pp;
+
+ *done = FALSE; /* default to not done yet */
+
+ /* We always support persistent connections in POP3 */
connkeep(conn, "POP3 default");
-
- /* Set the default response time-out */
- pp->response_time = RESP_TIMEOUT;
- pp->statemach_act = pop3_statemach_act;
- pp->endofresp = pop3_endofresp;
- pp->conn = conn;
-
- /* Set the default preferred authentication type and mechanism */
- pop3c->preftype = POP3_TYPE_ANY;
+
+ /* Set the default response time-out */
+ pp->response_time = RESP_TIMEOUT;
+ pp->statemach_act = pop3_statemach_act;
+ pp->endofresp = pop3_endofresp;
+ pp->conn = conn;
+
+ /* Set the default preferred authentication type and mechanism */
+ pop3c->preftype = POP3_TYPE_ANY;
Curl_sasl_init(&pop3c->sasl, &saslpop3);
-
- /* Initialise the pingpong layer */
+
+ /* Initialise the pingpong layer */
Curl_pp_setup(pp);
- Curl_pp_init(pp);
-
- /* Parse the URL options */
- result = pop3_parse_url_options(conn);
- if(result)
- return result;
-
- /* Start off waiting for the server greeting response */
- state(conn, POP3_SERVERGREET);
-
- result = pop3_multi_statemach(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_done()
- *
- * The DONE function. This does what needs to be done after a single DO has
- * performed.
- *
- * Input argument is already checked for validity.
- */
-static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
- bool premature)
-{
- CURLcode result = CURLE_OK;
+ Curl_pp_init(pp);
+
+ /* Parse the URL options */
+ result = pop3_parse_url_options(conn);
+ if(result)
+ return result;
+
+ /* Start off waiting for the server greeting response */
+ state(conn, POP3_SERVERGREET);
+
+ result = pop3_multi_statemach(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_done()
+ *
+ * The DONE function. This does what needs to be done after a single DO has
+ * performed.
+ *
+ * Input argument is already checked for validity.
+ */
+static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct POP3 *pop3 = data->req.p.pop3;
-
- (void)premature;
-
- if(!pop3)
- return CURLE_OK;
-
- if(status) {
+
+ (void)premature;
+
+ if(!pop3)
+ return CURLE_OK;
+
+ if(status) {
connclose(conn, "POP3 done with bad status");
- result = status; /* use the already set error code */
- }
-
- /* Cleanup our per-request based variables */
- Curl_safefree(pop3->id);
- Curl_safefree(pop3->custom);
-
- /* Clear the transfer mode for the next request */
- pop3->transfer = FTPTRANSFER_BODY;
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_perform()
- *
- * This is the actual DO function for POP3. Get a message/listing according to
- * the options previously setup.
- */
-static CURLcode pop3_perform(struct connectdata *conn, bool *connected,
- bool *dophase_done)
-{
- /* This is POP3 and no proxy */
- CURLcode result = CURLE_OK;
+ result = status; /* use the already set error code */
+ }
+
+ /* Cleanup our per-request based variables */
+ Curl_safefree(pop3->id);
+ Curl_safefree(pop3->custom);
+
+ /* Clear the transfer mode for the next request */
+ pop3->transfer = FTPTRANSFER_BODY;
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_perform()
+ *
+ * This is the actual DO function for POP3. Get a message/listing according to
+ * the options previously setup.
+ */
+static CURLcode pop3_perform(struct connectdata *conn, bool *connected,
+ bool *dophase_done)
+{
+ /* This is POP3 and no proxy */
+ CURLcode result = CURLE_OK;
struct POP3 *pop3 = conn->data->req.p.pop3;
-
- DEBUGF(infof(conn->data, "DO phase starts\n"));
-
- if(conn->data->set.opt_no_body) {
- /* Requested no body means no transfer */
- pop3->transfer = FTPTRANSFER_INFO;
- }
-
- *dophase_done = FALSE; /* not done yet */
-
- /* Start the first command in the DO phase */
- result = pop3_perform_command(conn);
- if(result)
- return result;
-
- /* Run the state-machine */
- result = pop3_multi_statemach(conn, dophase_done);
-
- *connected = conn->bits.tcpconnect[FIRSTSOCKET];
-
- if(*dophase_done)
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_do()
- *
- * This function is registered as 'curl_do' function. It decodes the path
- * parts etc as a wrapper to the actual DO function (pop3_perform).
- *
- * The input argument is already checked for validity.
- */
-static CURLcode pop3_do(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
-
- *done = FALSE; /* default to false */
-
- /* Parse the URL path */
- result = pop3_parse_url_path(conn);
- if(result)
- return result;
-
- /* Parse the custom request */
- result = pop3_parse_custom_request(conn);
- if(result)
- return result;
-
- result = pop3_regular_transfer(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_disconnect()
- *
- * Disconnect from an POP3 server. Cleanup protocol-specific per-connection
- * resources. BLOCKING.
- */
+
+ DEBUGF(infof(conn->data, "DO phase starts\n"));
+
+ if(conn->data->set.opt_no_body) {
+ /* Requested no body means no transfer */
+ pop3->transfer = FTPTRANSFER_INFO;
+ }
+
+ *dophase_done = FALSE; /* not done yet */
+
+ /* Start the first command in the DO phase */
+ result = pop3_perform_command(conn);
+ if(result)
+ return result;
+
+ /* Run the state-machine */
+ result = pop3_multi_statemach(conn, dophase_done);
+
+ *connected = conn->bits.tcpconnect[FIRSTSOCKET];
+
+ if(*dophase_done)
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_do()
+ *
+ * This function is registered as 'curl_do' function. It decodes the path
+ * parts etc as a wrapper to the actual DO function (pop3_perform).
+ *
+ * The input argument is already checked for validity.
+ */
+static CURLcode pop3_do(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+
+ *done = FALSE; /* default to false */
+
+ /* Parse the URL path */
+ result = pop3_parse_url_path(conn);
+ if(result)
+ return result;
+
+ /* Parse the custom request */
+ result = pop3_parse_custom_request(conn);
+ if(result)
+ return result;
+
+ result = pop3_regular_transfer(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_disconnect()
+ *
+ * Disconnect from an POP3 server. Cleanup protocol-specific per-connection
+ * resources. BLOCKING.
+ */
static CURLcode pop3_disconnect(struct connectdata *conn, bool dead_connection)
-{
- struct pop3_conn *pop3c = &conn->proto.pop3c;
-
- /* We cannot send quit unconditionally. If this connection is stale or
- bad in any way, sending quit and waiting around here will make the
- disconnect wait in vain and cause more problems than we need to. */
-
- /* The POP3 session may or may not have been allocated/setup at this
- point! */
+{
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+
+ /* We cannot send quit unconditionally. If this connection is stale or
+ bad in any way, sending quit and waiting around here will make the
+ disconnect wait in vain and cause more problems than we need to. */
+
+ /* The POP3 session may or may not have been allocated/setup at this
+ point! */
if(!dead_connection && pop3c->pp.conn && pop3c->pp.conn->bits.protoconnstart)
- if(!pop3_perform_quit(conn))
+ if(!pop3_perform_quit(conn))
(void)pop3_block_statemach(conn, TRUE); /* ignore errors on QUIT */
-
- /* Disconnect from the server */
- Curl_pp_disconnect(&pop3c->pp);
-
- /* Cleanup the SASL module */
+
+ /* Disconnect from the server */
+ Curl_pp_disconnect(&pop3c->pp);
+
+ /* Cleanup the SASL module */
Curl_sasl_cleanup(conn, pop3c->sasl.authused);
-
- /* Cleanup our connection based variables */
- Curl_safefree(pop3c->apoptimestamp);
-
- return CURLE_OK;
-}
-
-/* Call this when the DO phase has completed */
-static CURLcode pop3_dophase_done(struct connectdata *conn, bool connected)
-{
- (void)conn;
- (void)connected;
-
- return CURLE_OK;
-}
-
-/* Called from multi.c while DOing */
-static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done)
-{
- CURLcode result = pop3_multi_statemach(conn, dophase_done);
-
- if(result)
- DEBUGF(infof(conn->data, "DO phase failed\n"));
- else if(*dophase_done) {
- result = pop3_dophase_done(conn, FALSE /* not connected */);
-
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_regular_transfer()
- *
- * The input argument is already checked for validity.
- *
- * Performs all commands done before a regular transfer between a local and a
- * remote host.
- */
-static CURLcode pop3_regular_transfer(struct connectdata *conn,
- bool *dophase_done)
-{
- CURLcode result = CURLE_OK;
- bool connected = FALSE;
+
+ /* Cleanup our connection based variables */
+ Curl_safefree(pop3c->apoptimestamp);
+
+ return CURLE_OK;
+}
+
+/* Call this when the DO phase has completed */
+static CURLcode pop3_dophase_done(struct connectdata *conn, bool connected)
+{
+ (void)conn;
+ (void)connected;
+
+ return CURLE_OK;
+}
+
+/* Called from multi.c while DOing */
+static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done)
+{
+ CURLcode result = pop3_multi_statemach(conn, dophase_done);
+
+ if(result)
+ DEBUGF(infof(conn->data, "DO phase failed\n"));
+ else if(*dophase_done) {
+ result = pop3_dophase_done(conn, FALSE /* not connected */);
+
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_regular_transfer()
+ *
+ * The input argument is already checked for validity.
+ *
+ * Performs all commands done before a regular transfer between a local and a
+ * remote host.
+ */
+static CURLcode pop3_regular_transfer(struct connectdata *conn,
+ bool *dophase_done)
+{
+ CURLcode result = CURLE_OK;
+ bool connected = FALSE;
struct Curl_easy *data = conn->data;
-
- /* Make sure size is unknown at this point */
- data->req.size = -1;
-
- /* Set the progress data */
- Curl_pgrsSetUploadCounter(data, 0);
- Curl_pgrsSetDownloadCounter(data, 0);
+
+ /* Make sure size is unknown at this point */
+ data->req.size = -1;
+
+ /* Set the progress data */
+ Curl_pgrsSetUploadCounter(data, 0);
+ Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, -1);
Curl_pgrsSetDownloadSize(data, -1);
-
- /* Carry out the perform */
- result = pop3_perform(conn, &connected, dophase_done);
-
- /* Perform post DO phase operations if necessary */
- if(!result && *dophase_done)
- result = pop3_dophase_done(conn, connected);
-
- return result;
-}
-
-static CURLcode pop3_setup_connection(struct connectdata *conn)
-{
- /* Initialise the POP3 layer */
- CURLcode result = pop3_init(conn);
- if(result)
- return result;
-
+
+ /* Carry out the perform */
+ result = pop3_perform(conn, &connected, dophase_done);
+
+ /* Perform post DO phase operations if necessary */
+ if(!result && *dophase_done)
+ result = pop3_dophase_done(conn, connected);
+
+ return result;
+}
+
+static CURLcode pop3_setup_connection(struct connectdata *conn)
+{
+ /* Initialise the POP3 layer */
+ CURLcode result = pop3_init(conn);
+ if(result)
+ return result;
+
/* Clear the TLS upgraded flag */
conn->bits.tls_upgraded = FALSE;
-
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * pop3_parse_url_options()
- *
- * Parse the URL login options.
- */
-static CURLcode pop3_parse_url_options(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct pop3_conn *pop3c = &conn->proto.pop3c;
+
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * pop3_parse_url_options()
+ *
+ * Parse the URL login options.
+ */
+static CURLcode pop3_parse_url_options(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
const char *ptr = conn->options;
-
+
pop3c->sasl.resetprefs = TRUE;
while(!result && ptr && *ptr) {
- const char *key = ptr;
+ const char *key = ptr;
const char *value;
-
- while(*ptr && *ptr != '=')
- ptr++;
-
+
+ while(*ptr && *ptr != '=')
+ ptr++;
+
value = ptr + 1;
-
+
while(*ptr && *ptr != ';')
ptr++;
@@ -1351,18 +1351,18 @@ static CURLcode pop3_parse_url_options(struct connectdata *conn)
value, ptr - value);
if(result && strncasecompare(value, "+APOP", ptr - value)) {
- pop3c->preftype = POP3_TYPE_APOP;
+ pop3c->preftype = POP3_TYPE_APOP;
pop3c->sasl.prefmech = SASL_AUTH_NONE;
result = CURLE_OK;
- }
- }
- else
- result = CURLE_URL_MALFORMAT;
+ }
+ }
+ else
+ result = CURLE_URL_MALFORMAT;
if(*ptr == ';')
ptr++;
- }
-
+ }
+
if(pop3c->preftype != POP3_TYPE_APOP)
switch(pop3c->sasl.prefmech) {
case SASL_AUTH_NONE:
@@ -1376,172 +1376,172 @@ static CURLcode pop3_parse_url_options(struct connectdata *conn)
break;
}
- return result;
-}
-
-/***********************************************************************
- *
- * pop3_parse_url_path()
- *
- * Parse the URL path into separate path components.
- */
-static CURLcode pop3_parse_url_path(struct connectdata *conn)
-{
- /* The POP3 struct is already initialised in pop3_connect() */
+ return result;
+}
+
+/***********************************************************************
+ *
+ * pop3_parse_url_path()
+ *
+ * Parse the URL path into separate path components.
+ */
+static CURLcode pop3_parse_url_path(struct connectdata *conn)
+{
+ /* The POP3 struct is already initialised in pop3_connect() */
struct Curl_easy *data = conn->data;
struct POP3 *pop3 = data->req.p.pop3;
const char *path = &data->state.up.path[1]; /* skip leading path */
-
- /* URL decode the path for the message ID */
+
+ /* URL decode the path for the message ID */
return Curl_urldecode(data, path, 0, &pop3->id, NULL, REJECT_CTRL);
-}
-
-/***********************************************************************
- *
- * pop3_parse_custom_request()
- *
- * Parse the custom request.
- */
-static CURLcode pop3_parse_custom_request(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * pop3_parse_custom_request()
+ *
+ * Parse the custom request.
+ */
+static CURLcode pop3_parse_custom_request(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct POP3 *pop3 = data->req.p.pop3;
- const char *custom = data->set.str[STRING_CUSTOMREQUEST];
-
- /* URL decode the custom request */
- if(custom)
+ const char *custom = data->set.str[STRING_CUSTOMREQUEST];
+
+ /* URL decode the custom request */
+ if(custom)
result = Curl_urldecode(data, custom, 0, &pop3->custom, NULL, REJECT_CTRL);
-
- return result;
-}
-
-/***********************************************************************
- *
- * Curl_pop3_write()
- *
- * This function scans the body after the end-of-body and writes everything
- * until the end is found.
- */
-CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread)
-{
- /* This code could be made into a special function in the handler struct */
- CURLcode result = CURLE_OK;
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * Curl_pop3_write()
+ *
+ * This function scans the body after the end-of-body and writes everything
+ * until the end is found.
+ */
+CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread)
+{
+ /* This code could be made into a special function in the handler struct */
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct SingleRequest *k = &data->req;
-
- struct pop3_conn *pop3c = &conn->proto.pop3c;
- bool strip_dot = FALSE;
- size_t last = 0;
- size_t i;
-
- /* Search through the buffer looking for the end-of-body marker which is
- 5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches
- the eob so the server will have prefixed it with an extra dot which we
- need to strip out. Additionally the marker could of course be spread out
- over 5 different data chunks. */
- for(i = 0; i < nread; i++) {
- size_t prev = pop3c->eob;
-
- switch(str[i]) {
- case 0x0d:
- if(pop3c->eob == 0) {
- pop3c->eob++;
-
- if(i) {
- /* Write out the body part that didn't match */
- result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
- i - last);
-
- if(result)
- return result;
-
- last = i;
- }
- }
- else if(pop3c->eob == 3)
- pop3c->eob++;
- else
- /* If the character match wasn't at position 0 or 3 then restart the
- pattern matching */
- pop3c->eob = 1;
- break;
-
- case 0x0a:
- if(pop3c->eob == 1 || pop3c->eob == 4)
- pop3c->eob++;
- else
- /* If the character match wasn't at position 1 or 4 then start the
- search again */
- pop3c->eob = 0;
- break;
-
- case 0x2e:
- if(pop3c->eob == 2)
- pop3c->eob++;
- else if(pop3c->eob == 3) {
- /* We have an extra dot after the CRLF which we need to strip off */
- strip_dot = TRUE;
- pop3c->eob = 0;
- }
- else
- /* If the character match wasn't at position 2 then start the search
- again */
- pop3c->eob = 0;
- break;
-
- default:
- pop3c->eob = 0;
- break;
- }
-
- /* Did we have a partial match which has subsequently failed? */
- if(prev && prev >= pop3c->eob) {
- /* Strip can only be non-zero for the very first mismatch after CRLF
- and then both prev and strip are equal and nothing will be output
- below */
- while(prev && pop3c->strip) {
- prev--;
- pop3c->strip--;
- }
-
- if(prev) {
- /* If the partial match was the CRLF and dot then only write the CRLF
- as the server would have inserted the dot */
+ struct SingleRequest *k = &data->req;
+
+ struct pop3_conn *pop3c = &conn->proto.pop3c;
+ bool strip_dot = FALSE;
+ size_t last = 0;
+ size_t i;
+
+ /* Search through the buffer looking for the end-of-body marker which is
+ 5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches
+ the eob so the server will have prefixed it with an extra dot which we
+ need to strip out. Additionally the marker could of course be spread out
+ over 5 different data chunks. */
+ for(i = 0; i < nread; i++) {
+ size_t prev = pop3c->eob;
+
+ switch(str[i]) {
+ case 0x0d:
+ if(pop3c->eob == 0) {
+ pop3c->eob++;
+
+ if(i) {
+ /* Write out the body part that didn't match */
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
+ i - last);
+
+ if(result)
+ return result;
+
+ last = i;
+ }
+ }
+ else if(pop3c->eob == 3)
+ pop3c->eob++;
+ else
+ /* If the character match wasn't at position 0 or 3 then restart the
+ pattern matching */
+ pop3c->eob = 1;
+ break;
+
+ case 0x0a:
+ if(pop3c->eob == 1 || pop3c->eob == 4)
+ pop3c->eob++;
+ else
+ /* If the character match wasn't at position 1 or 4 then start the
+ search again */
+ pop3c->eob = 0;
+ break;
+
+ case 0x2e:
+ if(pop3c->eob == 2)
+ pop3c->eob++;
+ else if(pop3c->eob == 3) {
+ /* We have an extra dot after the CRLF which we need to strip off */
+ strip_dot = TRUE;
+ pop3c->eob = 0;
+ }
+ else
+ /* If the character match wasn't at position 2 then start the search
+ again */
+ pop3c->eob = 0;
+ break;
+
+ default:
+ pop3c->eob = 0;
+ break;
+ }
+
+ /* Did we have a partial match which has subsequently failed? */
+ if(prev && prev >= pop3c->eob) {
+ /* Strip can only be non-zero for the very first mismatch after CRLF
+ and then both prev and strip are equal and nothing will be output
+ below */
+ while(prev && pop3c->strip) {
+ prev--;
+ pop3c->strip--;
+ }
+
+ if(prev) {
+ /* If the partial match was the CRLF and dot then only write the CRLF
+ as the server would have inserted the dot */
result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)POP3_EOB,
- strip_dot ? prev - 1 : prev);
-
- if(result)
- return result;
-
- last = i;
- strip_dot = FALSE;
- }
- }
- }
-
- if(pop3c->eob == POP3_EOB_LEN) {
- /* We have a full match so the transfer is done, however we must transfer
- the CRLF at the start of the EOB as this is considered to be part of the
- message as per RFC-1939, sect. 3 */
- result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)POP3_EOB, 2);
-
- k->keepon &= ~KEEP_RECV;
- pop3c->eob = 0;
-
- return result;
- }
-
- if(pop3c->eob)
- /* While EOB is matching nothing should be output */
- return CURLE_OK;
-
- if(nread - last) {
- result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
- nread - last);
- }
-
- return result;
-}
-
-#endif /* CURL_DISABLE_POP3 */
+ strip_dot ? prev - 1 : prev);
+
+ if(result)
+ return result;
+
+ last = i;
+ strip_dot = FALSE;
+ }
+ }
+ }
+
+ if(pop3c->eob == POP3_EOB_LEN) {
+ /* We have a full match so the transfer is done, however we must transfer
+ the CRLF at the start of the EOB as this is considered to be part of the
+ message as per RFC-1939, sect. 3 */
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)POP3_EOB, 2);
+
+ k->keepon &= ~KEEP_RECV;
+ pop3c->eob = 0;
+
+ return result;
+ }
+
+ if(pop3c->eob)
+ /* While EOB is matching nothing should be output */
+ return CURLE_OK;
+
+ if(nread - last) {
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
+ nread - last);
+ }
+
+ return result;
+}
+
+#endif /* CURL_DISABLE_POP3 */
diff --git a/contrib/libs/curl/lib/pop3.h b/contrib/libs/curl/lib/pop3.h
index 6c7ae46788..6ca3fd511f 100644
--- a/contrib/libs/curl/lib/pop3.h
+++ b/contrib/libs/curl/lib/pop3.h
@@ -1,95 +1,95 @@
-#ifndef HEADER_CURL_POP3_H
-#define HEADER_CURL_POP3_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_POP3_H
+#define HEADER_CURL_POP3_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2009 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "pingpong.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "pingpong.h"
#include "curl_sasl.h"
-
-/****************************************************************************
- * POP3 unique setup
- ***************************************************************************/
-typedef enum {
- POP3_STOP, /* do nothing state, stops the state machine */
- POP3_SERVERGREET, /* waiting for the initial greeting immediately after
- a connect */
- POP3_CAPA,
- POP3_STARTTLS,
- POP3_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
- (multi mode only) */
+
+/****************************************************************************
+ * POP3 unique setup
+ ***************************************************************************/
+typedef enum {
+ POP3_STOP, /* do nothing state, stops the state machine */
+ POP3_SERVERGREET, /* waiting for the initial greeting immediately after
+ a connect */
+ POP3_CAPA,
+ POP3_STARTTLS,
+ POP3_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
+ (multi mode only) */
POP3_AUTH,
- POP3_APOP,
- POP3_USER,
- POP3_PASS,
- POP3_COMMAND,
- POP3_QUIT,
- POP3_LAST /* never used */
-} pop3state;
-
+ POP3_APOP,
+ POP3_USER,
+ POP3_PASS,
+ POP3_COMMAND,
+ POP3_QUIT,
+ POP3_LAST /* never used */
+} pop3state;
+
/* This POP3 struct is used in the Curl_easy. All POP3 data that is
- connection-oriented must be in pop3_conn to properly deal with the fact that
+ connection-oriented must be in pop3_conn to properly deal with the fact that
perhaps the Curl_easy is changed between the times the connection is
- used. */
-struct POP3 {
- curl_pp_transfer transfer;
- char *id; /* Message ID */
- char *custom; /* Custom Request */
-};
-
-/* pop3_conn is used for struct connection-oriented data in the connectdata
- struct */
-struct pop3_conn {
- struct pingpong pp;
- pop3state state; /* Always use pop3.c:state() to change state! */
- bool ssldone; /* Is connect() over SSL done? */
- size_t eob; /* Number of bytes of the EOB (End Of Body) that
- have been received so far */
- size_t strip; /* Number of bytes from the start to ignore as
- non-body */
+ used. */
+struct POP3 {
+ curl_pp_transfer transfer;
+ char *id; /* Message ID */
+ char *custom; /* Custom Request */
+};
+
+/* pop3_conn is used for struct connection-oriented data in the connectdata
+ struct */
+struct pop3_conn {
+ struct pingpong pp;
+ pop3state state; /* Always use pop3.c:state() to change state! */
+ bool ssldone; /* Is connect() over SSL done? */
+ size_t eob; /* Number of bytes of the EOB (End Of Body) that
+ have been received so far */
+ size_t strip; /* Number of bytes from the start to ignore as
+ non-body */
struct SASL sasl; /* SASL-related storage */
- unsigned int authtypes; /* Accepted authentication types */
- unsigned int preftype; /* Preferred authentication type */
- char *apoptimestamp; /* APOP timestamp from the server greeting */
- bool tls_supported; /* StartTLS capability supported by server */
-};
-
-extern const struct Curl_handler Curl_handler_pop3;
-extern const struct Curl_handler Curl_handler_pop3s;
-
-/* Authentication type flags */
-#define POP3_TYPE_CLEARTEXT (1 << 0)
-#define POP3_TYPE_APOP (1 << 1)
-#define POP3_TYPE_SASL (1 << 2)
-
-/* Authentication type values */
-#define POP3_TYPE_NONE 0
+ unsigned int authtypes; /* Accepted authentication types */
+ unsigned int preftype; /* Preferred authentication type */
+ char *apoptimestamp; /* APOP timestamp from the server greeting */
+ bool tls_supported; /* StartTLS capability supported by server */
+};
+
+extern const struct Curl_handler Curl_handler_pop3;
+extern const struct Curl_handler Curl_handler_pop3s;
+
+/* Authentication type flags */
+#define POP3_TYPE_CLEARTEXT (1 << 0)
+#define POP3_TYPE_APOP (1 << 1)
+#define POP3_TYPE_SASL (1 << 2)
+
+/* Authentication type values */
+#define POP3_TYPE_NONE 0
#define POP3_TYPE_ANY ~0U
-
-/* This is the 5-bytes End-Of-Body marker for POP3 */
-#define POP3_EOB "\x0d\x0a\x2e\x0d\x0a"
-#define POP3_EOB_LEN 5
-
-/* This function scans the body after the end-of-body and writes everything
- * until the end is found */
-CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread);
-
-#endif /* HEADER_CURL_POP3_H */
+
+/* This is the 5-bytes End-Of-Body marker for POP3 */
+#define POP3_EOB "\x0d\x0a\x2e\x0d\x0a"
+#define POP3_EOB_LEN 5
+
+/* This function scans the body after the end-of-body and writes everything
+ * until the end is found */
+CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread);
+
+#endif /* HEADER_CURL_POP3_H */
diff --git a/contrib/libs/curl/lib/progress.c b/contrib/libs/curl/lib/progress.c
index 5c26b9762c..658d05ab8e 100644
--- a/contrib/libs/curl/lib/progress.c
+++ b/contrib/libs/curl/lib/progress.c
@@ -1,168 +1,168 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "urldata.h"
-#include "sendf.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include "urldata.h"
+#include "sendf.h"
#include "multiif.h"
-#include "progress.h"
+#include "progress.h"
#include "timeval.h"
#include "curl_printf.h"
-
+
/* check rate limits within this many recent milliseconds, at minimum. */
#define MIN_RATE_LIMIT_PERIOD 3000
-
+
#ifndef CURL_DISABLE_PROGRESS_METER
-/* Provide a string that is 2 + 1 + 2 + 1 + 2 = 8 letters long (plus the zero
- byte) */
-static void time2str(char *r, curl_off_t seconds)
-{
+/* Provide a string that is 2 + 1 + 2 + 1 + 2 = 8 letters long (plus the zero
+ byte) */
+static void time2str(char *r, curl_off_t seconds)
+{
curl_off_t h;
- if(seconds <= 0) {
- strcpy(r, "--:--:--");
- return;
- }
- h = seconds / CURL_OFF_T_C(3600);
- if(h <= CURL_OFF_T_C(99)) {
+ if(seconds <= 0) {
+ strcpy(r, "--:--:--");
+ return;
+ }
+ h = seconds / CURL_OFF_T_C(3600);
+ if(h <= CURL_OFF_T_C(99)) {
curl_off_t m = (seconds - (h*CURL_OFF_T_C(3600))) / CURL_OFF_T_C(60);
curl_off_t s = (seconds - (h*CURL_OFF_T_C(3600))) - (m*CURL_OFF_T_C(60));
msnprintf(r, 9, "%2" CURL_FORMAT_CURL_OFF_T ":%02" CURL_FORMAT_CURL_OFF_T
":%02" CURL_FORMAT_CURL_OFF_T, h, m, s);
- }
- else {
- /* this equals to more than 99 hours, switch to a more suitable output
- format to fit within the limits. */
+ }
+ else {
+ /* this equals to more than 99 hours, switch to a more suitable output
+ format to fit within the limits. */
curl_off_t d = seconds / CURL_OFF_T_C(86400);
- h = (seconds - (d*CURL_OFF_T_C(86400))) / CURL_OFF_T_C(3600);
- if(d <= CURL_OFF_T_C(999))
+ h = (seconds - (d*CURL_OFF_T_C(86400))) / CURL_OFF_T_C(3600);
+ if(d <= CURL_OFF_T_C(999))
msnprintf(r, 9, "%3" CURL_FORMAT_CURL_OFF_T
"d %02" CURL_FORMAT_CURL_OFF_T "h", d, h);
- else
+ else
msnprintf(r, 9, "%7" CURL_FORMAT_CURL_OFF_T "d", d);
- }
-}
-
-/* The point of this function would be to return a string of the input data,
- but never longer than 5 columns (+ one zero byte).
- Add suffix k, M, G when suitable... */
-static char *max5data(curl_off_t bytes, char *max5)
-{
-#define ONE_KILOBYTE CURL_OFF_T_C(1024)
-#define ONE_MEGABYTE (CURL_OFF_T_C(1024) * ONE_KILOBYTE)
-#define ONE_GIGABYTE (CURL_OFF_T_C(1024) * ONE_MEGABYTE)
-#define ONE_TERABYTE (CURL_OFF_T_C(1024) * ONE_GIGABYTE)
-#define ONE_PETABYTE (CURL_OFF_T_C(1024) * ONE_TERABYTE)
-
- if(bytes < CURL_OFF_T_C(100000))
+ }
+}
+
+/* The point of this function would be to return a string of the input data,
+ but never longer than 5 columns (+ one zero byte).
+ Add suffix k, M, G when suitable... */
+static char *max5data(curl_off_t bytes, char *max5)
+{
+#define ONE_KILOBYTE CURL_OFF_T_C(1024)
+#define ONE_MEGABYTE (CURL_OFF_T_C(1024) * ONE_KILOBYTE)
+#define ONE_GIGABYTE (CURL_OFF_T_C(1024) * ONE_MEGABYTE)
+#define ONE_TERABYTE (CURL_OFF_T_C(1024) * ONE_GIGABYTE)
+#define ONE_PETABYTE (CURL_OFF_T_C(1024) * ONE_TERABYTE)
+
+ if(bytes < CURL_OFF_T_C(100000))
msnprintf(max5, 6, "%5" CURL_FORMAT_CURL_OFF_T, bytes);
-
- else if(bytes < CURL_OFF_T_C(10000) * ONE_KILOBYTE)
+
+ else if(bytes < CURL_OFF_T_C(10000) * ONE_KILOBYTE)
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "k", bytes/ONE_KILOBYTE);
-
- else if(bytes < CURL_OFF_T_C(100) * ONE_MEGABYTE)
- /* 'XX.XM' is good as long as we're less than 100 megs */
+
+ else if(bytes < CURL_OFF_T_C(100) * ONE_MEGABYTE)
+ /* 'XX.XM' is good as long as we're less than 100 megs */
msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0"
CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE,
(bytes%ONE_MEGABYTE) / (ONE_MEGABYTE/CURL_OFF_T_C(10)) );
-
-#if (CURL_SIZEOF_CURL_OFF_T > 4)
-
- else if(bytes < CURL_OFF_T_C(10000) * ONE_MEGABYTE)
- /* 'XXXXM' is good until we're at 10000MB or above */
+
+#if (CURL_SIZEOF_CURL_OFF_T > 4)
+
+ else if(bytes < CURL_OFF_T_C(10000) * ONE_MEGABYTE)
+ /* 'XXXXM' is good until we're at 10000MB or above */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE);
-
- else if(bytes < CURL_OFF_T_C(100) * ONE_GIGABYTE)
- /* 10000 MB - 100 GB, we show it as XX.XG */
+
+ else if(bytes < CURL_OFF_T_C(100) * ONE_GIGABYTE)
+ /* 10000 MB - 100 GB, we show it as XX.XG */
msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0"
CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE,
(bytes%ONE_GIGABYTE) / (ONE_GIGABYTE/CURL_OFF_T_C(10)) );
-
- else if(bytes < CURL_OFF_T_C(10000) * ONE_GIGABYTE)
- /* up to 10000GB, display without decimal: XXXXG */
+
+ else if(bytes < CURL_OFF_T_C(10000) * ONE_GIGABYTE)
+ /* up to 10000GB, display without decimal: XXXXG */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE);
-
- else if(bytes < CURL_OFF_T_C(10000) * ONE_TERABYTE)
- /* up to 10000TB, display without decimal: XXXXT */
+
+ else if(bytes < CURL_OFF_T_C(10000) * ONE_TERABYTE)
+ /* up to 10000TB, display without decimal: XXXXT */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "T", bytes/ONE_TERABYTE);
-
- else
- /* up to 10000PB, display without decimal: XXXXP */
+
+ else
+ /* up to 10000PB, display without decimal: XXXXP */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "P", bytes/ONE_PETABYTE);
-
- /* 16384 petabytes (16 exabytes) is the maximum a 64 bit unsigned number
- can hold, but our data type is signed so 8192PB will be the maximum. */
-
-#else
-
- else
+
+ /* 16384 petabytes (16 exabytes) is the maximum a 64 bit unsigned number
+ can hold, but our data type is signed so 8192PB will be the maximum. */
+
+#else
+
+ else
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE);
-
-#endif
-
- return max5;
-}
+
#endif
-
-/*
-
- New proposed interface, 9th of February 2000:
-
- pgrsStartNow() - sets start time
- pgrsSetDownloadSize(x) - known expected download size
- pgrsSetUploadSize(x) - known expected upload size
- pgrsSetDownloadCounter() - amount of data currently downloaded
- pgrsSetUploadCounter() - amount of data currently uploaded
- pgrsUpdate() - show progress
- pgrsDone() - transfer complete
-
-*/
-
-int Curl_pgrsDone(struct connectdata *conn)
-{
- int rc;
+
+ return max5;
+}
+#endif
+
+/*
+
+ New proposed interface, 9th of February 2000:
+
+ pgrsStartNow() - sets start time
+ pgrsSetDownloadSize(x) - known expected download size
+ pgrsSetUploadSize(x) - known expected upload size
+ pgrsSetDownloadCounter() - amount of data currently downloaded
+ pgrsSetUploadCounter() - amount of data currently uploaded
+ pgrsUpdate() - show progress
+ pgrsDone() - transfer complete
+
+*/
+
+int Curl_pgrsDone(struct connectdata *conn)
+{
+ int rc;
struct Curl_easy *data = conn->data;
data->progress.lastshow = 0;
- rc = Curl_pgrsUpdate(conn); /* the final (forced) update */
- if(rc)
- return rc;
-
- if(!(data->progress.flags & PGRS_HIDE) &&
- !data->progress.callback)
- /* only output if we don't use a progress callback and we're not
- * hidden */
- fprintf(data->set.err, "\n");
-
- data->progress.speeder_c = 0; /* reset the progress meter display */
- return 0;
-}
-
+ rc = Curl_pgrsUpdate(conn); /* the final (forced) update */
+ if(rc)
+ return rc;
+
+ if(!(data->progress.flags & PGRS_HIDE) &&
+ !data->progress.callback)
+ /* only output if we don't use a progress callback and we're not
+ * hidden */
+ fprintf(data->set.err, "\n");
+
+ data->progress.speeder_c = 0; /* reset the progress meter display */
+ return 0;
+}
+
/* reset the known transfer sizes */
void Curl_pgrsResetTransferSizes(struct Curl_easy *data)
-{
+{
Curl_pgrsSetDownloadSize(data, -1);
Curl_pgrsSetUploadSize(data, -1);
-}
-
+}
+
/*
*
* Curl_pgrsTime(). Store the current time at the given label. This fetches a
@@ -171,40 +171,40 @@ void Curl_pgrsResetTransferSizes(struct Curl_easy *data)
* @unittest: 1399
*/
struct curltime Curl_pgrsTime(struct Curl_easy *data, timerid timer)
-{
+{
struct curltime now = Curl_now();
timediff_t *delta = NULL;
-
- switch(timer) {
- default:
- case TIMER_NONE:
- /* mistake filter */
- break;
+
+ switch(timer) {
+ default:
+ case TIMER_NONE:
+ /* mistake filter */
+ break;
case TIMER_STARTOP:
/* This is set at the start of a transfer */
data->progress.t_startop = now;
break;
- case TIMER_STARTSINGLE:
+ case TIMER_STARTSINGLE:
/* This is set at the start of each single fetch */
- data->progress.t_startsingle = now;
+ data->progress.t_startsingle = now;
data->progress.is_t_startransfer_set = false;
- break;
- case TIMER_STARTACCEPT:
+ break;
+ case TIMER_STARTACCEPT:
data->progress.t_acceptdata = now;
- break;
- case TIMER_NAMELOOKUP:
+ break;
+ case TIMER_NAMELOOKUP:
delta = &data->progress.t_nslookup;
- break;
- case TIMER_CONNECT:
+ break;
+ case TIMER_CONNECT:
delta = &data->progress.t_connect;
- break;
- case TIMER_APPCONNECT:
+ break;
+ case TIMER_APPCONNECT:
delta = &data->progress.t_appconnect;
- break;
- case TIMER_PRETRANSFER:
+ break;
+ case TIMER_PRETRANSFER:
delta = &data->progress.t_pretransfer;
- break;
- case TIMER_STARTTRANSFER:
+ break;
+ case TIMER_STARTTRANSFER:
delta = &data->progress.t_starttransfer;
/* prevent updating t_starttransfer unless:
* 1) this is the first time we're setting t_starttransfer
@@ -219,13 +219,13 @@ struct curltime Curl_pgrsTime(struct Curl_easy *data, timerid timer)
data->progress.is_t_startransfer_set = true;
break;
}
- case TIMER_POSTRANSFER:
- /* this is the normal end-of-transfer thing */
- break;
- case TIMER_REDIRECT:
+ case TIMER_POSTRANSFER:
+ /* this is the normal end-of-transfer thing */
+ break;
+ case TIMER_REDIRECT:
data->progress.t_redirect = Curl_timediff_us(now, data->progress.start);
- break;
- }
+ break;
+ }
if(delta) {
timediff_t us = Curl_timediff_us(now, data->progress.t_startsingle);
if(us < 1)
@@ -233,22 +233,22 @@ struct curltime Curl_pgrsTime(struct Curl_easy *data, timerid timer)
*delta += us;
}
return now;
-}
-
+}
+
void Curl_pgrsStartNow(struct Curl_easy *data)
-{
- data->progress.speeder_c = 0; /* reset the progress meter display */
+{
+ data->progress.speeder_c = 0; /* reset the progress meter display */
data->progress.start = Curl_now();
data->progress.is_t_startransfer_set = false;
data->progress.ul_limit_start = data->progress.start;
data->progress.dl_limit_start = data->progress.start;
data->progress.downloaded = 0;
data->progress.uploaded = 0;
- /* clear all bits except HIDE and HEADERS_OUT */
- data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT;
+ /* clear all bits except HIDE and HEADERS_OUT */
+ data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT;
Curl_ratelimit(data, data->progress.start);
-}
-
+}
+
/*
* This is used to handle speed limits, calculating how many milliseconds to
* wait until we're back under the speed limit, if needed.
@@ -272,7 +272,7 @@ timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize,
curl_off_t limit,
struct curltime start,
struct curltime now)
-{
+{
curl_off_t size = cursize - startsize;
timediff_t minimum;
timediff_t actual;
@@ -313,14 +313,14 @@ timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize,
*/
void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size)
{
- data->progress.downloaded = size;
-}
-
+ data->progress.downloaded = size;
+}
+
/*
* Update the timestamp and sizestamp to use for rate limit calculations.
*/
void Curl_ratelimit(struct Curl_easy *data, struct curltime now)
-{
+{
/* don't set a new stamp unless the time since last update is long enough */
if(data->set.max_recv_speed > 0) {
if(Curl_timediff(now, data->progress.dl_limit_start) >=
@@ -343,127 +343,127 @@ void Curl_ratelimit(struct Curl_easy *data, struct curltime now)
*/
void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size)
{
- data->progress.uploaded = size;
-}
-
+ data->progress.uploaded = size;
+}
+
void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size)
-{
+{
if(size >= 0) {
data->progress.size_dl = size;
- data->progress.flags |= PGRS_DL_SIZE_KNOWN;
+ data->progress.flags |= PGRS_DL_SIZE_KNOWN;
}
else {
data->progress.size_dl = 0;
- data->progress.flags &= ~PGRS_DL_SIZE_KNOWN;
+ data->progress.flags &= ~PGRS_DL_SIZE_KNOWN;
}
-}
-
+}
+
void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size)
-{
+{
if(size >= 0) {
data->progress.size_ul = size;
- data->progress.flags |= PGRS_UL_SIZE_KNOWN;
+ data->progress.flags |= PGRS_UL_SIZE_KNOWN;
}
else {
data->progress.size_ul = 0;
- data->progress.flags &= ~PGRS_UL_SIZE_KNOWN;
+ data->progress.flags &= ~PGRS_UL_SIZE_KNOWN;
}
-}
-
+}
+
/* returns TRUE if it's time to show the progress meter */
static bool progress_calc(struct connectdata *conn, struct curltime now)
-{
- curl_off_t timespent;
+{
+ curl_off_t timespent;
curl_off_t timespent_ms; /* milliseconds */
struct Curl_easy *data = conn->data;
curl_off_t dl = data->progress.downloaded;
curl_off_t ul = data->progress.uploaded;
bool timetoshow = FALSE;
-
- /* The time spent so far (from the start) */
+
+ /* The time spent so far (from the start) */
data->progress.timespent = Curl_timediff_us(now, data->progress.start);
timespent = (curl_off_t)data->progress.timespent/1000000; /* seconds */
timespent_ms = (curl_off_t)data->progress.timespent/1000; /* ms */
-
- /* The average download speed this far */
+
+ /* The average download speed this far */
if(dl < CURL_OFF_T_MAX/1000)
data->progress.dlspeed = (dl * 1000 / (timespent_ms>0?timespent_ms:1));
else
data->progress.dlspeed = (dl / (timespent>0?timespent:1));
-
- /* The average upload speed this far */
+
+ /* The average upload speed this far */
if(ul < CURL_OFF_T_MAX/1000)
data->progress.ulspeed = (ul * 1000 / (timespent_ms>0?timespent_ms:1));
else
data->progress.ulspeed = (ul / (timespent>0?timespent:1));
-
- /* Calculations done at most once a second, unless end is reached */
+
+ /* Calculations done at most once a second, unless end is reached */
if(data->progress.lastshow != now.tv_sec) {
int countindex; /* amount of seconds stored in the speeder array */
int nowindex = data->progress.speeder_c% CURR_TIME;
- data->progress.lastshow = now.tv_sec;
+ data->progress.lastshow = now.tv_sec;
timetoshow = TRUE;
-
+
/* Let's do the "current speed" thing, with the dl + ul speeds
combined. Store the speed at entry 'nowindex'. */
- data->progress.speeder[ nowindex ] =
+ data->progress.speeder[ nowindex ] =
data->progress.downloaded + data->progress.uploaded;
-
- /* remember the exact time for this moment */
- data->progress.speeder_time [ nowindex ] = now;
-
- /* advance our speeder_c counter, which is increased every time we get
- here and we expect it to never wrap as 2^32 is a lot of seconds! */
- data->progress.speeder_c++;
-
- /* figure out how many index entries of data we have stored in our speeder
- array. With N_ENTRIES filled in, we have about N_ENTRIES-1 seconds of
- transfer. Imagine, after one second we have filled in two entries,
- after two seconds we've filled in three entries etc. */
+
+ /* remember the exact time for this moment */
+ data->progress.speeder_time [ nowindex ] = now;
+
+ /* advance our speeder_c counter, which is increased every time we get
+ here and we expect it to never wrap as 2^32 is a lot of seconds! */
+ data->progress.speeder_c++;
+
+ /* figure out how many index entries of data we have stored in our speeder
+ array. With N_ENTRIES filled in, we have about N_ENTRIES-1 seconds of
+ transfer. Imagine, after one second we have filled in two entries,
+ after two seconds we've filled in three entries etc. */
countindex = ((data->progress.speeder_c >= CURR_TIME)?
- CURR_TIME:data->progress.speeder_c) - 1;
-
- /* first of all, we don't do this if there's no counted seconds yet */
- if(countindex) {
+ CURR_TIME:data->progress.speeder_c) - 1;
+
+ /* first of all, we don't do this if there's no counted seconds yet */
+ if(countindex) {
int checkindex;
timediff_t span_ms;
-
- /* Get the index position to compare with the 'nowindex' position.
- Get the oldest entry possible. While we have less than CURR_TIME
- entries, the first entry will remain the oldest. */
+
+ /* Get the index position to compare with the 'nowindex' position.
+ Get the oldest entry possible. While we have less than CURR_TIME
+ entries, the first entry will remain the oldest. */
checkindex = (data->progress.speeder_c >= CURR_TIME)?
- data->progress.speeder_c%CURR_TIME:0;
-
- /* Figure out the exact time for the time span */
+ data->progress.speeder_c%CURR_TIME:0;
+
+ /* Figure out the exact time for the time span */
span_ms = Curl_timediff(now, data->progress.speeder_time[checkindex]);
- if(0 == span_ms)
+ if(0 == span_ms)
span_ms = 1; /* at least one millisecond MUST have passed */
-
- /* Calculate the average speed the last 'span_ms' milliseconds */
- {
- curl_off_t amount = data->progress.speeder[nowindex]-
- data->progress.speeder[checkindex];
-
- if(amount > CURL_OFF_T_C(4294967) /* 0xffffffff/1000 */)
- /* the 'amount' value is bigger than would fit in 32 bits if
- multiplied with 1000, so we use the double math for this */
- data->progress.current_speed = (curl_off_t)
- ((double)amount/((double)span_ms/1000.0));
- else
- /* the 'amount' value is small enough to fit within 32 bits even
- when multiplied with 1000 */
- data->progress.current_speed = amount*CURL_OFF_T_C(1000)/span_ms;
- }
- }
- else
+
+ /* Calculate the average speed the last 'span_ms' milliseconds */
+ {
+ curl_off_t amount = data->progress.speeder[nowindex]-
+ data->progress.speeder[checkindex];
+
+ if(amount > CURL_OFF_T_C(4294967) /* 0xffffffff/1000 */)
+ /* the 'amount' value is bigger than would fit in 32 bits if
+ multiplied with 1000, so we use the double math for this */
+ data->progress.current_speed = (curl_off_t)
+ ((double)amount/((double)span_ms/1000.0));
+ else
+ /* the 'amount' value is small enough to fit within 32 bits even
+ when multiplied with 1000 */
+ data->progress.current_speed = amount*CURL_OFF_T_C(1000)/span_ms;
+ }
+ }
+ else
/* the first second we use the average */
- data->progress.current_speed =
+ data->progress.current_speed =
data->progress.ulspeed + data->progress.dlspeed;
-
- } /* Calculations end */
+
+ } /* Calculations end */
return timetoshow;
}
-
+
#ifndef CURL_DISABLE_PROGRESS_METER
static void progress_meter(struct connectdata *conn)
{
@@ -586,10 +586,10 @@ int Curl_pgrsUpdate(struct connectdata *conn)
struct Curl_easy *data = conn->data;
struct curltime now = Curl_now(); /* what time is it */
bool showprogress = progress_calc(conn, now);
- if(!(data->progress.flags & PGRS_HIDE)) {
- if(data->set.fxferinfo) {
+ if(!(data->progress.flags & PGRS_HIDE)) {
+ if(data->set.fxferinfo) {
int result;
- /* There's a callback set, call that */
+ /* There's a callback set, call that */
Curl_set_in_callback(data, true);
result = data->set.fxferinfo(data->set.progress_client,
data->progress.size_dl,
@@ -602,10 +602,10 @@ int Curl_pgrsUpdate(struct connectdata *conn)
failf(data, "Callback aborted");
return result;
}
- }
+ }
else if(data->set.fprogress) {
int result;
- /* The older deprecated callback is set, call that */
+ /* The older deprecated callback is set, call that */
Curl_set_in_callback(data, true);
result = data->set.fprogress(data->set.progress_client,
(double)data->progress.size_dl,
@@ -618,11 +618,11 @@ int Curl_pgrsUpdate(struct connectdata *conn)
failf(data, "Callback aborted");
return result;
}
- }
-
+ }
+
if(showprogress)
progress_meter(conn);
}
-
- return 0;
-}
+
+ return 0;
+}
diff --git a/contrib/libs/curl/lib/progress.h b/contrib/libs/curl/lib/progress.h
index 340adc4b8b..74680099f0 100644
--- a/contrib/libs/curl/lib/progress.h
+++ b/contrib/libs/curl/lib/progress.h
@@ -1,53 +1,53 @@
-#ifndef HEADER_CURL_PROGRESS_H
-#define HEADER_CURL_PROGRESS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_PROGRESS_H
+#define HEADER_CURL_PROGRESS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "timeval.h"
-
-
-typedef enum {
- TIMER_NONE,
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "timeval.h"
+
+
+typedef enum {
+ TIMER_NONE,
TIMER_STARTOP,
TIMER_STARTSINGLE,
- TIMER_NAMELOOKUP,
- TIMER_CONNECT,
- TIMER_APPCONNECT,
- TIMER_PRETRANSFER,
- TIMER_STARTTRANSFER,
- TIMER_POSTRANSFER,
- TIMER_STARTACCEPT,
- TIMER_REDIRECT,
- TIMER_LAST /* must be last */
-} timerid;
-
-int Curl_pgrsDone(struct connectdata *);
+ TIMER_NAMELOOKUP,
+ TIMER_CONNECT,
+ TIMER_APPCONNECT,
+ TIMER_PRETRANSFER,
+ TIMER_STARTTRANSFER,
+ TIMER_POSTRANSFER,
+ TIMER_STARTACCEPT,
+ TIMER_REDIRECT,
+ TIMER_LAST /* must be last */
+} timerid;
+
+int Curl_pgrsDone(struct connectdata *);
void Curl_pgrsStartNow(struct Curl_easy *data);
void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size);
void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size);
void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size);
void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size);
void Curl_ratelimit(struct Curl_easy *data, struct curltime now);
-int Curl_pgrsUpdate(struct connectdata *);
+int Curl_pgrsUpdate(struct connectdata *);
void Curl_pgrsResetTransferSizes(struct Curl_easy *data);
struct curltime Curl_pgrsTime(struct Curl_easy *data, timerid timer);
timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize,
@@ -55,10 +55,10 @@ timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize,
curl_off_t limit,
struct curltime start,
struct curltime now);
-
-#define PGRS_HIDE (1<<4)
-#define PGRS_UL_SIZE_KNOWN (1<<5)
-#define PGRS_DL_SIZE_KNOWN (1<<6)
-#define PGRS_HEADERS_OUT (1<<7) /* set when the headers have been written */
-
-#endif /* HEADER_CURL_PROGRESS_H */
+
+#define PGRS_HIDE (1<<4)
+#define PGRS_UL_SIZE_KNOWN (1<<5)
+#define PGRS_DL_SIZE_KNOWN (1<<6)
+#define PGRS_HEADERS_OUT (1<<7) /* set when the headers have been written */
+
+#endif /* HEADER_CURL_PROGRESS_H */
diff --git a/contrib/libs/curl/lib/rtsp.c b/contrib/libs/curl/lib/rtsp.c
index 614ba8100e..151ff4af27 100644
--- a/contrib/libs/curl/lib/rtsp.c
+++ b/contrib/libs/curl/lib/rtsp.c
@@ -1,158 +1,158 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_RTSP
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
-#include "sendf.h"
-#include "multiif.h"
-#include "http.h"
-#include "url.h"
-#include "progress.h"
-#include "rtsp.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_RTSP
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
+#include "sendf.h"
+#include "multiif.h"
+#include "http.h"
+#include "url.h"
+#include "progress.h"
+#include "rtsp.h"
#include "strcase.h"
-#include "select.h"
-#include "connect.h"
+#include "select.h"
+#include "connect.h"
#include "strdup.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-#define RTP_PKT_CHANNEL(p) ((int)((unsigned char)((p)[1])))
-
-#define RTP_PKT_LENGTH(p) ((((int)((unsigned char)((p)[2]))) << 8) | \
- ((int)((unsigned char)((p)[3]))))
-
-/* protocol-specific functions set up to be called by the main engine */
-static CURLcode rtsp_do(struct connectdata *conn, bool *done);
-static CURLcode rtsp_done(struct connectdata *conn, CURLcode, bool premature);
-static CURLcode rtsp_connect(struct connectdata *conn, bool *done);
-static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead);
+#include "memdebug.h"
+
+#define RTP_PKT_CHANNEL(p) ((int)((unsigned char)((p)[1])))
+
+#define RTP_PKT_LENGTH(p) ((((int)((unsigned char)((p)[2]))) << 8) | \
+ ((int)((unsigned char)((p)[3]))))
+
+/* protocol-specific functions set up to be called by the main engine */
+static CURLcode rtsp_do(struct connectdata *conn, bool *done);
+static CURLcode rtsp_done(struct connectdata *conn, CURLcode, bool premature);
+static CURLcode rtsp_connect(struct connectdata *conn, bool *done);
+static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead);
static int rtsp_getsock_do(struct connectdata *conn, curl_socket_t *socks);
-
-/*
- * Parse and write out any available RTP data.
- *
- * nread: amount of data left after k->str. will be modified if RTP
- * data is parsed and k->str is moved up
- * readmore: whether or not the RTP parser needs more data right away
- */
+
+/*
+ * Parse and write out any available RTP data.
+ *
+ * nread: amount of data left after k->str. will be modified if RTP
+ * data is parsed and k->str is moved up
+ * readmore: whether or not the RTP parser needs more data right away
+ */
static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data,
- struct connectdata *conn,
- ssize_t *nread,
- bool *readmore);
-
-static CURLcode rtsp_setup_connection(struct connectdata *conn);
+ struct connectdata *conn,
+ ssize_t *nread,
+ bool *readmore);
+
+static CURLcode rtsp_setup_connection(struct connectdata *conn);
static unsigned int rtsp_conncheck(struct connectdata *check,
unsigned int checks_to_perform);
-
-/* this returns the socket to wait for in the DO and DOING state for the multi
- interface and then we're always _sending_ a request and thus we wait for
- the single socket to become writable only */
-static int rtsp_getsock_do(struct connectdata *conn,
+
+/* this returns the socket to wait for in the DO and DOING state for the multi
+ interface and then we're always _sending_ a request and thus we wait for
+ the single socket to become writable only */
+static int rtsp_getsock_do(struct connectdata *conn,
curl_socket_t *socks)
-{
- /* write mode */
- socks[0] = conn->sock[FIRSTSOCKET];
- return GETSOCK_WRITESOCK(0);
-}
-
-static
-CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len);
-
-
-/*
- * RTSP handler interface.
- */
-const struct Curl_handler Curl_handler_rtsp = {
- "RTSP", /* scheme */
- rtsp_setup_connection, /* setup_connection */
- rtsp_do, /* do_it */
- rtsp_done, /* done */
- ZERO_NULL, /* do_more */
- rtsp_connect, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- rtsp_getsock_do, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- rtsp_disconnect, /* disconnect */
- rtsp_rtp_readwrite, /* readwrite */
+{
+ /* write mode */
+ socks[0] = conn->sock[FIRSTSOCKET];
+ return GETSOCK_WRITESOCK(0);
+}
+
+static
+CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len);
+
+
+/*
+ * RTSP handler interface.
+ */
+const struct Curl_handler Curl_handler_rtsp = {
+ "RTSP", /* scheme */
+ rtsp_setup_connection, /* setup_connection */
+ rtsp_do, /* do_it */
+ rtsp_done, /* done */
+ ZERO_NULL, /* do_more */
+ rtsp_connect, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ rtsp_getsock_do, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ rtsp_disconnect, /* disconnect */
+ rtsp_rtp_readwrite, /* readwrite */
rtsp_conncheck, /* connection_check */
- PORT_RTSP, /* defport */
- CURLPROTO_RTSP, /* protocol */
+ PORT_RTSP, /* defport */
+ CURLPROTO_RTSP, /* protocol */
CURLPROTO_RTSP, /* family */
- PROTOPT_NONE /* flags */
-};
-
-
-static CURLcode rtsp_setup_connection(struct connectdata *conn)
-{
- struct RTSP *rtsp;
-
+ PROTOPT_NONE /* flags */
+};
+
+
+static CURLcode rtsp_setup_connection(struct connectdata *conn)
+{
+ struct RTSP *rtsp;
+
conn->data->req.p.rtsp = rtsp = calloc(1, sizeof(struct RTSP));
- if(!rtsp)
- return CURLE_OUT_OF_MEMORY;
-
- return CURLE_OK;
-}
-
-
-/*
- * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
- * want to block the application forever while receiving a stream. Therefore,
- * we cannot assume that an RTSP socket is dead just because it is readable.
- *
+ if(!rtsp)
+ return CURLE_OUT_OF_MEMORY;
+
+ return CURLE_OK;
+}
+
+
+/*
+ * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
+ * want to block the application forever while receiving a stream. Therefore,
+ * we cannot assume that an RTSP socket is dead just because it is readable.
+ *
* Instead, if it is readable, run Curl_connalive() to peek at the socket
- * and distinguish between closed and data.
- */
+ * and distinguish between closed and data.
+ */
static bool rtsp_connisdead(struct connectdata *check)
-{
- int sval;
- bool ret_val = TRUE;
-
+{
+ int sval;
+ bool ret_val = TRUE;
+
sval = SOCKET_READABLE(check->sock[FIRSTSOCKET], 0);
- if(sval == 0) {
- /* timeout */
- ret_val = FALSE;
- }
- else if(sval & CURL_CSELECT_ERR) {
- /* socket is in an error state */
- ret_val = TRUE;
- }
+ if(sval == 0) {
+ /* timeout */
+ ret_val = FALSE;
+ }
+ else if(sval & CURL_CSELECT_ERR) {
+ /* socket is in an error state */
+ ret_val = TRUE;
+ }
else if(sval & CURL_CSELECT_IN) {
/* readable with no error. could still be closed */
ret_val = !Curl_connalive(check);
- }
-
- return ret_val;
-}
-
+ }
+
+ return ret_val;
+}
+
/*
* Function to check on various aspects of a connection.
*/
@@ -170,220 +170,220 @@ static unsigned int rtsp_conncheck(struct connectdata *check,
}
-static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
-{
- CURLcode httpStatus;
+static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
+{
+ CURLcode httpStatus;
struct Curl_easy *data = conn->data;
-
- httpStatus = Curl_http_connect(conn, done);
-
- /* Initialize the CSeq if not already done */
- if(data->state.rtsp_next_client_CSeq == 0)
- data->state.rtsp_next_client_CSeq = 1;
- if(data->state.rtsp_next_server_CSeq == 0)
- data->state.rtsp_next_server_CSeq = 1;
-
- conn->proto.rtspc.rtp_channel = -1;
-
- return httpStatus;
-}
-
-static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
-{
- (void) dead;
- Curl_safefree(conn->proto.rtspc.rtp_buf);
- return CURLE_OK;
-}
-
-
-static CURLcode rtsp_done(struct connectdata *conn,
- CURLcode status, bool premature)
-{
+
+ httpStatus = Curl_http_connect(conn, done);
+
+ /* Initialize the CSeq if not already done */
+ if(data->state.rtsp_next_client_CSeq == 0)
+ data->state.rtsp_next_client_CSeq = 1;
+ if(data->state.rtsp_next_server_CSeq == 0)
+ data->state.rtsp_next_server_CSeq = 1;
+
+ conn->proto.rtspc.rtp_channel = -1;
+
+ return httpStatus;
+}
+
+static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
+{
+ (void) dead;
+ Curl_safefree(conn->proto.rtspc.rtp_buf);
+ return CURLE_OK;
+}
+
+
+static CURLcode rtsp_done(struct connectdata *conn,
+ CURLcode status, bool premature)
+{
struct Curl_easy *data = conn->data;
struct RTSP *rtsp = data->req.p.rtsp;
- CURLcode httpStatus;
-
- /* Bypass HTTP empty-reply checks on receive */
- if(data->set.rtspreq == RTSPREQ_RECEIVE)
- premature = TRUE;
-
- httpStatus = Curl_http_done(conn, status, premature);
-
- if(rtsp) {
- /* Check the sequence numbers */
+ CURLcode httpStatus;
+
+ /* Bypass HTTP empty-reply checks on receive */
+ if(data->set.rtspreq == RTSPREQ_RECEIVE)
+ premature = TRUE;
+
+ httpStatus = Curl_http_done(conn, status, premature);
+
+ if(rtsp) {
+ /* Check the sequence numbers */
long CSeq_sent = rtsp->CSeq_sent;
long CSeq_recv = rtsp->CSeq_recv;
- if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
- failf(data,
- "The CSeq of this request %ld did not match the response %ld",
- CSeq_sent, CSeq_recv);
- return CURLE_RTSP_CSEQ_ERROR;
- }
+ if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
+ failf(data,
+ "The CSeq of this request %ld did not match the response %ld",
+ CSeq_sent, CSeq_recv);
+ return CURLE_RTSP_CSEQ_ERROR;
+ }
if(data->set.rtspreq == RTSPREQ_RECEIVE &&
- (conn->proto.rtspc.rtp_channel == -1)) {
- infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv);
- }
- }
-
- return httpStatus;
-}
-
-static CURLcode rtsp_do(struct connectdata *conn, bool *done)
-{
+ (conn->proto.rtspc.rtp_channel == -1)) {
+ infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv);
+ }
+ }
+
+ return httpStatus;
+}
+
+static CURLcode rtsp_do(struct connectdata *conn, bool *done)
+{
struct Curl_easy *data = conn->data;
CURLcode result = CURLE_OK;
- Curl_RtspReq rtspreq = data->set.rtspreq;
+ Curl_RtspReq rtspreq = data->set.rtspreq;
struct RTSP *rtsp = data->req.p.rtsp;
struct dynbuf req_buffer;
- curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
- curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
-
- const char *p_request = NULL;
- const char *p_session_id = NULL;
- const char *p_accept = NULL;
- const char *p_accept_encoding = NULL;
- const char *p_range = NULL;
- const char *p_referrer = NULL;
- const char *p_stream_uri = NULL;
- const char *p_transport = NULL;
- const char *p_uagent = NULL;
+ curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
+ curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
+
+ const char *p_request = NULL;
+ const char *p_session_id = NULL;
+ const char *p_accept = NULL;
+ const char *p_accept_encoding = NULL;
+ const char *p_range = NULL;
+ const char *p_referrer = NULL;
+ const char *p_stream_uri = NULL;
+ const char *p_transport = NULL;
+ const char *p_uagent = NULL;
const char *p_proxyuserpwd = NULL;
const char *p_userpwd = NULL;
-
- *done = TRUE;
-
- rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
- rtsp->CSeq_recv = 0;
-
- /* Setup the 'p_request' pointer to the proper p_request string
- * Since all RTSP requests are included here, there is no need to
- * support custom requests like HTTP.
- **/
- data->set.opt_no_body = TRUE; /* most requests don't contain a body */
- switch(rtspreq) {
+
+ *done = TRUE;
+
+ rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
+ rtsp->CSeq_recv = 0;
+
+ /* Setup the 'p_request' pointer to the proper p_request string
+ * Since all RTSP requests are included here, there is no need to
+ * support custom requests like HTTP.
+ **/
+ data->set.opt_no_body = TRUE; /* most requests don't contain a body */
+ switch(rtspreq) {
default:
failf(data, "Got invalid RTSP request");
- return CURLE_BAD_FUNCTION_ARGUMENT;
- case RTSPREQ_OPTIONS:
- p_request = "OPTIONS";
- break;
- case RTSPREQ_DESCRIBE:
- p_request = "DESCRIBE";
- data->set.opt_no_body = FALSE;
- break;
- case RTSPREQ_ANNOUNCE:
- p_request = "ANNOUNCE";
- break;
- case RTSPREQ_SETUP:
- p_request = "SETUP";
- break;
- case RTSPREQ_PLAY:
- p_request = "PLAY";
- break;
- case RTSPREQ_PAUSE:
- p_request = "PAUSE";
- break;
- case RTSPREQ_TEARDOWN:
- p_request = "TEARDOWN";
- break;
- case RTSPREQ_GET_PARAMETER:
- /* GET_PARAMETER's no_body status is determined later */
- p_request = "GET_PARAMETER";
- data->set.opt_no_body = FALSE;
- break;
- case RTSPREQ_SET_PARAMETER:
- p_request = "SET_PARAMETER";
- break;
- case RTSPREQ_RECORD:
- p_request = "RECORD";
- break;
- case RTSPREQ_RECEIVE:
- p_request = "";
- /* Treat interleaved RTP as body*/
- data->set.opt_no_body = FALSE;
- break;
- case RTSPREQ_LAST:
- failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
- return CURLE_BAD_FUNCTION_ARGUMENT;
- }
-
- if(rtspreq == RTSPREQ_RECEIVE) {
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ case RTSPREQ_OPTIONS:
+ p_request = "OPTIONS";
+ break;
+ case RTSPREQ_DESCRIBE:
+ p_request = "DESCRIBE";
+ data->set.opt_no_body = FALSE;
+ break;
+ case RTSPREQ_ANNOUNCE:
+ p_request = "ANNOUNCE";
+ break;
+ case RTSPREQ_SETUP:
+ p_request = "SETUP";
+ break;
+ case RTSPREQ_PLAY:
+ p_request = "PLAY";
+ break;
+ case RTSPREQ_PAUSE:
+ p_request = "PAUSE";
+ break;
+ case RTSPREQ_TEARDOWN:
+ p_request = "TEARDOWN";
+ break;
+ case RTSPREQ_GET_PARAMETER:
+ /* GET_PARAMETER's no_body status is determined later */
+ p_request = "GET_PARAMETER";
+ data->set.opt_no_body = FALSE;
+ break;
+ case RTSPREQ_SET_PARAMETER:
+ p_request = "SET_PARAMETER";
+ break;
+ case RTSPREQ_RECORD:
+ p_request = "RECORD";
+ break;
+ case RTSPREQ_RECEIVE:
+ p_request = "";
+ /* Treat interleaved RTP as body*/
+ data->set.opt_no_body = FALSE;
+ break;
+ case RTSPREQ_LAST:
+ failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+
+ if(rtspreq == RTSPREQ_RECEIVE) {
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1);
-
- return result;
- }
-
- p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
- if(!p_session_id &&
- (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
- failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
+
+ return result;
+ }
+
+ p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
+ if(!p_session_id &&
+ (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
+ failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
p_request);
- return CURLE_BAD_FUNCTION_ARGUMENT;
- }
-
- /* Stream URI. Default to server '*' if not specified */
- if(data->set.str[STRING_RTSP_STREAM_URI]) {
- p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
- }
- else {
- p_stream_uri = "*";
- }
-
- /* Transport Header for SETUP requests */
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+
+ /* Stream URI. Default to server '*' if not specified */
+ if(data->set.str[STRING_RTSP_STREAM_URI]) {
+ p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
+ }
+ else {
+ p_stream_uri = "*";
+ }
+
+ /* Transport Header for SETUP requests */
p_transport = Curl_checkheaders(conn, "Transport");
- if(rtspreq == RTSPREQ_SETUP && !p_transport) {
- /* New Transport: setting? */
- if(data->set.str[STRING_RTSP_TRANSPORT]) {
+ if(rtspreq == RTSPREQ_SETUP && !p_transport) {
+ /* New Transport: setting? */
+ if(data->set.str[STRING_RTSP_TRANSPORT]) {
Curl_safefree(data->state.aptr.rtsp_transport);
-
+
data->state.aptr.rtsp_transport =
- aprintf("Transport: %s\r\n",
- data->set.str[STRING_RTSP_TRANSPORT]);
+ aprintf("Transport: %s\r\n",
+ data->set.str[STRING_RTSP_TRANSPORT]);
if(!data->state.aptr.rtsp_transport)
- return CURLE_OUT_OF_MEMORY;
- }
- else {
- failf(data,
- "Refusing to issue an RTSP SETUP without a Transport: header.");
- return CURLE_BAD_FUNCTION_ARGUMENT;
- }
-
+ return CURLE_OUT_OF_MEMORY;
+ }
+ else {
+ failf(data,
+ "Refusing to issue an RTSP SETUP without a Transport: header.");
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+
p_transport = data->state.aptr.rtsp_transport;
- }
-
- /* Accept Headers for DESCRIBE requests */
- if(rtspreq == RTSPREQ_DESCRIBE) {
- /* Accept Header */
+ }
+
+ /* Accept Headers for DESCRIBE requests */
+ if(rtspreq == RTSPREQ_DESCRIBE) {
+ /* Accept Header */
p_accept = Curl_checkheaders(conn, "Accept")?
- NULL:"Accept: application/sdp\r\n";
-
- /* Accept-Encoding header */
+ NULL:"Accept: application/sdp\r\n";
+
+ /* Accept-Encoding header */
if(!Curl_checkheaders(conn, "Accept-Encoding") &&
- data->set.str[STRING_ENCODING]) {
+ data->set.str[STRING_ENCODING]) {
Curl_safefree(data->state.aptr.accept_encoding);
data->state.aptr.accept_encoding =
- aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
-
+ aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
+
if(!data->state.aptr.accept_encoding)
- return CURLE_OUT_OF_MEMORY;
-
+ return CURLE_OUT_OF_MEMORY;
+
p_accept_encoding = data->state.aptr.accept_encoding;
- }
- }
-
- /* The User-Agent string might have been allocated in url.c already, because
- it might have been used in the proxy connect, but if we have got a header
- with the user-agent string specified, we erase the previously made string
- here. */
+ }
+ }
+
+ /* The User-Agent string might have been allocated in url.c already, because
+ it might have been used in the proxy connect, but if we have got a header
+ with the user-agent string specified, we erase the previously made string
+ here. */
if(Curl_checkheaders(conn, "User-Agent") && data->state.aptr.uagent) {
Curl_safefree(data->state.aptr.uagent);
data->state.aptr.uagent = NULL;
- }
+ }
else if(!Curl_checkheaders(conn, "User-Agent") &&
- data->set.str[STRING_USERAGENT]) {
+ data->set.str[STRING_USERAGENT]) {
p_uagent = data->state.aptr.uagent;
- }
-
+ }
+
/* setup the authentication headers */
result = Curl_http_output_auth(conn, p_request, p_stream_uri, FALSE);
if(result)
@@ -392,68 +392,68 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done)
p_proxyuserpwd = data->state.aptr.proxyuserpwd;
p_userpwd = data->state.aptr.userpwd;
- /* Referrer */
+ /* Referrer */
Curl_safefree(data->state.aptr.ref);
if(data->change.referer && !Curl_checkheaders(conn, "Referer"))
data->state.aptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
- else
+ else
data->state.aptr.ref = NULL;
-
+
p_referrer = data->state.aptr.ref;
-
- /*
- * Range Header
- * Only applies to PLAY, PAUSE, RECORD
- *
- * Go ahead and use the Range stuff supplied for HTTP
- */
- if(data->state.use_range &&
- (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
-
- /* Check to see if there is a range set in the custom headers */
+
+ /*
+ * Range Header
+ * Only applies to PLAY, PAUSE, RECORD
+ *
+ * Go ahead and use the Range stuff supplied for HTTP
+ */
+ if(data->state.use_range &&
+ (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
+
+ /* Check to see if there is a range set in the custom headers */
if(!Curl_checkheaders(conn, "Range") && data->state.range) {
Curl_safefree(data->state.aptr.rangeline);
data->state.aptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
p_range = data->state.aptr.rangeline;
- }
- }
-
- /*
- * Sanity check the custom headers
- */
+ }
+ }
+
+ /*
+ * Sanity check the custom headers
+ */
if(Curl_checkheaders(conn, "CSeq")) {
- failf(data, "CSeq cannot be set as a custom header.");
- return CURLE_RTSP_CSEQ_ERROR;
- }
+ failf(data, "CSeq cannot be set as a custom header.");
+ return CURLE_RTSP_CSEQ_ERROR;
+ }
if(Curl_checkheaders(conn, "Session")) {
- failf(data, "Session ID cannot be set as a custom header.");
- return CURLE_BAD_FUNCTION_ARGUMENT;
- }
-
- /* Initialize a dynamic send buffer */
+ failf(data, "Session ID cannot be set as a custom header.");
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+
+ /* Initialize a dynamic send buffer */
Curl_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER);
-
- result =
+
+ result =
Curl_dyn_addf(&req_buffer,
"%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
"CSeq: %ld\r\n", /* CSeq */
p_request, p_stream_uri, rtsp->CSeq_sent);
- if(result)
- return result;
-
- /*
- * Rather than do a normal alloc line, keep the session_id unformatted
- * to make comparison easier
- */
- if(p_session_id) {
+ if(result)
+ return result;
+
+ /*
+ * Rather than do a normal alloc line, keep the session_id unformatted
+ * to make comparison easier
+ */
+ if(p_session_id) {
result = Curl_dyn_addf(&req_buffer, "Session: %s\r\n", p_session_id);
- if(result)
- return result;
- }
-
- /*
- * Shared HTTP-like options
- */
+ if(result)
+ return result;
+ }
+
+ /*
+ * Shared HTTP-like options
+ */
result = Curl_dyn_addf(&req_buffer,
"%s" /* transport */
"%s" /* accept */
@@ -480,164 +480,164 @@ static CURLcode rtsp_do(struct connectdata *conn, bool *done)
Curl_safefree(data->state.aptr.userpwd);
data->state.aptr.userpwd = NULL;
- if(result)
- return result;
-
- if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
+ if(result)
+ return result;
+
+ if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
result = Curl_add_timecondition(conn, &req_buffer);
- if(result)
- return result;
- }
-
+ if(result)
+ return result;
+ }
+
result = Curl_add_custom_headers(conn, FALSE, &req_buffer);
- if(result)
- return result;
-
- if(rtspreq == RTSPREQ_ANNOUNCE ||
- rtspreq == RTSPREQ_SET_PARAMETER ||
- rtspreq == RTSPREQ_GET_PARAMETER) {
-
- if(data->set.upload) {
+ if(result)
+ return result;
+
+ if(rtspreq == RTSPREQ_ANNOUNCE ||
+ rtspreq == RTSPREQ_SET_PARAMETER ||
+ rtspreq == RTSPREQ_GET_PARAMETER) {
+
+ if(data->set.upload) {
putsize = data->state.infilesize;
data->state.httpreq = HTTPREQ_PUT;
-
- }
- else {
+
+ }
+ else {
postsize = (data->state.infilesize != -1)?
data->state.infilesize:
- (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
+ (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
data->state.httpreq = HTTPREQ_POST;
- }
-
- if(putsize > 0 || postsize > 0) {
- /* As stated in the http comments, it is probably not wise to
- * actually set a custom Content-Length in the headers */
+ }
+
+ if(putsize > 0 || postsize > 0) {
+ /* As stated in the http comments, it is probably not wise to
+ * actually set a custom Content-Length in the headers */
if(!Curl_checkheaders(conn, "Content-Length")) {
result =
Curl_dyn_addf(&req_buffer,
"Content-Length: %" CURL_FORMAT_CURL_OFF_T"\r\n",
(data->set.upload ? putsize : postsize));
- if(result)
- return result;
- }
-
- if(rtspreq == RTSPREQ_SET_PARAMETER ||
- rtspreq == RTSPREQ_GET_PARAMETER) {
+ if(result)
+ return result;
+ }
+
+ if(rtspreq == RTSPREQ_SET_PARAMETER ||
+ rtspreq == RTSPREQ_GET_PARAMETER) {
if(!Curl_checkheaders(conn, "Content-Type")) {
result = Curl_dyn_addf(&req_buffer,
"Content-Type: text/parameters\r\n");
- if(result)
- return result;
- }
- }
-
- if(rtspreq == RTSPREQ_ANNOUNCE) {
+ if(result)
+ return result;
+ }
+ }
+
+ if(rtspreq == RTSPREQ_ANNOUNCE) {
if(!Curl_checkheaders(conn, "Content-Type")) {
result = Curl_dyn_addf(&req_buffer,
"Content-Type: application/sdp\r\n");
- if(result)
- return result;
- }
- }
-
- data->state.expect100header = FALSE; /* RTSP posts are simple/small */
- }
- else if(rtspreq == RTSPREQ_GET_PARAMETER) {
- /* Check for an empty GET_PARAMETER (heartbeat) request */
+ if(result)
+ return result;
+ }
+ }
+
+ data->state.expect100header = FALSE; /* RTSP posts are simple/small */
+ }
+ else if(rtspreq == RTSPREQ_GET_PARAMETER) {
+ /* Check for an empty GET_PARAMETER (heartbeat) request */
data->state.httpreq = HTTPREQ_HEAD;
- data->set.opt_no_body = TRUE;
- }
- }
-
- /* RTSP never allows chunked transfer */
- data->req.forbidchunk = TRUE;
- /* Finish the request buffer */
+ data->set.opt_no_body = TRUE;
+ }
+ }
+
+ /* RTSP never allows chunked transfer */
+ data->req.forbidchunk = TRUE;
+ /* Finish the request buffer */
result = Curl_dyn_add(&req_buffer, "\r\n");
- if(result)
- return result;
-
- if(postsize > 0) {
+ if(result)
+ return result;
+
+ if(postsize > 0) {
result = Curl_dyn_addn(&req_buffer, data->set.postfields,
(size_t)postsize);
- if(result)
- return result;
- }
-
- /* issue the request */
+ if(result)
+ return result;
+ }
+
+ /* issue the request */
result = Curl_buffer_send(&req_buffer, conn,
&data->info.request_size, 0, FIRSTSOCKET);
- if(result) {
- failf(data, "Failed sending RTSP request");
- return result;
- }
-
+ if(result) {
+ failf(data, "Failed sending RTSP request");
+ return result;
+ }
+
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, putsize?FIRSTSOCKET:-1);
-
- /* Increment the CSeq on success */
- data->state.rtsp_next_client_CSeq++;
-
+
+ /* Increment the CSeq on success */
+ data->state.rtsp_next_client_CSeq++;
+
if(data->req.writebytecount) {
- /* if a request-body has been sent off, we make sure this progress is
- noted properly */
+ /* if a request-body has been sent off, we make sure this progress is
+ noted properly */
Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
- if(Curl_pgrsUpdate(conn))
- result = CURLE_ABORTED_BY_CALLBACK;
- }
-
- return result;
-}
-
-
+ if(Curl_pgrsUpdate(conn))
+ result = CURLE_ABORTED_BY_CALLBACK;
+ }
+
+ return result;
+}
+
+
static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data,
- struct connectdata *conn,
- ssize_t *nread,
- bool *readmore) {
- struct SingleRequest *k = &data->req;
- struct rtsp_conn *rtspc = &(conn->proto.rtspc);
-
- char *rtp; /* moving pointer to rtp data */
- ssize_t rtp_dataleft; /* how much data left to parse in this round */
- char *scratch;
- CURLcode result;
-
- if(rtspc->rtp_buf) {
- /* There was some leftover data the last time. Merge buffers */
+ struct connectdata *conn,
+ ssize_t *nread,
+ bool *readmore) {
+ struct SingleRequest *k = &data->req;
+ struct rtsp_conn *rtspc = &(conn->proto.rtspc);
+
+ char *rtp; /* moving pointer to rtp data */
+ ssize_t rtp_dataleft; /* how much data left to parse in this round */
+ char *scratch;
+ CURLcode result;
+
+ if(rtspc->rtp_buf) {
+ /* There was some leftover data the last time. Merge buffers */
char *newptr = Curl_saferealloc(rtspc->rtp_buf,
rtspc->rtp_bufsize + *nread);
- if(!newptr) {
- rtspc->rtp_buf = NULL;
- rtspc->rtp_bufsize = 0;
- return CURLE_OUT_OF_MEMORY;
- }
- rtspc->rtp_buf = newptr;
- memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
- rtspc->rtp_bufsize += *nread;
- rtp = rtspc->rtp_buf;
- rtp_dataleft = rtspc->rtp_bufsize;
- }
- else {
- /* Just parse the request buffer directly */
- rtp = k->str;
- rtp_dataleft = *nread;
- }
-
- while((rtp_dataleft > 0) &&
- (rtp[0] == '$')) {
- if(rtp_dataleft > 4) {
- int rtp_length;
-
- /* Parse the header */
- /* The channel identifier immediately follows and is 1 byte */
- rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
-
- /* The length is two bytes */
- rtp_length = RTP_PKT_LENGTH(rtp);
-
- if(rtp_dataleft < rtp_length + 4) {
- /* Need more - incomplete payload*/
- *readmore = TRUE;
- break;
- }
+ if(!newptr) {
+ rtspc->rtp_buf = NULL;
+ rtspc->rtp_bufsize = 0;
+ return CURLE_OUT_OF_MEMORY;
+ }
+ rtspc->rtp_buf = newptr;
+ memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
+ rtspc->rtp_bufsize += *nread;
+ rtp = rtspc->rtp_buf;
+ rtp_dataleft = rtspc->rtp_bufsize;
+ }
+ else {
+ /* Just parse the request buffer directly */
+ rtp = k->str;
+ rtp_dataleft = *nread;
+ }
+
+ while((rtp_dataleft > 0) &&
+ (rtp[0] == '$')) {
+ if(rtp_dataleft > 4) {
+ int rtp_length;
+
+ /* Parse the header */
+ /* The channel identifier immediately follows and is 1 byte */
+ rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
+
+ /* The length is two bytes */
+ rtp_length = RTP_PKT_LENGTH(rtp);
+
+ if(rtp_dataleft < rtp_length + 4) {
+ /* Need more - incomplete payload*/
+ *readmore = TRUE;
+ break;
+ }
/* We have the full RTP interleaved packet
* Write out the header including the leading '$' */
DEBUGF(infof(data, "RTP write channel %d rtp_length %d\n",
@@ -651,80 +651,80 @@ static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data,
rtspc->rtp_bufsize = 0;
return result;
}
-
+
/* Move forward in the buffer */
rtp_dataleft -= rtp_length + 4;
rtp += rtp_length + 4;
-
+
if(data->set.rtspreq == RTSPREQ_RECEIVE) {
/* If we are in a passive receive, give control back
* to the app as often as we can.
*/
k->keepon &= ~KEEP_RECV;
- }
- }
- else {
- /* Need more - incomplete header */
- *readmore = TRUE;
- break;
- }
- }
-
- if(rtp_dataleft != 0 && rtp[0] == '$') {
- DEBUGF(infof(data, "RTP Rewinding %zd %s\n", rtp_dataleft,
- *readmore ? "(READMORE)" : ""));
-
- /* Store the incomplete RTP packet for a "rewind" */
- scratch = malloc(rtp_dataleft);
- if(!scratch) {
- Curl_safefree(rtspc->rtp_buf);
- rtspc->rtp_buf = NULL;
- rtspc->rtp_bufsize = 0;
- return CURLE_OUT_OF_MEMORY;
- }
- memcpy(scratch, rtp, rtp_dataleft);
- Curl_safefree(rtspc->rtp_buf);
- rtspc->rtp_buf = scratch;
- rtspc->rtp_bufsize = rtp_dataleft;
-
- /* As far as the transfer is concerned, this data is consumed */
- *nread = 0;
- return CURLE_OK;
- }
+ }
+ }
+ else {
+ /* Need more - incomplete header */
+ *readmore = TRUE;
+ break;
+ }
+ }
+
+ if(rtp_dataleft != 0 && rtp[0] == '$') {
+ DEBUGF(infof(data, "RTP Rewinding %zd %s\n", rtp_dataleft,
+ *readmore ? "(READMORE)" : ""));
+
+ /* Store the incomplete RTP packet for a "rewind" */
+ scratch = malloc(rtp_dataleft);
+ if(!scratch) {
+ Curl_safefree(rtspc->rtp_buf);
+ rtspc->rtp_buf = NULL;
+ rtspc->rtp_bufsize = 0;
+ return CURLE_OUT_OF_MEMORY;
+ }
+ memcpy(scratch, rtp, rtp_dataleft);
+ Curl_safefree(rtspc->rtp_buf);
+ rtspc->rtp_buf = scratch;
+ rtspc->rtp_bufsize = rtp_dataleft;
+
+ /* As far as the transfer is concerned, this data is consumed */
+ *nread = 0;
+ return CURLE_OK;
+ }
/* Fix up k->str to point just after the last RTP packet */
k->str += *nread - rtp_dataleft;
-
+
/* either all of the data has been read or...
* rtp now points at the next byte to parse
*/
if(rtp_dataleft > 0)
DEBUGASSERT(k->str[0] == rtp[0]);
-
+
DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
-
+
*nread = rtp_dataleft;
-
- /* If we get here, we have finished with the leftover/merge buffer */
- Curl_safefree(rtspc->rtp_buf);
- rtspc->rtp_buf = NULL;
- rtspc->rtp_bufsize = 0;
-
- return CURLE_OK;
-}
-
-static
-CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
-{
+
+ /* If we get here, we have finished with the leftover/merge buffer */
+ Curl_safefree(rtspc->rtp_buf);
+ rtspc->rtp_buf = NULL;
+ rtspc->rtp_bufsize = 0;
+
+ return CURLE_OK;
+}
+
+static
+CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
+{
struct Curl_easy *data = conn->data;
- size_t wrote;
- curl_write_callback writeit;
+ size_t wrote;
+ curl_write_callback writeit;
void *user_ptr;
-
- if(len == 0) {
+
+ if(len == 0) {
failf(data, "Cannot write a 0 size RTP packet.");
- return CURLE_WRITE_ERROR;
- }
-
+ return CURLE_WRITE_ERROR;
+ }
+
/* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that
function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP
data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA
@@ -737,57 +737,57 @@ CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
writeit = data->set.fwrite_func;
user_ptr = data->set.out;
}
-
+
Curl_set_in_callback(data, true);
wrote = writeit(ptr, 1, len, user_ptr);
Curl_set_in_callback(data, false);
- if(CURL_WRITEFUNC_PAUSE == wrote) {
+ if(CURL_WRITEFUNC_PAUSE == wrote) {
failf(data, "Cannot pause RTP");
- return CURLE_WRITE_ERROR;
- }
-
- if(wrote != len) {
+ return CURLE_WRITE_ERROR;
+ }
+
+ if(wrote != len) {
failf(data, "Failed writing RTP data");
- return CURLE_WRITE_ERROR;
- }
-
- return CURLE_OK;
-}
-
-CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
- char *header)
-{
+ return CURLE_WRITE_ERROR;
+ }
+
+ return CURLE_OK;
+}
+
+CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
+ char *header)
+{
struct Curl_easy *data = conn->data;
- long CSeq = 0;
-
- if(checkprefix("CSeq:", header)) {
- /* Store the received CSeq. Match is verified in rtsp_done */
- int nc = sscanf(&header[4], ": %ld", &CSeq);
- if(nc == 1) {
+ long CSeq = 0;
+
+ if(checkprefix("CSeq:", header)) {
+ /* Store the received CSeq. Match is verified in rtsp_done */
+ int nc = sscanf(&header[4], ": %ld", &CSeq);
+ if(nc == 1) {
struct RTSP *rtsp = data->req.p.rtsp;
- rtsp->CSeq_recv = CSeq; /* mark the request */
- data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
- }
- else {
- failf(data, "Unable to read the CSeq header: [%s]", header);
- return CURLE_RTSP_CSEQ_ERROR;
- }
- }
- else if(checkprefix("Session:", header)) {
- char *start;
+ rtsp->CSeq_recv = CSeq; /* mark the request */
+ data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
+ }
+ else {
+ failf(data, "Unable to read the CSeq header: [%s]", header);
+ return CURLE_RTSP_CSEQ_ERROR;
+ }
+ }
+ else if(checkprefix("Session:", header)) {
+ char *start;
char *end;
size_t idlen;
-
- /* Find the first non-space letter */
+
+ /* Find the first non-space letter */
start = header + 8;
- while(*start && ISSPACE(*start))
- start++;
-
- if(!*start) {
- failf(data, "Got a blank Session ID");
+ while(*start && ISSPACE(*start))
+ start++;
+
+ if(!*start) {
+ failf(data, "Got a blank Session ID");
return CURLE_RTSP_SESSION_ERROR;
- }
+ }
/* Find the end of Session ID
*
@@ -802,28 +802,28 @@ CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
if(data->set.str[STRING_RTSP_SESSION_ID]) {
- /* If the Session ID is set, then compare */
+ /* If the Session ID is set, then compare */
if(strlen(data->set.str[STRING_RTSP_SESSION_ID]) != idlen ||
strncmp(start, data->set.str[STRING_RTSP_SESSION_ID], idlen) != 0) {
- failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
- start, data->set.str[STRING_RTSP_SESSION_ID]);
- return CURLE_RTSP_SESSION_ERROR;
- }
- }
- else {
+ failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
+ start, data->set.str[STRING_RTSP_SESSION_ID]);
+ return CURLE_RTSP_SESSION_ERROR;
+ }
+ }
+ else {
/* If the Session ID is not set, and we find it in a response, then set
* it.
*/
-
- /* Copy the id substring into a new buffer */
+
+ /* Copy the id substring into a new buffer */
data->set.str[STRING_RTSP_SESSION_ID] = malloc(idlen + 1);
- if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
- return CURLE_OUT_OF_MEMORY;
+ if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
+ return CURLE_OUT_OF_MEMORY;
memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, idlen);
(data->set.str[STRING_RTSP_SESSION_ID])[idlen] = '\0';
- }
- }
- return CURLE_OK;
-}
-
-#endif /* CURL_DISABLE_RTSP */
+ }
+ }
+ return CURLE_OK;
+}
+
+#endif /* CURL_DISABLE_RTSP */
diff --git a/contrib/libs/curl/lib/rtsp.h b/contrib/libs/curl/lib/rtsp.h
index 2d43b15dec..bf7f0bc8ef 100644
--- a/contrib/libs/curl/lib/rtsp.h
+++ b/contrib/libs/curl/lib/rtsp.h
@@ -1,66 +1,66 @@
-#ifndef HEADER_CURL_RTSP_H
-#define HEADER_CURL_RTSP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_RTSP_H
+#define HEADER_CURL_RTSP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifndef CURL_DISABLE_RTSP
-
-extern const struct Curl_handler Curl_handler_rtsp;
-
-CURLcode Curl_rtsp_parseheader(struct connectdata *conn, char *header);
-
-#else
-/* disabled */
-#define Curl_rtsp_parseheader(x,y) CURLE_NOT_BUILT_IN
-
-#endif /* CURL_DISABLE_RTSP */
-
-/*
- * RTSP Connection data
- *
- * Currently, only used for tracking incomplete RTP data reads
- */
-struct rtsp_conn {
- char *rtp_buf;
- ssize_t rtp_bufsize;
- int rtp_channel;
-};
-
-/****************************************************************************
- * RTSP unique setup
- ***************************************************************************/
-struct RTSP {
- /*
- * http_wrapper MUST be the first element of this structure for the wrap
- * logic to work. In this way, we get a cheap polymorphism because
- * &(data->state.proto.rtsp) == &(data->state.proto.http) per the C spec
- *
- * HTTP functions can safely treat this as an HTTP struct, but RTSP aware
- * functions can also index into the later elements.
- */
- struct HTTP http_wrapper; /*wrap HTTP to do the heavy lifting */
-
- long CSeq_sent; /* CSeq of this request */
- long CSeq_recv; /* CSeq received */
-};
-
-
-#endif /* HEADER_CURL_RTSP_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifndef CURL_DISABLE_RTSP
+
+extern const struct Curl_handler Curl_handler_rtsp;
+
+CURLcode Curl_rtsp_parseheader(struct connectdata *conn, char *header);
+
+#else
+/* disabled */
+#define Curl_rtsp_parseheader(x,y) CURLE_NOT_BUILT_IN
+
+#endif /* CURL_DISABLE_RTSP */
+
+/*
+ * RTSP Connection data
+ *
+ * Currently, only used for tracking incomplete RTP data reads
+ */
+struct rtsp_conn {
+ char *rtp_buf;
+ ssize_t rtp_bufsize;
+ int rtp_channel;
+};
+
+/****************************************************************************
+ * RTSP unique setup
+ ***************************************************************************/
+struct RTSP {
+ /*
+ * http_wrapper MUST be the first element of this structure for the wrap
+ * logic to work. In this way, we get a cheap polymorphism because
+ * &(data->state.proto.rtsp) == &(data->state.proto.http) per the C spec
+ *
+ * HTTP functions can safely treat this as an HTTP struct, but RTSP aware
+ * functions can also index into the later elements.
+ */
+ struct HTTP http_wrapper; /*wrap HTTP to do the heavy lifting */
+
+ long CSeq_sent; /* CSeq of this request */
+ long CSeq_recv; /* CSeq received */
+};
+
+
+#endif /* HEADER_CURL_RTSP_H */
diff --git a/contrib/libs/curl/lib/select.c b/contrib/libs/curl/lib/select.c
index 9160c760e4..7d1f944cdb 100644
--- a/contrib/libs/curl/lib/select.c
+++ b/contrib/libs/curl/lib/select.c
@@ -1,88 +1,88 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <limits.h>
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
#elif defined(HAVE_UNISTD_H)
#include <unistd.h>
-#endif
-
-#if !defined(HAVE_SELECT) && !defined(HAVE_POLL_FINE)
-#error "We can't compile without select() or poll() support."
-#endif
-
-#if defined(__BEOS__) && !defined(__HAIKU__)
-/* BeOS has FD_SET defined in socket.h */
-#include <socket.h>
-#endif
-
-#ifdef MSDOS
-#include <dos.h> /* delay() */
-#endif
-
+#endif
+
+#if !defined(HAVE_SELECT) && !defined(HAVE_POLL_FINE)
+#error "We can't compile without select() or poll() support."
+#endif
+
+#if defined(__BEOS__) && !defined(__HAIKU__)
+/* BeOS has FD_SET defined in socket.h */
+#include <socket.h>
+#endif
+
+#ifdef MSDOS
+#include <dos.h> /* delay() */
+#endif
+
#ifdef __VXWORKS__
#include <strings.h> /* bzero() in FD_SET */
#endif
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "connect.h"
-#include "select.h"
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "connect.h"
+#include "select.h"
#include "timeval.h"
-#include "warnless.h"
-
-/*
- * Internal function used for waiting a specific amount of ms
+#include "warnless.h"
+
+/*
+ * Internal function used for waiting a specific amount of ms
* in Curl_socket_check() and Curl_poll() when no file descriptor
- * is provided to wait on, just being used to delay execution.
- * WinSock select() and poll() timeout mechanisms need a valid
- * socket descriptor in a not null file descriptor set to work.
- * Waiting indefinitely with this function is not allowed, a
- * zero or negative timeout value will return immediately.
- * Timeout resolution, accuracy, as well as maximum supported
- * value is system dependent, neither factor is a citical issue
- * for the intended use of this function in the library.
- *
- * Return values:
- * -1 = system call error, invalid timeout value, or interrupted
- * 0 = specified timeout has elapsed
- */
+ * is provided to wait on, just being used to delay execution.
+ * WinSock select() and poll() timeout mechanisms need a valid
+ * socket descriptor in a not null file descriptor set to work.
+ * Waiting indefinitely with this function is not allowed, a
+ * zero or negative timeout value will return immediately.
+ * Timeout resolution, accuracy, as well as maximum supported
+ * value is system dependent, neither factor is a citical issue
+ * for the intended use of this function in the library.
+ *
+ * Return values:
+ * -1 = system call error, invalid timeout value, or interrupted
+ * 0 = specified timeout has elapsed
+ */
int Curl_wait_ms(timediff_t timeout_ms)
-{
- int r = 0;
-
- if(!timeout_ms)
- return 0;
- if(timeout_ms < 0) {
- SET_SOCKERRNO(EINVAL);
- return -1;
- }
-#if defined(MSDOS)
- delay(timeout_ms);
+{
+ int r = 0;
+
+ if(!timeout_ms)
+ return 0;
+ if(timeout_ms < 0) {
+ SET_SOCKERRNO(EINVAL);
+ return -1;
+ }
+#if defined(MSDOS)
+ delay(timeout_ms);
#elif defined(WIN32)
/* prevent overflow, timeout_ms is typecast to ULONG/DWORD. */
#if TIMEDIFF_T_MAX >= ULONG_MAX
@@ -91,15 +91,15 @@ int Curl_wait_ms(timediff_t timeout_ms)
/* don't use ULONG_MAX, because that is equal to INFINITE */
#endif
Sleep((ULONG)timeout_ms);
-#else
-#if defined(HAVE_POLL_FINE)
+#else
+#if defined(HAVE_POLL_FINE)
/* prevent overflow, timeout_ms is typecast to int. */
#if TIMEDIFF_T_MAX > INT_MAX
if(timeout_ms > INT_MAX)
timeout_ms = INT_MAX;
#endif
r = poll(NULL, 0, (int)timeout_ms);
-#else
+#else
{
struct timeval pending_tv;
timediff_t tv_sec = timeout_ms / 1000;
@@ -121,16 +121,16 @@ int Curl_wait_ms(timediff_t timeout_ms)
pending_tv.tv_sec = (int)tv_sec;
pending_tv.tv_usec = (int)tv_usec;
#endif
- r = select(0, NULL, NULL, NULL, &pending_tv);
+ r = select(0, NULL, NULL, NULL, &pending_tv);
}
-#endif /* HAVE_POLL_FINE */
-#endif /* USE_WINSOCK */
- if(r)
- r = -1;
- return r;
-}
-
-/*
+#endif /* HAVE_POLL_FINE */
+#endif /* USE_WINSOCK */
+ if(r)
+ r = -1;
+ return r;
+}
+
+/*
* This is a wrapper around select() to aid in Windows compatibility.
* A negative timeout value makes this function wait indefinitely,
* unless no valid file descriptor is given, when this happens the
@@ -221,142 +221,142 @@ int Curl_select(curl_socket_t maxfd, /* highest socket number */
}
/*
- * Wait for read or write events on a set of file descriptors. It uses poll()
- * when a fine poll() is available, in order to avoid limits with FD_SETSIZE,
- * otherwise select() is used. An error is returned if select() is being used
- * and a file descriptor is too large for FD_SETSIZE.
- *
- * A negative timeout value makes this function wait indefinitely,
+ * Wait for read or write events on a set of file descriptors. It uses poll()
+ * when a fine poll() is available, in order to avoid limits with FD_SETSIZE,
+ * otherwise select() is used. An error is returned if select() is being used
+ * and a file descriptor is too large for FD_SETSIZE.
+ *
+ * A negative timeout value makes this function wait indefinitely,
* unless no valid file descriptor is given, when this happens the
- * negative timeout is ignored and the function times out immediately.
- *
- * Return values:
- * -1 = system call error or fd >= FD_SETSIZE
- * 0 = timeout
- * [bitmask] = action as described below
- *
- * CURL_CSELECT_IN - first socket is readable
- * CURL_CSELECT_IN2 - second socket is readable
- * CURL_CSELECT_OUT - write socket is writable
- * CURL_CSELECT_ERR - an error condition occurred
- */
-int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
- curl_socket_t readfd1,
- curl_socket_t writefd, /* socket to write to */
+ * negative timeout is ignored and the function times out immediately.
+ *
+ * Return values:
+ * -1 = system call error or fd >= FD_SETSIZE
+ * 0 = timeout
+ * [bitmask] = action as described below
+ *
+ * CURL_CSELECT_IN - first socket is readable
+ * CURL_CSELECT_IN2 - second socket is readable
+ * CURL_CSELECT_OUT - write socket is writable
+ * CURL_CSELECT_ERR - an error condition occurred
+ */
+int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
+ curl_socket_t readfd1,
+ curl_socket_t writefd, /* socket to write to */
timediff_t timeout_ms) /* milliseconds to wait */
-{
- struct pollfd pfd[3];
- int num;
- int r;
-
- if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) &&
- (writefd == CURL_SOCKET_BAD)) {
- /* no sockets, just wait */
+{
+ struct pollfd pfd[3];
+ int num;
+ int r;
+
+ if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) &&
+ (writefd == CURL_SOCKET_BAD)) {
+ /* no sockets, just wait */
return Curl_wait_ms(timeout_ms);
- }
-
+ }
+
/* Avoid initial timestamp, avoid Curl_now() call, when elapsed
- time in this function does not need to be measured. This happens
- when function is called with a zero timeout or a negative timeout
- value indicating a blocking call should be performed. */
-
- num = 0;
- if(readfd0 != CURL_SOCKET_BAD) {
- pfd[num].fd = readfd0;
- pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
- pfd[num].revents = 0;
- num++;
- }
- if(readfd1 != CURL_SOCKET_BAD) {
- pfd[num].fd = readfd1;
- pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
- pfd[num].revents = 0;
- num++;
- }
- if(writefd != CURL_SOCKET_BAD) {
- pfd[num].fd = writefd;
+ time in this function does not need to be measured. This happens
+ when function is called with a zero timeout or a negative timeout
+ value indicating a blocking call should be performed. */
+
+ num = 0;
+ if(readfd0 != CURL_SOCKET_BAD) {
+ pfd[num].fd = readfd0;
+ pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
+ pfd[num].revents = 0;
+ num++;
+ }
+ if(readfd1 != CURL_SOCKET_BAD) {
+ pfd[num].fd = readfd1;
+ pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
+ pfd[num].revents = 0;
+ num++;
+ }
+ if(writefd != CURL_SOCKET_BAD) {
+ pfd[num].fd = writefd;
pfd[num].events = POLLWRNORM|POLLOUT|POLLPRI;
- pfd[num].revents = 0;
- num++;
- }
-
+ pfd[num].revents = 0;
+ num++;
+ }
+
r = Curl_poll(pfd, num, timeout_ms);
if(r <= 0)
return r;
-
+
r = 0;
- num = 0;
- if(readfd0 != CURL_SOCKET_BAD) {
- if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
+ num = 0;
+ if(readfd0 != CURL_SOCKET_BAD) {
+ if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
r |= CURL_CSELECT_IN;
- if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
+ if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
r |= CURL_CSELECT_ERR;
- num++;
- }
- if(readfd1 != CURL_SOCKET_BAD) {
- if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
+ num++;
+ }
+ if(readfd1 != CURL_SOCKET_BAD) {
+ if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
r |= CURL_CSELECT_IN2;
- if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
+ if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
r |= CURL_CSELECT_ERR;
- num++;
- }
- if(writefd != CURL_SOCKET_BAD) {
- if(pfd[num].revents & (POLLWRNORM|POLLOUT))
+ num++;
+ }
+ if(writefd != CURL_SOCKET_BAD) {
+ if(pfd[num].revents & (POLLWRNORM|POLLOUT))
r |= CURL_CSELECT_OUT;
if(pfd[num].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL))
r |= CURL_CSELECT_ERR;
- }
-
+ }
+
return r;
-}
-
-/*
- * This is a wrapper around poll(). If poll() does not exist, then
- * select() is used instead. An error is returned if select() is
- * being used and a file descriptor is too large for FD_SETSIZE.
- * A negative timeout value makes this function wait indefinitely,
+}
+
+/*
+ * This is a wrapper around poll(). If poll() does not exist, then
+ * select() is used instead. An error is returned if select() is
+ * being used and a file descriptor is too large for FD_SETSIZE.
+ * A negative timeout value makes this function wait indefinitely,
* unless no valid file descriptor is given, when this happens the
- * negative timeout is ignored and the function times out immediately.
- *
- * Return values:
- * -1 = system call error or fd >= FD_SETSIZE
- * 0 = timeout
- * N = number of structures with non zero revent fields
- */
+ * negative timeout is ignored and the function times out immediately.
+ *
+ * Return values:
+ * -1 = system call error or fd >= FD_SETSIZE
+ * 0 = timeout
+ * N = number of structures with non zero revent fields
+ */
int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms)
-{
+{
#ifdef HAVE_POLL_FINE
int pending_ms;
#else
- fd_set fds_read;
- fd_set fds_write;
- fd_set fds_err;
- curl_socket_t maxfd;
-#endif
- bool fds_none = TRUE;
- unsigned int i;
- int r;
-
- if(ufds) {
- for(i = 0; i < nfds; i++) {
- if(ufds[i].fd != CURL_SOCKET_BAD) {
- fds_none = FALSE;
- break;
- }
- }
- }
- if(fds_none) {
+ fd_set fds_read;
+ fd_set fds_write;
+ fd_set fds_err;
+ curl_socket_t maxfd;
+#endif
+ bool fds_none = TRUE;
+ unsigned int i;
+ int r;
+
+ if(ufds) {
+ for(i = 0; i < nfds; i++) {
+ if(ufds[i].fd != CURL_SOCKET_BAD) {
+ fds_none = FALSE;
+ break;
+ }
+ }
+ }
+ if(fds_none) {
/* no sockets, just wait */
return Curl_wait_ms(timeout_ms);
- }
-
+ }
+
/* Avoid initial timestamp, avoid Curl_now() call, when elapsed
- time in this function does not need to be measured. This happens
- when function is called with a zero timeout or a negative timeout
- value indicating a blocking call should be performed. */
-
-#ifdef HAVE_POLL_FINE
-
+ time in this function does not need to be measured. This happens
+ when function is called with a zero timeout or a negative timeout
+ value indicating a blocking call should be performed. */
+
+#ifdef HAVE_POLL_FINE
+
/* prevent overflow, timeout_ms is typecast to int. */
#if TIMEDIFF_T_MAX > INT_MAX
if(timeout_ms > INT_MAX)
@@ -371,41 +371,41 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms)
r = poll(ufds, nfds, pending_ms);
if(r <= 0)
return r;
-
- for(i = 0; i < nfds; i++) {
- if(ufds[i].fd == CURL_SOCKET_BAD)
- continue;
- if(ufds[i].revents & POLLHUP)
- ufds[i].revents |= POLLIN;
- if(ufds[i].revents & POLLERR)
+
+ for(i = 0; i < nfds; i++) {
+ if(ufds[i].fd == CURL_SOCKET_BAD)
+ continue;
+ if(ufds[i].revents & POLLHUP)
+ ufds[i].revents |= POLLIN;
+ if(ufds[i].revents & POLLERR)
ufds[i].revents |= POLLIN|POLLOUT;
- }
-
-#else /* HAVE_POLL_FINE */
-
- FD_ZERO(&fds_read);
- FD_ZERO(&fds_write);
- FD_ZERO(&fds_err);
- maxfd = (curl_socket_t)-1;
-
- for(i = 0; i < nfds; i++) {
- ufds[i].revents = 0;
- if(ufds[i].fd == CURL_SOCKET_BAD)
- continue;
- VERIFY_SOCK(ufds[i].fd);
- if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI|
+ }
+
+#else /* HAVE_POLL_FINE */
+
+ FD_ZERO(&fds_read);
+ FD_ZERO(&fds_write);
+ FD_ZERO(&fds_err);
+ maxfd = (curl_socket_t)-1;
+
+ for(i = 0; i < nfds; i++) {
+ ufds[i].revents = 0;
+ if(ufds[i].fd == CURL_SOCKET_BAD)
+ continue;
+ VERIFY_SOCK(ufds[i].fd);
+ if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI|
POLLRDNORM|POLLWRNORM|POLLRDBAND)) {
- if(ufds[i].fd > maxfd)
- maxfd = ufds[i].fd;
- if(ufds[i].events & (POLLRDNORM|POLLIN))
- FD_SET(ufds[i].fd, &fds_read);
- if(ufds[i].events & (POLLWRNORM|POLLOUT))
- FD_SET(ufds[i].fd, &fds_write);
- if(ufds[i].events & (POLLRDBAND|POLLPRI))
- FD_SET(ufds[i].fd, &fds_err);
- }
- }
-
+ if(ufds[i].fd > maxfd)
+ maxfd = ufds[i].fd;
+ if(ufds[i].events & (POLLRDNORM|POLLIN))
+ FD_SET(ufds[i].fd, &fds_read);
+ if(ufds[i].events & (POLLWRNORM|POLLOUT))
+ FD_SET(ufds[i].fd, &fds_write);
+ if(ufds[i].events & (POLLRDBAND|POLLPRI))
+ FD_SET(ufds[i].fd, &fds_err);
+ }
+ }
+
/*
Note also that WinSock ignores the first argument, so we don't worry
about the fact that maxfd is computed incorrectly with WinSock (since
@@ -416,11 +416,11 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms)
if(r <= 0)
return r;
- r = 0;
- for(i = 0; i < nfds; i++) {
- ufds[i].revents = 0;
- if(ufds[i].fd == CURL_SOCKET_BAD)
- continue;
+ r = 0;
+ for(i = 0; i < nfds; i++) {
+ ufds[i].revents = 0;
+ if(ufds[i].fd == CURL_SOCKET_BAD)
+ continue;
if(FD_ISSET(ufds[i].fd, &fds_read)) {
if(ufds[i].events & POLLRDNORM)
ufds[i].revents |= POLLRDNORM;
@@ -439,31 +439,31 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms)
if(ufds[i].events & POLLPRI)
ufds[i].revents |= POLLPRI;
}
- if(ufds[i].revents != 0)
- r++;
- }
-
-#endif /* HAVE_POLL_FINE */
-
- return r;
-}
-
-#ifdef TPF
-/*
- * This is a replacement for select() on the TPF platform.
- * It is used whenever libcurl calls select().
- * The call below to tpf_process_signals() is required because
- * TPF's select calls are not signal interruptible.
- *
- * Return values are the same as select's.
- */
+ if(ufds[i].revents != 0)
+ r++;
+ }
+
+#endif /* HAVE_POLL_FINE */
+
+ return r;
+}
+
+#ifdef TPF
+/*
+ * This is a replacement for select() on the TPF platform.
+ * It is used whenever libcurl calls select().
+ * The call below to tpf_process_signals() is required because
+ * TPF's select calls are not signal interruptible.
+ *
+ * Return values are the same as select's.
+ */
int tpf_select_libcurl(int maxfds, fd_set *reads, fd_set *writes,
fd_set *excepts, struct timeval *tv)
-{
- int rc;
-
- rc = tpf_select_bsd(maxfds, reads, writes, excepts, tv);
- tpf_process_signals();
+{
+ int rc;
+
+ rc = tpf_select_bsd(maxfds, reads, writes, excepts, tv);
+ tpf_process_signals();
return rc;
-}
-#endif /* TPF */
+}
+#endif /* TPF */
diff --git a/contrib/libs/curl/lib/select.h b/contrib/libs/curl/lib/select.h
index 3f57f6ac24..1350950439 100644
--- a/contrib/libs/curl/lib/select.h
+++ b/contrib/libs/curl/lib/select.h
@@ -1,108 +1,108 @@
-#ifndef HEADER_CURL_SELECT_H
-#define HEADER_CURL_SELECT_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SELECT_H
+#define HEADER_CURL_SELECT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#ifdef HAVE_POLL_H
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
-#include <sys/poll.h>
-#endif
-
-/*
- * Definition of pollfd struct and constants for platforms lacking them.
- */
-
-#if !defined(HAVE_STRUCT_POLLFD) && \
- !defined(HAVE_SYS_POLL_H) && \
+#include <sys/poll.h>
+#endif
+
+/*
+ * Definition of pollfd struct and constants for platforms lacking them.
+ */
+
+#if !defined(HAVE_STRUCT_POLLFD) && \
+ !defined(HAVE_SYS_POLL_H) && \
!defined(HAVE_POLL_H) && \
!defined(POLLIN)
-
-#define POLLIN 0x01
-#define POLLPRI 0x02
-#define POLLOUT 0x04
-#define POLLERR 0x08
-#define POLLHUP 0x10
-#define POLLNVAL 0x20
-
-struct pollfd
-{
- curl_socket_t fd;
- short events;
- short revents;
-};
-
-#endif
-
-#ifndef POLLRDNORM
-#define POLLRDNORM POLLIN
-#endif
-
-#ifndef POLLWRNORM
-#define POLLWRNORM POLLOUT
-#endif
-
-#ifndef POLLRDBAND
-#define POLLRDBAND POLLPRI
-#endif
-
-/* there are three CSELECT defines that are defined in the public header that
- are exposed to users, but this *IN2 bit is only ever used internally and
- therefore defined here */
-#define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1)
-
+
+#define POLLIN 0x01
+#define POLLPRI 0x02
+#define POLLOUT 0x04
+#define POLLERR 0x08
+#define POLLHUP 0x10
+#define POLLNVAL 0x20
+
+struct pollfd
+{
+ curl_socket_t fd;
+ short events;
+ short revents;
+};
+
+#endif
+
+#ifndef POLLRDNORM
+#define POLLRDNORM POLLIN
+#endif
+
+#ifndef POLLWRNORM
+#define POLLWRNORM POLLOUT
+#endif
+
+#ifndef POLLRDBAND
+#define POLLRDBAND POLLPRI
+#endif
+
+/* there are three CSELECT defines that are defined in the public header that
+ are exposed to users, but this *IN2 bit is only ever used internally and
+ therefore defined here */
+#define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1)
+
int Curl_select(curl_socket_t maxfd,
fd_set *fds_read,
fd_set *fds_write,
fd_set *fds_err,
timediff_t timeout_ms);
-int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2,
- curl_socket_t writefd,
+int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2,
+ curl_socket_t writefd,
timediff_t timeout_ms);
#define SOCKET_READABLE(x,z) \
Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z)
#define SOCKET_WRITABLE(x,z) \
Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z)
-
+
int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms);
int Curl_wait_ms(timediff_t timeout_ms);
-
-#ifdef TPF
-int tpf_select_libcurl(int maxfds, fd_set* reads, fd_set* writes,
+
+#ifdef TPF
+int tpf_select_libcurl(int maxfds, fd_set* reads, fd_set* writes,
fd_set* excepts, struct timeval *tv);
-#endif
-
+#endif
+
/* TPF sockets are not in range [0..FD_SETSIZE-1], which
- unfortunately makes it impossible for us to easily check if they're valid
+ unfortunately makes it impossible for us to easily check if they're valid
With Winsock the valid range is [0..INVALID_SOCKET-1] according to
https://docs.microsoft.com/en-us/windows/win32/winsock/socket-data-type-2
-*/
+*/
#if defined(TPF)
-#define VALID_SOCK(x) 1
-#define VERIFY_SOCK(x) Curl_nop_stmt
+#define VALID_SOCK(x) 1
+#define VERIFY_SOCK(x) Curl_nop_stmt
#elif defined(USE_WINSOCK)
#define VALID_SOCK(s) ((s) < INVALID_SOCKET)
#define VERIFY_SOCK(x) do { \
@@ -111,14 +111,14 @@ int tpf_select_libcurl(int maxfds, fd_set* reads, fd_set* writes,
return -1; \
} \
} while(0)
-#else
-#define VALID_SOCK(s) (((s) >= 0) && ((s) < FD_SETSIZE))
-#define VERIFY_SOCK(x) do { \
- if(!VALID_SOCK(x)) { \
- SET_SOCKERRNO(EINVAL); \
- return -1; \
- } \
+#else
+#define VALID_SOCK(s) (((s) >= 0) && ((s) < FD_SETSIZE))
+#define VERIFY_SOCK(x) do { \
+ if(!VALID_SOCK(x)) { \
+ SET_SOCKERRNO(EINVAL); \
+ return -1; \
+ } \
} while(0)
-#endif
-
-#endif /* HEADER_CURL_SELECT_H */
+#endif
+
+#endif /* HEADER_CURL_SELECT_H */
diff --git a/contrib/libs/curl/lib/sendf.c b/contrib/libs/curl/lib/sendf.c
index 8b54c472cf..04cc725f5a 100644
--- a/contrib/libs/curl/lib/sendf.c
+++ b/contrib/libs/curl/lib/sendf.c
@@ -1,27 +1,27 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
@@ -32,108 +32,108 @@
#include <netinet/tcp.h>
#endif
-#include <curl/curl.h>
-
-#include "urldata.h"
-#include "sendf.h"
-#include "connect.h"
+#include <curl/curl.h>
+
+#include "urldata.h"
+#include "sendf.h"
+#include "connect.h"
#include "vtls/vtls.h"
#include "vssh/ssh.h"
#include "easyif.h"
-#include "multiif.h"
-#include "non-ascii.h"
+#include "multiif.h"
+#include "non-ascii.h"
#include "strerror.h"
#include "select.h"
#include "strdup.h"
#include "http2.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-#ifdef CURL_DO_LINEEND_CONV
-/*
- * convert_lineends() changes CRLF (\r\n) end-of-line markers to a single LF
- * (\n), with special processing for CRLF sequences that are split between two
- * blocks of data. Remaining, bare CRs are changed to LFs. The possibly new
- * size of the data is returned.
- */
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#ifdef CURL_DO_LINEEND_CONV
+/*
+ * convert_lineends() changes CRLF (\r\n) end-of-line markers to a single LF
+ * (\n), with special processing for CRLF sequences that are split between two
+ * blocks of data. Remaining, bare CRs are changed to LFs. The possibly new
+ * size of the data is returned.
+ */
static size_t convert_lineends(struct Curl_easy *data,
- char *startPtr, size_t size)
-{
- char *inPtr, *outPtr;
-
- /* sanity check */
- if((startPtr == NULL) || (size < 1)) {
+ char *startPtr, size_t size)
+{
+ char *inPtr, *outPtr;
+
+ /* sanity check */
+ if((startPtr == NULL) || (size < 1)) {
return size;
- }
-
- if(data->state.prev_block_had_trailing_cr) {
- /* The previous block of incoming data
- had a trailing CR, which was turned into a LF. */
- if(*startPtr == '\n') {
- /* This block of incoming data starts with the
- previous block's LF so get rid of it */
+ }
+
+ if(data->state.prev_block_had_trailing_cr) {
+ /* The previous block of incoming data
+ had a trailing CR, which was turned into a LF. */
+ if(*startPtr == '\n') {
+ /* This block of incoming data starts with the
+ previous block's LF so get rid of it */
memmove(startPtr, startPtr + 1, size-1);
- size--;
- /* and it wasn't a bare CR but a CRLF conversion instead */
- data->state.crlf_conversions++;
- }
- data->state.prev_block_had_trailing_cr = FALSE; /* reset the flag */
- }
-
- /* find 1st CR, if any */
- inPtr = outPtr = memchr(startPtr, '\r', size);
- if(inPtr) {
- /* at least one CR, now look for CRLF */
+ size--;
+ /* and it wasn't a bare CR but a CRLF conversion instead */
+ data->state.crlf_conversions++;
+ }
+ data->state.prev_block_had_trailing_cr = FALSE; /* reset the flag */
+ }
+
+ /* find 1st CR, if any */
+ inPtr = outPtr = memchr(startPtr, '\r', size);
+ if(inPtr) {
+ /* at least one CR, now look for CRLF */
while(inPtr < (startPtr + size-1)) {
- /* note that it's size-1, so we'll never look past the last byte */
- if(memcmp(inPtr, "\r\n", 2) == 0) {
- /* CRLF found, bump past the CR and copy the NL */
- inPtr++;
- *outPtr = *inPtr;
- /* keep track of how many CRLFs we converted */
- data->state.crlf_conversions++;
- }
- else {
- if(*inPtr == '\r') {
- /* lone CR, move LF instead */
- *outPtr = '\n';
- }
- else {
- /* not a CRLF nor a CR, just copy whatever it is */
- *outPtr = *inPtr;
- }
- }
- outPtr++;
- inPtr++;
- } /* end of while loop */
-
+ /* note that it's size-1, so we'll never look past the last byte */
+ if(memcmp(inPtr, "\r\n", 2) == 0) {
+ /* CRLF found, bump past the CR and copy the NL */
+ inPtr++;
+ *outPtr = *inPtr;
+ /* keep track of how many CRLFs we converted */
+ data->state.crlf_conversions++;
+ }
+ else {
+ if(*inPtr == '\r') {
+ /* lone CR, move LF instead */
+ *outPtr = '\n';
+ }
+ else {
+ /* not a CRLF nor a CR, just copy whatever it is */
+ *outPtr = *inPtr;
+ }
+ }
+ outPtr++;
+ inPtr++;
+ } /* end of while loop */
+
if(inPtr < startPtr + size) {
- /* handle last byte */
- if(*inPtr == '\r') {
- /* deal with a CR at the end of the buffer */
- *outPtr = '\n'; /* copy a NL instead */
- /* note that a CRLF might be split across two blocks */
- data->state.prev_block_had_trailing_cr = TRUE;
- }
- else {
- /* copy last byte */
- *outPtr = *inPtr;
- }
- outPtr++;
- }
+ /* handle last byte */
+ if(*inPtr == '\r') {
+ /* deal with a CR at the end of the buffer */
+ *outPtr = '\n'; /* copy a NL instead */
+ /* note that a CRLF might be split across two blocks */
+ data->state.prev_block_had_trailing_cr = TRUE;
+ }
+ else {
+ /* copy last byte */
+ *outPtr = *inPtr;
+ }
+ outPtr++;
+ }
if(outPtr < startPtr + size)
- /* tidy up by null terminating the now shorter data */
- *outPtr = '\0';
-
+ /* tidy up by null terminating the now shorter data */
+ *outPtr = '\0';
+
return (outPtr - startPtr);
- }
+ }
return size;
-}
-#endif /* CURL_DO_LINEEND_CONV */
-
+}
+#endif /* CURL_DO_LINEEND_CONV */
+
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex)
{
@@ -234,15 +234,15 @@ bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex)
#define get_pre_recved(c,n,b,l) 0
#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
-/* Curl_infof() is for info message along the way */
-
+/* Curl_infof() is for info message along the way */
+
void Curl_infof(struct Curl_easy *data, const char *fmt, ...)
-{
- if(data && data->set.verbose) {
- va_list ap;
- size_t len;
- char print_buffer[2048 + 1];
- va_start(ap, fmt);
+{
+ if(data && data->set.verbose) {
+ va_list ap;
+ size_t len;
+ char print_buffer[2048 + 1];
+ va_start(ap, fmt);
len = mvsnprintf(print_buffer, sizeof(print_buffer), fmt, ap);
/*
* Indicate truncation of the input by replacing the last 3 characters
@@ -255,18 +255,18 @@ void Curl_infof(struct Curl_easy *data, const char *fmt, ...)
else
msnprintf(print_buffer + (sizeof(print_buffer) - 4), 4, "...");
}
- va_end(ap);
- len = strlen(print_buffer);
+ va_end(ap);
+ len = strlen(print_buffer);
Curl_debug(data, CURLINFO_TEXT, print_buffer, len);
- }
-}
-
-/* Curl_failf() is for messages stating why we failed.
- * The message SHALL NOT include any LF or CR.
- */
-
+ }
+}
+
+/* Curl_failf() is for messages stating why we failed.
+ * The message SHALL NOT include any LF or CR.
+ */
+
void Curl_failf(struct Curl_easy *data, const char *fmt, ...)
-{
+{
if(data->set.verbose || data->set.errorbuffer) {
va_list ap;
size_t len;
@@ -274,61 +274,61 @@ void Curl_failf(struct Curl_easy *data, const char *fmt, ...)
va_start(ap, fmt);
(void)mvsnprintf(error, CURL_ERROR_SIZE, fmt, ap);
len = strlen(error);
-
+
if(data->set.errorbuffer && !data->state.errorbuf) {
strcpy(data->set.errorbuffer, error);
data->state.errorbuf = TRUE; /* wrote error string */
- }
+ }
error[len++] = '\n';
Curl_debug(data, CURLINFO_TEXT, error, len);
va_end(ap);
- }
-}
-
-/*
- * Curl_write() is an internal write function that sends data to the
- * server. Works with plain sockets, SCP, SSL or kerberos.
- *
- * If the write would block (CURLE_AGAIN), we return CURLE_OK and
- * (*written == 0). Otherwise we return regular CURLcode value.
- */
-CURLcode Curl_write(struct connectdata *conn,
- curl_socket_t sockfd,
- const void *mem,
- size_t len,
- ssize_t *written)
-{
- ssize_t bytes_written;
+ }
+}
+
+/*
+ * Curl_write() is an internal write function that sends data to the
+ * server. Works with plain sockets, SCP, SSL or kerberos.
+ *
+ * If the write would block (CURLE_AGAIN), we return CURLE_OK and
+ * (*written == 0). Otherwise we return regular CURLcode value.
+ */
+CURLcode Curl_write(struct connectdata *conn,
+ curl_socket_t sockfd,
+ const void *mem,
+ size_t len,
+ ssize_t *written)
+{
+ ssize_t bytes_written;
CURLcode result = CURLE_OK;
- int num = (sockfd == conn->sock[SECONDARYSOCKET]);
-
+ int num = (sockfd == conn->sock[SECONDARYSOCKET]);
+
bytes_written = conn->send[num](conn, num, mem, len, &result);
-
- *written = bytes_written;
- if(bytes_written >= 0)
- /* we completely ignore the curlcode value when subzero is not returned */
- return CURLE_OK;
-
- /* handle CURLE_AGAIN or a send failure */
+
+ *written = bytes_written;
+ if(bytes_written >= 0)
+ /* we completely ignore the curlcode value when subzero is not returned */
+ return CURLE_OK;
+
+ /* handle CURLE_AGAIN or a send failure */
switch(result) {
- case CURLE_AGAIN:
- *written = 0;
- return CURLE_OK;
-
- case CURLE_OK:
- /* general send failure */
- return CURLE_SEND_ERROR;
-
- default:
- /* we got a specific curlcode, forward it */
+ case CURLE_AGAIN:
+ *written = 0;
+ return CURLE_OK;
+
+ case CURLE_OK:
+ /* general send failure */
+ return CURLE_SEND_ERROR;
+
+ default:
+ /* we got a specific curlcode, forward it */
return result;
- }
-}
-
-ssize_t Curl_send_plain(struct connectdata *conn, int num,
- const void *mem, size_t len, CURLcode *code)
-{
- curl_socket_t sockfd = conn->sock[num];
+ }
+}
+
+ssize_t Curl_send_plain(struct connectdata *conn, int num,
+ const void *mem, size_t len, CURLcode *code)
+{
+ curl_socket_t sockfd = conn->sock[num];
ssize_t bytes_written;
/* WinSock will destroy unread received data if send() is
failed.
@@ -339,7 +339,7 @@ ssize_t Curl_send_plain(struct connectdata *conn, int num,
*code = CURLE_OUT_OF_MEMORY;
return -1;
}
-
+
#if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
if(conn->bits.tcp_fastopen) {
bytes_written = sendto(sockfd, mem, len, MSG_FASTOPEN,
@@ -350,63 +350,63 @@ ssize_t Curl_send_plain(struct connectdata *conn, int num,
#endif
bytes_written = swrite(sockfd, mem, len);
- *code = CURLE_OK;
- if(-1 == bytes_written) {
- int err = SOCKERRNO;
-
- if(
-#ifdef WSAEWOULDBLOCK
- /* This is how Windows does it */
- (WSAEWOULDBLOCK == err)
-#else
- /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
+ *code = CURLE_OK;
+ if(-1 == bytes_written) {
+ int err = SOCKERRNO;
+
+ if(
+#ifdef WSAEWOULDBLOCK
+ /* This is how Windows does it */
+ (WSAEWOULDBLOCK == err)
+#else
+ /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
due to its inability to send off data without blocking. We therefore
- treat both error codes the same here */
+ treat both error codes the same here */
(EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err) ||
(EINPROGRESS == err)
-#endif
- ) {
- /* this is just a case of EWOULDBLOCK */
+#endif
+ ) {
+ /* this is just a case of EWOULDBLOCK */
bytes_written = 0;
- *code = CURLE_AGAIN;
- }
- else {
+ *code = CURLE_AGAIN;
+ }
+ else {
char buffer[STRERROR_LEN];
- failf(conn->data, "Send failure: %s",
+ failf(conn->data, "Send failure: %s",
Curl_strerror(err, buffer, sizeof(buffer)));
- conn->data->state.os_errno = err;
- *code = CURLE_SEND_ERROR;
- }
- }
- return bytes_written;
-}
-
-/*
- * Curl_write_plain() is an internal write function that sends data to the
- * server using plain sockets only. Otherwise meant to have the exact same
- * proto as Curl_write()
- */
-CURLcode Curl_write_plain(struct connectdata *conn,
- curl_socket_t sockfd,
- const void *mem,
- size_t len,
- ssize_t *written)
-{
- ssize_t bytes_written;
+ conn->data->state.os_errno = err;
+ *code = CURLE_SEND_ERROR;
+ }
+ }
+ return bytes_written;
+}
+
+/*
+ * Curl_write_plain() is an internal write function that sends data to the
+ * server using plain sockets only. Otherwise meant to have the exact same
+ * proto as Curl_write()
+ */
+CURLcode Curl_write_plain(struct connectdata *conn,
+ curl_socket_t sockfd,
+ const void *mem,
+ size_t len,
+ ssize_t *written)
+{
+ ssize_t bytes_written;
CURLcode result;
- int num = (sockfd == conn->sock[SECONDARYSOCKET]);
-
+ int num = (sockfd == conn->sock[SECONDARYSOCKET]);
+
bytes_written = Curl_send_plain(conn, num, mem, len, &result);
-
- *written = bytes_written;
-
+
+ *written = bytes_written;
+
return result;
-}
-
-ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf,
- size_t len, CURLcode *code)
-{
- curl_socket_t sockfd = conn->sock[num];
+}
+
+ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf,
+ size_t len, CURLcode *code)
+{
+ curl_socket_t sockfd = conn->sock[num];
ssize_t nread;
/* Check and return data that already received and storied in internal
intermediate buffer */
@@ -415,51 +415,51 @@ ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf,
*code = CURLE_OK;
return nread;
}
-
+
nread = sread(sockfd, buf, len);
- *code = CURLE_OK;
- if(-1 == nread) {
- int err = SOCKERRNO;
-
- if(
-#ifdef WSAEWOULDBLOCK
- /* This is how Windows does it */
- (WSAEWOULDBLOCK == err)
-#else
- /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
+ *code = CURLE_OK;
+ if(-1 == nread) {
+ int err = SOCKERRNO;
+
+ if(
+#ifdef WSAEWOULDBLOCK
+ /* This is how Windows does it */
+ (WSAEWOULDBLOCK == err)
+#else
+ /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
due to its inability to send off data without blocking. We therefore
- treat both error codes the same here */
- (EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err)
-#endif
- ) {
- /* this is just a case of EWOULDBLOCK */
- *code = CURLE_AGAIN;
- }
- else {
+ treat both error codes the same here */
+ (EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err)
+#endif
+ ) {
+ /* this is just a case of EWOULDBLOCK */
+ *code = CURLE_AGAIN;
+ }
+ else {
char buffer[STRERROR_LEN];
- failf(conn->data, "Recv failure: %s",
+ failf(conn->data, "Recv failure: %s",
Curl_strerror(err, buffer, sizeof(buffer)));
- conn->data->state.os_errno = err;
- *code = CURLE_RECV_ERROR;
- }
- }
- return nread;
-}
-
+ conn->data->state.os_errno = err;
+ *code = CURLE_RECV_ERROR;
+ }
+ }
+ return nread;
+}
+
static CURLcode pausewrite(struct Curl_easy *data,
- int type, /* what type of data */
- const char *ptr,
- size_t len)
-{
- /* signalled to pause sending on this connection, but since we have data
- we want to send we need to dup it to save a copy for when the sending
- is again enabled */
- struct SingleRequest *k = &data->req;
+ int type, /* what type of data */
+ const char *ptr,
+ size_t len)
+{
+ /* signalled to pause sending on this connection, but since we have data
+ we want to send we need to dup it to save a copy for when the sending
+ is again enabled */
+ struct SingleRequest *k = &data->req;
struct UrlState *s = &data->state;
unsigned int i;
bool newtype = TRUE;
-
+
/* If this transfers over HTTP/2, pause the stream! */
Curl_http2_stream_pause(data, TRUE);
@@ -475,7 +475,7 @@ static CURLcode pausewrite(struct Curl_easy *data,
}
else
i = 0;
-
+
if(newtype) {
/* store this information in the state struct for later use */
Curl_dyn_init(&s->tempwrite[i].b, DYN_PAUSE_BUFFER);
@@ -488,36 +488,36 @@ static CURLcode pausewrite(struct Curl_easy *data,
if(Curl_dyn_addn(&s->tempwrite[i].b, (unsigned char *)ptr, len))
return CURLE_OUT_OF_MEMORY;
- /* mark the connection as RECV paused */
- k->keepon |= KEEP_RECV_PAUSE;
-
- return CURLE_OK;
-}
-
-
+ /* mark the connection as RECV paused */
+ k->keepon |= KEEP_RECV_PAUSE;
+
+ return CURLE_OK;
+}
+
+
/* chop_write() writes chunks of data not larger than CURL_MAX_WRITE_SIZE via
* client write callback(s) and takes care of pause requests from the
* callbacks.
- */
+ */
static CURLcode chop_write(struct connectdata *conn,
- int type,
+ int type,
char *optr,
size_t olen)
-{
+{
struct Curl_easy *data = conn->data;
curl_write_callback writeheader = NULL;
curl_write_callback writebody = NULL;
char *ptr = optr;
size_t len = olen;
-
+
if(!len)
return CURLE_OK;
-
+
/* If reading is paused, append this data to the already held data for this
type. */
if(data->req.keepon & KEEP_RECV_PAUSE)
return pausewrite(data, type, ptr, len);
-
+
/* Determine the callback(s) to use. */
if(type & CLIENTWRITE_BODY)
writebody = data->set.fwrite_func;
@@ -530,17 +530,17 @@ static CURLcode chop_write(struct connectdata *conn,
writeheader =
data->set.fwrite_header? data->set.fwrite_header: data->set.fwrite_func;
}
-
+
/* Chop data, write chunks. */
while(len) {
size_t chunklen = len <= CURL_MAX_WRITE_SIZE? len: CURL_MAX_WRITE_SIZE;
-
+
if(writebody) {
size_t wrote;
Curl_set_in_callback(data, true);
wrote = writebody(ptr, 1, chunklen, data->set.out);
Curl_set_in_callback(data, false);
-
+
if(CURL_WRITEFUNC_PAUSE == wrote) {
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* Protocols that work without network cannot be paused. This is
@@ -555,12 +555,12 @@ static CURLcode chop_write(struct connectdata *conn,
failf(data, "Failure writing output to destination");
return CURLE_WRITE_ERROR;
}
- }
-
+ }
+
ptr += chunklen;
len -= chunklen;
- }
-
+ }
+
if(writeheader) {
size_t wrote;
ptr = optr;
@@ -568,22 +568,22 @@ static CURLcode chop_write(struct connectdata *conn,
Curl_set_in_callback(data, true);
wrote = writeheader(ptr, 1, len, data->set.writeheader);
Curl_set_in_callback(data, false);
-
- if(CURL_WRITEFUNC_PAUSE == wrote)
- /* here we pass in the HEADER bit only since if this was body as well
+
+ if(CURL_WRITEFUNC_PAUSE == wrote)
+ /* here we pass in the HEADER bit only since if this was body as well
then it was passed already and clearly that didn't trigger the
pause, so this is saved for later with the HEADER bit only */
- return pausewrite(data, CLIENTWRITE_HEADER, ptr, len);
-
- if(wrote != len) {
+ return pausewrite(data, CLIENTWRITE_HEADER, ptr, len);
+
+ if(wrote != len) {
failf(data, "Failed writing header");
- return CURLE_WRITE_ERROR;
- }
- }
-
- return CURLE_OK;
-}
-
+ return CURLE_WRITE_ERROR;
+ }
+ }
+
+ return CURLE_OK;
+}
+
/* Curl_client_write() sends data to the write callback(s)
@@ -625,82 +625,82 @@ CURLcode Curl_client_write(struct connectdata *conn,
return chop_write(conn, type, ptr, len);
}
-CURLcode Curl_read_plain(curl_socket_t sockfd,
- char *buf,
- size_t bytesfromsocket,
- ssize_t *n)
-{
- ssize_t nread = sread(sockfd, buf, bytesfromsocket);
-
- if(-1 == nread) {
+CURLcode Curl_read_plain(curl_socket_t sockfd,
+ char *buf,
+ size_t bytesfromsocket,
+ ssize_t *n)
+{
+ ssize_t nread = sread(sockfd, buf, bytesfromsocket);
+
+ if(-1 == nread) {
const int err = SOCKERRNO;
const bool return_error =
-#ifdef USE_WINSOCK
+#ifdef USE_WINSOCK
WSAEWOULDBLOCK == err
-#else
+#else
EWOULDBLOCK == err || EAGAIN == err || EINTR == err
-#endif
+#endif
;
*n = 0; /* no data returned */
if(return_error)
- return CURLE_AGAIN;
+ return CURLE_AGAIN;
return CURLE_RECV_ERROR;
- }
-
- *n = nread;
- return CURLE_OK;
-}
-
-/*
- * Internal read-from-socket function. This is meant to deal with plain
- * sockets, SSL sockets and kerberos sockets.
- *
- * Returns a regular CURLcode value.
- */
-CURLcode Curl_read(struct connectdata *conn, /* connection data */
- curl_socket_t sockfd, /* read from this socket */
- char *buf, /* store read data here */
- size_t sizerequested, /* max amount to read */
- ssize_t *n) /* amount bytes read */
-{
+ }
+
+ *n = nread;
+ return CURLE_OK;
+}
+
+/*
+ * Internal read-from-socket function. This is meant to deal with plain
+ * sockets, SSL sockets and kerberos sockets.
+ *
+ * Returns a regular CURLcode value.
+ */
+CURLcode Curl_read(struct connectdata *conn, /* connection data */
+ curl_socket_t sockfd, /* read from this socket */
+ char *buf, /* store read data here */
+ size_t sizerequested, /* max amount to read */
+ ssize_t *n) /* amount bytes read */
+{
CURLcode result = CURLE_RECV_ERROR;
- ssize_t nread = 0;
- size_t bytesfromsocket = 0;
- char *buffertofill = NULL;
+ ssize_t nread = 0;
+ size_t bytesfromsocket = 0;
+ char *buffertofill = NULL;
struct Curl_easy *data = conn->data;
-
- /* Set 'num' to 0 or 1, depending on which socket that has been sent here.
- If it is the second socket, we set num to 1. Otherwise to 0. This lets
- us use the correct ssl handle. */
- int num = (sockfd == conn->sock[SECONDARYSOCKET]);
-
+
+ /* Set 'num' to 0 or 1, depending on which socket that has been sent here.
+ If it is the second socket, we set num to 1. Otherwise to 0. This lets
+ us use the correct ssl handle. */
+ int num = (sockfd == conn->sock[SECONDARYSOCKET]);
+
*n = 0; /* reset amount to zero */
-
+
bytesfromsocket = CURLMIN(sizerequested, (size_t)data->set.buffer_size);
buffertofill = buf;
-
+
nread = conn->recv[num](conn, num, buffertofill, bytesfromsocket, &result);
- if(nread < 0)
+ if(nread < 0)
return result;
-
- *n += nread;
-
- return CURLE_OK;
-}
-
-/* return 0 on success */
+
+ *n += nread;
+
+ return CURLE_OK;
+}
+
+/* return 0 on success */
int Curl_debug(struct Curl_easy *data, curl_infotype type,
char *ptr, size_t size)
-{
+{
int rc = 0;
if(data->set.verbose) {
static const char s_infotype[CURLINFO_END][3] = {
"* ", "< ", "> ", "{ ", "} ", "{ ", "} " };
-
-#ifdef CURL_DOES_CONVERSIONS
+
+#ifdef CURL_DOES_CONVERSIONS
char *buf = NULL;
size_t conv_size = 0;
-
+
switch(type) {
case CURLINFO_HEADER_OUT:
buf = Curl_memdup(ptr, size);
@@ -720,8 +720,8 @@ int Curl_debug(struct Curl_easy *data, curl_infotype type,
conv_size = i + 4;
break;
}
- }
- }
+ }
+ }
Curl_convert_from_network(data, buf, conv_size);
/* Curl_convert_from_network calls failf if unsuccessful */
@@ -731,9 +731,9 @@ int Curl_debug(struct Curl_easy *data, curl_infotype type,
default:
/* leave everything else as-is */
break;
- }
-#endif /* CURL_DOES_CONVERSIONS */
-
+ }
+#endif /* CURL_DOES_CONVERSIONS */
+
if(data->set.fdebug) {
Curl_set_in_callback(data, true);
rc = (*data->set.fdebug)(data, type, ptr, size, data->set.debugdata);
@@ -746,7 +746,7 @@ int Curl_debug(struct Curl_easy *data, curl_infotype type,
case CURLINFO_HEADER_IN:
fwrite(s_infotype[type], 2, 1, data->set.err);
fwrite(ptr, size, 1, data->set.err);
-#ifdef CURL_DOES_CONVERSIONS
+#ifdef CURL_DOES_CONVERSIONS
if(size != conv_size) {
/* we had untranslated data so we need an explicit newline */
fwrite("\n", 1, 1, data->set.err);
@@ -756,10 +756,10 @@ int Curl_debug(struct Curl_easy *data, curl_infotype type,
default: /* nada */
break;
}
- }
+ }
#ifdef CURL_DOES_CONVERSIONS
free(buf);
#endif
}
- return rc;
-}
+ return rc;
+}
diff --git a/contrib/libs/curl/lib/sendf.h b/contrib/libs/curl/lib/sendf.h
index c2c7d77172..c7e67c7451 100644
--- a/contrib/libs/curl/lib/sendf.h
+++ b/contrib/libs/curl/lib/sendf.h
@@ -1,89 +1,89 @@
-#ifndef HEADER_CURL_SENDF_H
-#define HEADER_CURL_SENDF_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SENDF_H
+#define HEADER_CURL_SENDF_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
void Curl_infof(struct Curl_easy *, const char *fmt, ...);
void Curl_failf(struct Curl_easy *, const char *fmt, ...);
-
-#if defined(CURL_DISABLE_VERBOSE_STRINGS)
-
-#if defined(HAVE_VARIADIC_MACROS_C99)
-#define infof(...) Curl_nop_stmt
-#elif defined(HAVE_VARIADIC_MACROS_GCC)
-#define infof(x...) Curl_nop_stmt
-#else
+
+#if defined(CURL_DISABLE_VERBOSE_STRINGS)
+
+#if defined(HAVE_VARIADIC_MACROS_C99)
+#define infof(...) Curl_nop_stmt
+#elif defined(HAVE_VARIADIC_MACROS_GCC)
+#define infof(x...) Curl_nop_stmt
+#else
#error "missing VARIADIC macro define, fix and rebuild!"
-#endif
-
-#else /* CURL_DISABLE_VERBOSE_STRINGS */
-
-#define infof Curl_infof
-
-#endif /* CURL_DISABLE_VERBOSE_STRINGS */
-
-#define failf Curl_failf
-
-#define CLIENTWRITE_BODY (1<<0)
-#define CLIENTWRITE_HEADER (1<<1)
-#define CLIENTWRITE_BOTH (CLIENTWRITE_BODY|CLIENTWRITE_HEADER)
-
-CURLcode Curl_client_write(struct connectdata *conn, int type, char *ptr,
+#endif
+
+#else /* CURL_DISABLE_VERBOSE_STRINGS */
+
+#define infof Curl_infof
+
+#endif /* CURL_DISABLE_VERBOSE_STRINGS */
+
+#define failf Curl_failf
+
+#define CLIENTWRITE_BODY (1<<0)
+#define CLIENTWRITE_HEADER (1<<1)
+#define CLIENTWRITE_BOTH (CLIENTWRITE_BODY|CLIENTWRITE_HEADER)
+
+CURLcode Curl_client_write(struct connectdata *conn, int type, char *ptr,
size_t len) WARN_UNUSED_RESULT;
-
+
bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex);
-/* internal read-function, does plain socket only */
-CURLcode Curl_read_plain(curl_socket_t sockfd,
- char *buf,
- size_t bytesfromsocket,
- ssize_t *n);
-
-ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf,
- size_t len, CURLcode *code);
-ssize_t Curl_send_plain(struct connectdata *conn, int num,
- const void *mem, size_t len, CURLcode *code);
-
-/* internal read-function, does plain socket, SSL and krb4 */
-CURLcode Curl_read(struct connectdata *conn, curl_socket_t sockfd,
- char *buf, size_t buffersize,
- ssize_t *n);
-/* internal write-function, does plain socket, SSL, SCP, SFTP and krb4 */
-CURLcode Curl_write(struct connectdata *conn,
- curl_socket_t sockfd,
- const void *mem, size_t len,
- ssize_t *written);
-
-/* internal write-function, does plain sockets ONLY */
-CURLcode Curl_write_plain(struct connectdata *conn,
- curl_socket_t sockfd,
- const void *mem, size_t len,
- ssize_t *written);
-
-/* the function used to output verbose information */
+/* internal read-function, does plain socket only */
+CURLcode Curl_read_plain(curl_socket_t sockfd,
+ char *buf,
+ size_t bytesfromsocket,
+ ssize_t *n);
+
+ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf,
+ size_t len, CURLcode *code);
+ssize_t Curl_send_plain(struct connectdata *conn, int num,
+ const void *mem, size_t len, CURLcode *code);
+
+/* internal read-function, does plain socket, SSL and krb4 */
+CURLcode Curl_read(struct connectdata *conn, curl_socket_t sockfd,
+ char *buf, size_t buffersize,
+ ssize_t *n);
+/* internal write-function, does plain socket, SSL, SCP, SFTP and krb4 */
+CURLcode Curl_write(struct connectdata *conn,
+ curl_socket_t sockfd,
+ const void *mem, size_t len,
+ ssize_t *written);
+
+/* internal write-function, does plain sockets ONLY */
+CURLcode Curl_write_plain(struct connectdata *conn,
+ curl_socket_t sockfd,
+ const void *mem, size_t len,
+ ssize_t *written);
+
+/* the function used to output verbose information */
int Curl_debug(struct Curl_easy *data, curl_infotype type,
char *ptr, size_t size);
-
-
-#endif /* HEADER_CURL_SENDF_H */
+
+
+#endif /* HEADER_CURL_SENDF_H */
diff --git a/contrib/libs/curl/lib/setup-os400.h b/contrib/libs/curl/lib/setup-os400.h
index aca827e292..8c97371e4d 100644
--- a/contrib/libs/curl/lib/setup-os400.h
+++ b/contrib/libs/curl/lib/setup-os400.h
@@ -1,205 +1,205 @@
-#ifndef HEADER_CURL_SETUP_OS400_H
-#define HEADER_CURL_SETUP_OS400_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SETUP_OS400_H
+#define HEADER_CURL_SETUP_OS400_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-
-/* OS/400 netdb.h does not define NI_MAXHOST. */
-#define NI_MAXHOST 1025
-
-/* OS/400 netdb.h does not define NI_MAXSERV. */
-#define NI_MAXSERV 32
-
-/* No OS/400 header file defines u_int32_t. */
-typedef unsigned long u_int32_t;
-
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+
+/* OS/400 netdb.h does not define NI_MAXHOST. */
+#define NI_MAXHOST 1025
+
+/* OS/400 netdb.h does not define NI_MAXSERV. */
+#define NI_MAXSERV 32
+
+/* No OS/400 header file defines u_int32_t. */
+typedef unsigned long u_int32_t;
+
+
/* System API wrapper prototypes & definitions to support ASCII parameters. */
-
-#include <sys/socket.h>
-#include <netdb.h>
-#include <gskssl.h>
-#include <qsoasync.h>
-#include <gssapi.h>
-
+
+#include <sys/socket.h>
+#include <netdb.h>
+#include <gskssl.h>
+#include <qsoasync.h>
+#include <gssapi.h>
+
extern int Curl_getaddrinfo_a(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct addrinfo **res);
-#define getaddrinfo Curl_getaddrinfo_a
-
-
+#define getaddrinfo Curl_getaddrinfo_a
+
+
extern int Curl_getnameinfo_a(const struct sockaddr *sa,
curl_socklen_t salen,
char *nodename, curl_socklen_t nodenamelen,
char *servname, curl_socklen_t servnamelen,
int flags);
-#define getnameinfo Curl_getnameinfo_a
-
-
-/* GSKit wrappers. */
-
-extern int Curl_gsk_environment_open(gsk_handle * my_env_handle);
-#define gsk_environment_open Curl_gsk_environment_open
-
-extern int Curl_gsk_secure_soc_open(gsk_handle my_env_handle,
- gsk_handle * my_session_handle);
-#define gsk_secure_soc_open Curl_gsk_secure_soc_open
-
-extern int Curl_gsk_environment_close(gsk_handle * my_env_handle);
-#define gsk_environment_close Curl_gsk_environment_close
-
-extern int Curl_gsk_secure_soc_close(gsk_handle * my_session_handle);
-#define gsk_secure_soc_close Curl_gsk_secure_soc_close
-
-extern int Curl_gsk_environment_init(gsk_handle my_env_handle);
-#define gsk_environment_init Curl_gsk_environment_init
-
-extern int Curl_gsk_secure_soc_init(gsk_handle my_session_handle);
-#define gsk_secure_soc_init Curl_gsk_secure_soc_init
-
-extern int Curl_gsk_attribute_set_buffer_a(gsk_handle my_gsk_handle,
- GSK_BUF_ID bufID,
+#define getnameinfo Curl_getnameinfo_a
+
+
+/* GSKit wrappers. */
+
+extern int Curl_gsk_environment_open(gsk_handle * my_env_handle);
+#define gsk_environment_open Curl_gsk_environment_open
+
+extern int Curl_gsk_secure_soc_open(gsk_handle my_env_handle,
+ gsk_handle * my_session_handle);
+#define gsk_secure_soc_open Curl_gsk_secure_soc_open
+
+extern int Curl_gsk_environment_close(gsk_handle * my_env_handle);
+#define gsk_environment_close Curl_gsk_environment_close
+
+extern int Curl_gsk_secure_soc_close(gsk_handle * my_session_handle);
+#define gsk_secure_soc_close Curl_gsk_secure_soc_close
+
+extern int Curl_gsk_environment_init(gsk_handle my_env_handle);
+#define gsk_environment_init Curl_gsk_environment_init
+
+extern int Curl_gsk_secure_soc_init(gsk_handle my_session_handle);
+#define gsk_secure_soc_init Curl_gsk_secure_soc_init
+
+extern int Curl_gsk_attribute_set_buffer_a(gsk_handle my_gsk_handle,
+ GSK_BUF_ID bufID,
const char *buffer,
- int bufSize);
-#define gsk_attribute_set_buffer Curl_gsk_attribute_set_buffer_a
-
-extern int Curl_gsk_attribute_set_enum(gsk_handle my_gsk_handle,
- GSK_ENUM_ID enumID,
- GSK_ENUM_VALUE enumValue);
-#define gsk_attribute_set_enum Curl_gsk_attribute_set_enum
-
-extern int Curl_gsk_attribute_set_numeric_value(gsk_handle my_gsk_handle,
- GSK_NUM_ID numID,
- int numValue);
-#define gsk_attribute_set_numeric_value Curl_gsk_attribute_set_numeric_value
-
-extern int Curl_gsk_attribute_set_callback(gsk_handle my_gsk_handle,
- GSK_CALLBACK_ID callBackID,
+ int bufSize);
+#define gsk_attribute_set_buffer Curl_gsk_attribute_set_buffer_a
+
+extern int Curl_gsk_attribute_set_enum(gsk_handle my_gsk_handle,
+ GSK_ENUM_ID enumID,
+ GSK_ENUM_VALUE enumValue);
+#define gsk_attribute_set_enum Curl_gsk_attribute_set_enum
+
+extern int Curl_gsk_attribute_set_numeric_value(gsk_handle my_gsk_handle,
+ GSK_NUM_ID numID,
+ int numValue);
+#define gsk_attribute_set_numeric_value Curl_gsk_attribute_set_numeric_value
+
+extern int Curl_gsk_attribute_set_callback(gsk_handle my_gsk_handle,
+ GSK_CALLBACK_ID callBackID,
void *callBackAreaPtr);
-#define gsk_attribute_set_callback Curl_gsk_attribute_set_callback
-
-extern int Curl_gsk_attribute_get_buffer_a(gsk_handle my_gsk_handle,
- GSK_BUF_ID bufID,
+#define gsk_attribute_set_callback Curl_gsk_attribute_set_callback
+
+extern int Curl_gsk_attribute_get_buffer_a(gsk_handle my_gsk_handle,
+ GSK_BUF_ID bufID,
const char **buffer,
int *bufSize);
-#define gsk_attribute_get_buffer Curl_gsk_attribute_get_buffer_a
-
-extern int Curl_gsk_attribute_get_enum(gsk_handle my_gsk_handle,
- GSK_ENUM_ID enumID,
+#define gsk_attribute_get_buffer Curl_gsk_attribute_get_buffer_a
+
+extern int Curl_gsk_attribute_get_enum(gsk_handle my_gsk_handle,
+ GSK_ENUM_ID enumID,
GSK_ENUM_VALUE *enumValue);
-#define gsk_attribute_get_enum Curl_gsk_attribute_get_enum
-
-extern int Curl_gsk_attribute_get_numeric_value(gsk_handle my_gsk_handle,
- GSK_NUM_ID numID,
+#define gsk_attribute_get_enum Curl_gsk_attribute_get_enum
+
+extern int Curl_gsk_attribute_get_numeric_value(gsk_handle my_gsk_handle,
+ GSK_NUM_ID numID,
int *numValue);
-#define gsk_attribute_get_numeric_value Curl_gsk_attribute_get_numeric_value
-
-extern int Curl_gsk_attribute_get_cert_info(gsk_handle my_gsk_handle,
- GSK_CERT_ID certID,
+#define gsk_attribute_get_numeric_value Curl_gsk_attribute_get_numeric_value
+
+extern int Curl_gsk_attribute_get_cert_info(gsk_handle my_gsk_handle,
+ GSK_CERT_ID certID,
const gsk_cert_data_elem **certDataElem,
int *certDataElementCount);
-#define gsk_attribute_get_cert_info Curl_gsk_attribute_get_cert_info
-
-extern int Curl_gsk_secure_soc_misc(gsk_handle my_session_handle,
- GSK_MISC_ID miscID);
-#define gsk_secure_soc_misc Curl_gsk_secure_soc_misc
-
-extern int Curl_gsk_secure_soc_read(gsk_handle my_session_handle,
+#define gsk_attribute_get_cert_info Curl_gsk_attribute_get_cert_info
+
+extern int Curl_gsk_secure_soc_misc(gsk_handle my_session_handle,
+ GSK_MISC_ID miscID);
+#define gsk_secure_soc_misc Curl_gsk_secure_soc_misc
+
+extern int Curl_gsk_secure_soc_read(gsk_handle my_session_handle,
char *readBuffer,
int readBufSize, int *amtRead);
-#define gsk_secure_soc_read Curl_gsk_secure_soc_read
-
-extern int Curl_gsk_secure_soc_write(gsk_handle my_session_handle,
+#define gsk_secure_soc_read Curl_gsk_secure_soc_read
+
+extern int Curl_gsk_secure_soc_write(gsk_handle my_session_handle,
char *writeBuffer,
int writeBufSize, int *amtWritten);
-#define gsk_secure_soc_write Curl_gsk_secure_soc_write
-
-extern const char * Curl_gsk_strerror_a(int gsk_return_value);
-#define gsk_strerror Curl_gsk_strerror_a
-
-extern int Curl_gsk_secure_soc_startInit(gsk_handle my_session_handle,
- int IOCompletionPort,
- Qso_OverlappedIO_t * communicationsArea);
-#define gsk_secure_soc_startInit Curl_gsk_secure_soc_startInit
-
-
-/* GSSAPI wrappers. */
-
-extern OM_uint32 Curl_gss_import_name_a(OM_uint32 * minor_status,
- gss_buffer_t in_name,
- gss_OID in_name_type,
- gss_name_t * out_name);
-#define gss_import_name Curl_gss_import_name_a
-
-
-extern OM_uint32 Curl_gss_display_status_a(OM_uint32 * minor_status,
- OM_uint32 status_value,
- int status_type, gss_OID mech_type,
- gss_msg_ctx_t * message_context,
- gss_buffer_t status_string);
-#define gss_display_status Curl_gss_display_status_a
-
-
-extern OM_uint32 Curl_gss_init_sec_context_a(OM_uint32 * minor_status,
- gss_cred_id_t cred_handle,
- gss_ctx_id_t * context_handle,
- gss_name_t target_name,
- gss_OID mech_type,
- gss_flags_t req_flags,
- OM_uint32 time_req,
- gss_channel_bindings_t
- input_chan_bindings,
- gss_buffer_t input_token,
- gss_OID * actual_mech_type,
- gss_buffer_t output_token,
- gss_flags_t * ret_flags,
- OM_uint32 * time_rec);
-#define gss_init_sec_context Curl_gss_init_sec_context_a
-
-
-extern OM_uint32 Curl_gss_delete_sec_context_a(OM_uint32 * minor_status,
- gss_ctx_id_t * context_handle,
- gss_buffer_t output_token);
-#define gss_delete_sec_context Curl_gss_delete_sec_context_a
-
-
-/* LDAP wrappers. */
-
-#define BerValue struct berval
-
-#define ldap_url_parse ldap_url_parse_utf8
-#define ldap_init Curl_ldap_init_a
-#define ldap_simple_bind_s Curl_ldap_simple_bind_s_a
-#define ldap_search_s Curl_ldap_search_s_a
-#define ldap_get_values_len Curl_ldap_get_values_len_a
-#define ldap_err2string Curl_ldap_err2string_a
-#define ldap_get_dn Curl_ldap_get_dn_a
-#define ldap_first_attribute Curl_ldap_first_attribute_a
-#define ldap_next_attribute Curl_ldap_next_attribute_a
-
-/* Some socket functions must be wrapped to process textual addresses
- like AF_UNIX. */
-
+#define gsk_secure_soc_write Curl_gsk_secure_soc_write
+
+extern const char * Curl_gsk_strerror_a(int gsk_return_value);
+#define gsk_strerror Curl_gsk_strerror_a
+
+extern int Curl_gsk_secure_soc_startInit(gsk_handle my_session_handle,
+ int IOCompletionPort,
+ Qso_OverlappedIO_t * communicationsArea);
+#define gsk_secure_soc_startInit Curl_gsk_secure_soc_startInit
+
+
+/* GSSAPI wrappers. */
+
+extern OM_uint32 Curl_gss_import_name_a(OM_uint32 * minor_status,
+ gss_buffer_t in_name,
+ gss_OID in_name_type,
+ gss_name_t * out_name);
+#define gss_import_name Curl_gss_import_name_a
+
+
+extern OM_uint32 Curl_gss_display_status_a(OM_uint32 * minor_status,
+ OM_uint32 status_value,
+ int status_type, gss_OID mech_type,
+ gss_msg_ctx_t * message_context,
+ gss_buffer_t status_string);
+#define gss_display_status Curl_gss_display_status_a
+
+
+extern OM_uint32 Curl_gss_init_sec_context_a(OM_uint32 * minor_status,
+ gss_cred_id_t cred_handle,
+ gss_ctx_id_t * context_handle,
+ gss_name_t target_name,
+ gss_OID mech_type,
+ gss_flags_t req_flags,
+ OM_uint32 time_req,
+ gss_channel_bindings_t
+ input_chan_bindings,
+ gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ gss_flags_t * ret_flags,
+ OM_uint32 * time_rec);
+#define gss_init_sec_context Curl_gss_init_sec_context_a
+
+
+extern OM_uint32 Curl_gss_delete_sec_context_a(OM_uint32 * minor_status,
+ gss_ctx_id_t * context_handle,
+ gss_buffer_t output_token);
+#define gss_delete_sec_context Curl_gss_delete_sec_context_a
+
+
+/* LDAP wrappers. */
+
+#define BerValue struct berval
+
+#define ldap_url_parse ldap_url_parse_utf8
+#define ldap_init Curl_ldap_init_a
+#define ldap_simple_bind_s Curl_ldap_simple_bind_s_a
+#define ldap_search_s Curl_ldap_search_s_a
+#define ldap_get_values_len Curl_ldap_get_values_len_a
+#define ldap_err2string Curl_ldap_err2string_a
+#define ldap_get_dn Curl_ldap_get_dn_a
+#define ldap_first_attribute Curl_ldap_first_attribute_a
+#define ldap_next_attribute Curl_ldap_next_attribute_a
+
+/* Some socket functions must be wrapped to process textual addresses
+ like AF_UNIX. */
+
extern int Curl_os400_connect(int sd, struct sockaddr *destaddr, int addrlen);
extern int Curl_os400_bind(int sd, struct sockaddr *localaddr, int addrlen);
extern int Curl_os400_sendto(int sd, char *buffer, int buflen, int flags,
@@ -208,14 +208,14 @@ extern int Curl_os400_recvfrom(int sd, char *buffer, int buflen, int flags,
struct sockaddr *fromaddr, int *addrlen);
extern int Curl_os400_getpeername(int sd, struct sockaddr *addr, int *addrlen);
extern int Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen);
-
-#define connect Curl_os400_connect
-#define bind Curl_os400_bind
-#define sendto Curl_os400_sendto
-#define recvfrom Curl_os400_recvfrom
+
+#define connect Curl_os400_connect
+#define bind Curl_os400_bind
+#define sendto Curl_os400_sendto
+#define recvfrom Curl_os400_recvfrom
#define getpeername Curl_os400_getpeername
#define getsockname Curl_os400_getsockname
-
+
#ifdef HAVE_LIBZ
#define zlibVersion Curl_os400_zlibVersion
#define inflateInit_ Curl_os400_inflateInit_
@@ -223,5 +223,5 @@ extern int Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen);
#define inflate Curl_os400_inflate
#define inflateEnd Curl_os400_inflateEnd
#endif
-
-#endif /* HEADER_CURL_SETUP_OS400_H */
+
+#endif /* HEADER_CURL_SETUP_OS400_H */
diff --git a/contrib/libs/curl/lib/setup-vms.h b/contrib/libs/curl/lib/setup-vms.h
index e8751b6a12..ba75dc295b 100644
--- a/contrib/libs/curl/lib/setup-vms.h
+++ b/contrib/libs/curl/lib/setup-vms.h
@@ -1,175 +1,175 @@
-#ifndef HEADER_CURL_SETUP_VMS_H
-#define HEADER_CURL_SETUP_VMS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SETUP_VMS_H
+#define HEADER_CURL_SETUP_VMS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* */
-/* JEM, 12/30/12, VMS now generates config.h, so only define wrappers for */
-/* getenv(), getpwuid() and provide is_vms_shell() */
-/* Also need upper case symbols for system services, and */
-/* OpenSSL, and some Kerberos image */
-
-#ifdef __DECC
-#pragma message save
-#pragma message disable dollarid
-#endif
-
-/* Hide the stuff we are overriding */
-#define getenv decc_getenv
-#ifdef __DECC
-# if __INITIAL_POINTER_SIZE != 64
-# define getpwuid decc_getpwuid
-# endif
-#endif
-#include <stdlib.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* */
+/* JEM, 12/30/12, VMS now generates config.h, so only define wrappers for */
+/* getenv(), getpwuid() and provide is_vms_shell() */
+/* Also need upper case symbols for system services, and */
+/* OpenSSL, and some Kerberos image */
+
+#ifdef __DECC
+#pragma message save
+#pragma message disable dollarid
+#endif
+
+/* Hide the stuff we are overriding */
+#define getenv decc_getenv
+#ifdef __DECC
+# if __INITIAL_POINTER_SIZE != 64
+# define getpwuid decc_getpwuid
+# endif
+#endif
+#include <stdlib.h>
char *decc$getenv(const char *__name);
-#include <pwd.h>
-
-#include <string.h>
-#include <unixlib.h>
-
-#undef getenv
-#undef getpwuid
-#define getenv vms_getenv
-#define getpwuid vms_getpwuid
-
-/* VAX needs these in upper case when compiling exact case */
-#define sys$assign SYS$ASSIGN
-#define sys$dassgn SYS$DASSGN
-#define sys$qiow SYS$QIOW
-
-#ifdef __DECC
-# if __INITIAL_POINTER_SIZE
-# pragma __pointer_size __save
-# endif
-#endif
-
-#if __USE_LONG_GID_T
-# define decc_getpwuid DECC$__LONG_GID_GETPWUID
-#else
-# if __INITIAL_POINTER_SIZE
-# define decc_getpwuid decc$__32_getpwuid
-# else
-# define decc_getpwuid decc$getpwuid
-# endif
-#endif
-
+#include <pwd.h>
+
+#include <string.h>
+#include <unixlib.h>
+
+#undef getenv
+#undef getpwuid
+#define getenv vms_getenv
+#define getpwuid vms_getpwuid
+
+/* VAX needs these in upper case when compiling exact case */
+#define sys$assign SYS$ASSIGN
+#define sys$dassgn SYS$DASSGN
+#define sys$qiow SYS$QIOW
+
+#ifdef __DECC
+# if __INITIAL_POINTER_SIZE
+# pragma __pointer_size __save
+# endif
+#endif
+
+#if __USE_LONG_GID_T
+# define decc_getpwuid DECC$__LONG_GID_GETPWUID
+#else
+# if __INITIAL_POINTER_SIZE
+# define decc_getpwuid decc$__32_getpwuid
+# else
+# define decc_getpwuid decc$getpwuid
+# endif
+#endif
+
struct passwd *decc_getpwuid(uid_t uid);
-
-#ifdef __DECC
-# if __INITIAL_POINTER_SIZE == 32
-/* Translate the path, but only if the path is a VMS file specification */
-/* The translation is usually only needed for older versions of VMS */
+
+#ifdef __DECC
+# if __INITIAL_POINTER_SIZE == 32
+/* Translate the path, but only if the path is a VMS file specification */
+/* The translation is usually only needed for older versions of VMS */
static char *vms_translate_path(const char *path)
{
char *unix_path;
char *test_str;
-
+
/* See if the result is in VMS format, if not, we are done */
/* Assume that this is a PATH, not just some data */
test_str = strpbrk(path, ":[<^");
if(test_str == NULL) {
return (char *)path;
}
-
+
unix_path = decc$translate_vms(path);
-
+
if((int)unix_path <= 0) {
/* We can not translate it, so return the original string */
return (char *)path;
}
-}
-# else
- /* VMS translate path is actually not needed on the current 64 bit */
- /* VMS platforms, so instead of figuring out the pointer settings */
- /* Change it to a noop */
-# define vms_translate_path(__path) __path
-# endif
-#endif
-
-#ifdef __DECC
-# if __INITIAL_POINTER_SIZE
-# pragma __pointer_size __restore
-# endif
-#endif
-
+}
+# else
+ /* VMS translate path is actually not needed on the current 64 bit */
+ /* VMS platforms, so instead of figuring out the pointer settings */
+ /* Change it to a noop */
+# define vms_translate_path(__path) __path
+# endif
+#endif
+
+#ifdef __DECC
+# if __INITIAL_POINTER_SIZE
+# pragma __pointer_size __restore
+# endif
+#endif
+
static char *vms_getenv(const char *envvar)
{
char *result;
char *vms_path;
-
+
/* first use the DECC getenv() function */
result = decc$getenv(envvar);
if(result == NULL) {
return result;
}
-
+
vms_path = result;
result = vms_translate_path(vms_path);
-
+
/* note that if you backport this to use VAX C RTL, that the VAX C RTL */
/* may do a malloc(2048) for each call to getenv(), so you will need */
/* to add a free(vms_path) */
/* Do not do a free() for DEC C RTL builds, which should be used for */
/* VMS 5.5-2 and later, even if using GCC */
-
+
return result;
-}
-
-
-static struct passwd vms_passwd_cache;
-
+}
+
+
+static struct passwd vms_passwd_cache;
+
static struct passwd *vms_getpwuid(uid_t uid)
{
struct passwd *my_passwd;
-
-/* Hack needed to support 64 bit builds, decc_getpwnam is 32 bit only */
-#ifdef __DECC
-# if __INITIAL_POINTER_SIZE
+
+/* Hack needed to support 64 bit builds, decc_getpwnam is 32 bit only */
+#ifdef __DECC
+# if __INITIAL_POINTER_SIZE
__char_ptr32 unix_path;
-# else
+# else
char *unix_path;
-# endif
-#else
+# endif
+#else
char *unix_path;
-#endif
-
+#endif
+
my_passwd = decc_getpwuid(uid);
if(my_passwd == NULL) {
return my_passwd;
}
-
+
unix_path = vms_translate_path(my_passwd->pw_dir);
-
+
if((long)unix_path <= 0) {
/* We can not translate it, so return the original string */
return my_passwd;
}
-
+
/* If no changes needed just return it */
if(unix_path == my_passwd->pw_dir) {
return my_passwd;
}
-
+
/* Need to copy the structure returned */
/* Since curl is only using pw_dir, no need to fix up */
/* the pw_shell when running under Bash */
@@ -178,32 +178,32 @@ static struct passwd *vms_getpwuid(uid_t uid)
vms_passwd_cache.pw_gid = my_passwd->pw_uid;
vms_passwd_cache.pw_dir = unix_path;
vms_passwd_cache.pw_shell = my_passwd->pw_shell;
-
+
return &vms_passwd_cache;
-}
-
-#ifdef __DECC
-#pragma message restore
-#endif
-
-/* Bug - VMS OpenSSL and Kerberos universal symbols are in uppercase only */
-/* VMS libraries should have universal symbols in exact and uppercase */
-
-#define ASN1_INTEGER_get ASN1_INTEGER_GET
-#define ASN1_STRING_data ASN1_STRING_DATA
-#define ASN1_STRING_length ASN1_STRING_LENGTH
-#define ASN1_STRING_print ASN1_STRING_PRINT
-#define ASN1_STRING_to_UTF8 ASN1_STRING_TO_UTF8
-#define ASN1_STRING_type ASN1_STRING_TYPE
-#define BIO_ctrl BIO_CTRL
-#define BIO_free BIO_FREE
-#define BIO_new BIO_NEW
-#define BIO_s_mem BIO_S_MEM
-#define BN_bn2bin BN_BN2BIN
-#define BN_num_bits BN_NUM_BITS
-#define CRYPTO_cleanup_all_ex_data CRYPTO_CLEANUP_ALL_EX_DATA
-#define CRYPTO_free CRYPTO_FREE
-#define CRYPTO_malloc CRYPTO_MALLOC
+}
+
+#ifdef __DECC
+#pragma message restore
+#endif
+
+/* Bug - VMS OpenSSL and Kerberos universal symbols are in uppercase only */
+/* VMS libraries should have universal symbols in exact and uppercase */
+
+#define ASN1_INTEGER_get ASN1_INTEGER_GET
+#define ASN1_STRING_data ASN1_STRING_DATA
+#define ASN1_STRING_length ASN1_STRING_LENGTH
+#define ASN1_STRING_print ASN1_STRING_PRINT
+#define ASN1_STRING_to_UTF8 ASN1_STRING_TO_UTF8
+#define ASN1_STRING_type ASN1_STRING_TYPE
+#define BIO_ctrl BIO_CTRL
+#define BIO_free BIO_FREE
+#define BIO_new BIO_NEW
+#define BIO_s_mem BIO_S_MEM
+#define BN_bn2bin BN_BN2BIN
+#define BN_num_bits BN_NUM_BITS
+#define CRYPTO_cleanup_all_ex_data CRYPTO_CLEANUP_ALL_EX_DATA
+#define CRYPTO_free CRYPTO_FREE
+#define CRYPTO_malloc CRYPTO_MALLOC
#define CONF_modules_load_file CONF_MODULES_LOAD_FILE
#ifdef __VAX
# ifdef VMS_OLD_SSL
@@ -217,101 +217,101 @@ static struct passwd *vms_getpwuid(uid_t uid)
}
# endif
#endif
-#define DES_ecb_encrypt DES_ECB_ENCRYPT
-#define DES_set_key DES_SET_KEY
-#define DES_set_odd_parity DES_SET_ODD_PARITY
-#define ENGINE_ctrl ENGINE_CTRL
-#define ENGINE_ctrl_cmd ENGINE_CTRL_CMD
-#define ENGINE_finish ENGINE_FINISH
-#define ENGINE_free ENGINE_FREE
-#define ENGINE_get_first ENGINE_GET_FIRST
-#define ENGINE_get_id ENGINE_GET_ID
-#define ENGINE_get_next ENGINE_GET_NEXT
-#define ENGINE_init ENGINE_INIT
-#define ENGINE_load_builtin_engines ENGINE_LOAD_BUILTIN_ENGINES
-#define ENGINE_load_private_key ENGINE_LOAD_PRIVATE_KEY
-#define ENGINE_set_default ENGINE_SET_DEFAULT
-#define ERR_clear_error ERR_CLEAR_ERROR
-#define ERR_error_string ERR_ERROR_STRING
-#define ERR_error_string_n ERR_ERROR_STRING_N
-#define ERR_free_strings ERR_FREE_STRINGS
-#define ERR_get_error ERR_GET_ERROR
-#define ERR_peek_error ERR_PEEK_ERROR
-#define ERR_remove_state ERR_REMOVE_STATE
-#define EVP_PKEY_copy_parameters EVP_PKEY_COPY_PARAMETERS
-#define EVP_PKEY_free EVP_PKEY_FREE
-#define EVP_cleanup EVP_CLEANUP
-#define GENERAL_NAMES_free GENERAL_NAMES_FREE
+#define DES_ecb_encrypt DES_ECB_ENCRYPT
+#define DES_set_key DES_SET_KEY
+#define DES_set_odd_parity DES_SET_ODD_PARITY
+#define ENGINE_ctrl ENGINE_CTRL
+#define ENGINE_ctrl_cmd ENGINE_CTRL_CMD
+#define ENGINE_finish ENGINE_FINISH
+#define ENGINE_free ENGINE_FREE
+#define ENGINE_get_first ENGINE_GET_FIRST
+#define ENGINE_get_id ENGINE_GET_ID
+#define ENGINE_get_next ENGINE_GET_NEXT
+#define ENGINE_init ENGINE_INIT
+#define ENGINE_load_builtin_engines ENGINE_LOAD_BUILTIN_ENGINES
+#define ENGINE_load_private_key ENGINE_LOAD_PRIVATE_KEY
+#define ENGINE_set_default ENGINE_SET_DEFAULT
+#define ERR_clear_error ERR_CLEAR_ERROR
+#define ERR_error_string ERR_ERROR_STRING
+#define ERR_error_string_n ERR_ERROR_STRING_N
+#define ERR_free_strings ERR_FREE_STRINGS
+#define ERR_get_error ERR_GET_ERROR
+#define ERR_peek_error ERR_PEEK_ERROR
+#define ERR_remove_state ERR_REMOVE_STATE
+#define EVP_PKEY_copy_parameters EVP_PKEY_COPY_PARAMETERS
+#define EVP_PKEY_free EVP_PKEY_FREE
+#define EVP_cleanup EVP_CLEANUP
+#define GENERAL_NAMES_free GENERAL_NAMES_FREE
#define i2d_X509_PUBKEY I2D_X509_PUBKEY
-#define MD4_Final MD4_FINAL
-#define MD4_Init MD4_INIT
-#define MD4_Update MD4_UPDATE
-#define MD5_Final MD5_FINAL
-#define MD5_Init MD5_INIT
-#define MD5_Update MD5_UPDATE
-#define OPENSSL_add_all_algo_noconf OPENSSL_ADD_ALL_ALGO_NOCONF
+#define MD4_Final MD4_FINAL
+#define MD4_Init MD4_INIT
+#define MD4_Update MD4_UPDATE
+#define MD5_Final MD5_FINAL
+#define MD5_Init MD5_INIT
+#define MD5_Update MD5_UPDATE
+#define OPENSSL_add_all_algo_noconf OPENSSL_ADD_ALL_ALGO_NOCONF
#ifndef __VAX
#define OPENSSL_load_builtin_modules OPENSSL_LOAD_BUILTIN_MODULES
#endif
-#define PEM_read_X509 PEM_READ_X509
-#define PEM_write_bio_X509 PEM_WRITE_BIO_X509
-#define PKCS12_PBE_add PKCS12_PBE_ADD
-#define PKCS12_free PKCS12_FREE
-#define PKCS12_parse PKCS12_PARSE
-#define RAND_add RAND_ADD
-#define RAND_bytes RAND_BYTES
-#define RAND_egd RAND_EGD
-#define RAND_file_name RAND_FILE_NAME
-#define RAND_load_file RAND_LOAD_FILE
-#define RAND_status RAND_STATUS
-#define SSL_CIPHER_get_name SSL_CIPHER_GET_NAME
-#define SSL_CTX_add_client_CA SSL_CTX_ADD_CLIENT_CA
-#define SSL_CTX_callback_ctrl SSL_CTX_CALLBACK_CTRL
-#define SSL_CTX_check_private_key SSL_CTX_CHECK_PRIVATE_KEY
-#define SSL_CTX_ctrl SSL_CTX_CTRL
-#define SSL_CTX_free SSL_CTX_FREE
-#define SSL_CTX_get_cert_store SSL_CTX_GET_CERT_STORE
-#define SSL_CTX_load_verify_locations SSL_CTX_LOAD_VERIFY_LOCATIONS
-#define SSL_CTX_new SSL_CTX_NEW
-#define SSL_CTX_set_cipher_list SSL_CTX_SET_CIPHER_LIST
-#define SSL_CTX_set_def_passwd_cb_ud SSL_CTX_SET_DEF_PASSWD_CB_UD
-#define SSL_CTX_set_default_passwd_cb SSL_CTX_SET_DEFAULT_PASSWD_CB
+#define PEM_read_X509 PEM_READ_X509
+#define PEM_write_bio_X509 PEM_WRITE_BIO_X509
+#define PKCS12_PBE_add PKCS12_PBE_ADD
+#define PKCS12_free PKCS12_FREE
+#define PKCS12_parse PKCS12_PARSE
+#define RAND_add RAND_ADD
+#define RAND_bytes RAND_BYTES
+#define RAND_egd RAND_EGD
+#define RAND_file_name RAND_FILE_NAME
+#define RAND_load_file RAND_LOAD_FILE
+#define RAND_status RAND_STATUS
+#define SSL_CIPHER_get_name SSL_CIPHER_GET_NAME
+#define SSL_CTX_add_client_CA SSL_CTX_ADD_CLIENT_CA
+#define SSL_CTX_callback_ctrl SSL_CTX_CALLBACK_CTRL
+#define SSL_CTX_check_private_key SSL_CTX_CHECK_PRIVATE_KEY
+#define SSL_CTX_ctrl SSL_CTX_CTRL
+#define SSL_CTX_free SSL_CTX_FREE
+#define SSL_CTX_get_cert_store SSL_CTX_GET_CERT_STORE
+#define SSL_CTX_load_verify_locations SSL_CTX_LOAD_VERIFY_LOCATIONS
+#define SSL_CTX_new SSL_CTX_NEW
+#define SSL_CTX_set_cipher_list SSL_CTX_SET_CIPHER_LIST
+#define SSL_CTX_set_def_passwd_cb_ud SSL_CTX_SET_DEF_PASSWD_CB_UD
+#define SSL_CTX_set_default_passwd_cb SSL_CTX_SET_DEFAULT_PASSWD_CB
#define SSL_CTX_set_msg_callback SSL_CTX_SET_MSG_CALLBACK
-#define SSL_CTX_set_verify SSL_CTX_SET_VERIFY
-#define SSL_CTX_use_PrivateKey SSL_CTX_USE_PRIVATEKEY
-#define SSL_CTX_use_PrivateKey_file SSL_CTX_USE_PRIVATEKEY_FILE
-#define SSL_CTX_use_cert_chain_file SSL_CTX_USE_CERT_CHAIN_FILE
-#define SSL_CTX_use_certificate SSL_CTX_USE_CERTIFICATE
-#define SSL_CTX_use_certificate_file SSL_CTX_USE_CERTIFICATE_FILE
-#define SSL_SESSION_free SSL_SESSION_FREE
-#define SSL_connect SSL_CONNECT
-#define SSL_free SSL_FREE
-#define SSL_get1_session SSL_GET1_SESSION
-#define SSL_get_certificate SSL_GET_CERTIFICATE
-#define SSL_get_current_cipher SSL_GET_CURRENT_CIPHER
-#define SSL_get_error SSL_GET_ERROR
-#define SSL_get_peer_cert_chain SSL_GET_PEER_CERT_CHAIN
-#define SSL_get_peer_certificate SSL_GET_PEER_CERTIFICATE
-#define SSL_get_privatekey SSL_GET_PRIVATEKEY
+#define SSL_CTX_set_verify SSL_CTX_SET_VERIFY
+#define SSL_CTX_use_PrivateKey SSL_CTX_USE_PRIVATEKEY
+#define SSL_CTX_use_PrivateKey_file SSL_CTX_USE_PRIVATEKEY_FILE
+#define SSL_CTX_use_cert_chain_file SSL_CTX_USE_CERT_CHAIN_FILE
+#define SSL_CTX_use_certificate SSL_CTX_USE_CERTIFICATE
+#define SSL_CTX_use_certificate_file SSL_CTX_USE_CERTIFICATE_FILE
+#define SSL_SESSION_free SSL_SESSION_FREE
+#define SSL_connect SSL_CONNECT
+#define SSL_free SSL_FREE
+#define SSL_get1_session SSL_GET1_SESSION
+#define SSL_get_certificate SSL_GET_CERTIFICATE
+#define SSL_get_current_cipher SSL_GET_CURRENT_CIPHER
+#define SSL_get_error SSL_GET_ERROR
+#define SSL_get_peer_cert_chain SSL_GET_PEER_CERT_CHAIN
+#define SSL_get_peer_certificate SSL_GET_PEER_CERTIFICATE
+#define SSL_get_privatekey SSL_GET_PRIVATEKEY
#define SSL_get_session SSL_GET_SESSION
-#define SSL_get_shutdown SSL_GET_SHUTDOWN
-#define SSL_get_verify_result SSL_GET_VERIFY_RESULT
-#define SSL_library_init SSL_LIBRARY_INIT
-#define SSL_load_error_strings SSL_LOAD_ERROR_STRINGS
-#define SSL_new SSL_NEW
-#define SSL_peek SSL_PEEK
-#define SSL_pending SSL_PENDING
-#define SSL_read SSL_READ
-#define SSL_set_connect_state SSL_SET_CONNECT_STATE
-#define SSL_set_fd SSL_SET_FD
-#define SSL_set_session SSL_SET_SESSION
-#define SSL_shutdown SSL_SHUTDOWN
+#define SSL_get_shutdown SSL_GET_SHUTDOWN
+#define SSL_get_verify_result SSL_GET_VERIFY_RESULT
+#define SSL_library_init SSL_LIBRARY_INIT
+#define SSL_load_error_strings SSL_LOAD_ERROR_STRINGS
+#define SSL_new SSL_NEW
+#define SSL_peek SSL_PEEK
+#define SSL_pending SSL_PENDING
+#define SSL_read SSL_READ
+#define SSL_set_connect_state SSL_SET_CONNECT_STATE
+#define SSL_set_fd SSL_SET_FD
+#define SSL_set_session SSL_SET_SESSION
+#define SSL_shutdown SSL_SHUTDOWN
#define SSL_version SSL_VERSION
-#define SSL_write SSL_WRITE
-#define SSLeay SSLEAY
-#define SSLv23_client_method SSLV23_CLIENT_METHOD
-#define SSLv3_client_method SSLV3_CLIENT_METHOD
-#define TLSv1_client_method TLSV1_CLIENT_METHOD
+#define SSL_write SSL_WRITE
+#define SSLeay SSLEAY
+#define SSLv23_client_method SSLV23_CLIENT_METHOD
+#define SSLv3_client_method SSLV3_CLIENT_METHOD
+#define TLSv1_client_method TLSV1_CLIENT_METHOD
#define UI_create_method UI_CREATE_METHOD
#define UI_destroy_method UI_DESTROY_METHOD
#define UI_get0_user_data UI_GET0_USER_DATA
@@ -327,117 +327,117 @@ static struct passwd *vms_getpwuid(uid_t uid)
#define UI_method_set_opener UI_METHOD_SET_OPENER
#define UI_method_set_reader UI_METHOD_SET_READER
#define UI_method_set_writer UI_METHOD_SET_WRITER
-#define UI_OpenSSL UI_OPENSSL
+#define UI_OpenSSL UI_OPENSSL
#define UI_set_result UI_SET_RESULT
-#define X509V3_EXT_print X509V3_EXT_PRINT
-#define X509_EXTENSION_get_critical X509_EXTENSION_GET_CRITICAL
+#define X509V3_EXT_print X509V3_EXT_PRINT
+#define X509_EXTENSION_get_critical X509_EXTENSION_GET_CRITICAL
#define X509_EXTENSION_get_data X509_EXTENSION_GET_DATA
-#define X509_EXTENSION_get_object X509_EXTENSION_GET_OBJECT
-#define X509_LOOKUP_file X509_LOOKUP_FILE
-#define X509_NAME_ENTRY_get_data X509_NAME_ENTRY_GET_DATA
-#define X509_NAME_get_entry X509_NAME_GET_ENTRY
-#define X509_NAME_get_index_by_NID X509_NAME_GET_INDEX_BY_NID
-#define X509_NAME_print_ex X509_NAME_PRINT_EX
-#define X509_STORE_CTX_get_current_cert X509_STORE_CTX_GET_CURRENT_CERT
-#define X509_STORE_add_lookup X509_STORE_ADD_LOOKUP
-#define X509_STORE_set_flags X509_STORE_SET_FLAGS
-#define X509_check_issued X509_CHECK_ISSUED
-#define X509_free X509_FREE
-#define X509_get_ext_d2i X509_GET_EXT_D2I
-#define X509_get_issuer_name X509_GET_ISSUER_NAME
-#define X509_get_pubkey X509_GET_PUBKEY
-#define X509_get_serialNumber X509_GET_SERIALNUMBER
-#define X509_get_subject_name X509_GET_SUBJECT_NAME
-#define X509_load_crl_file X509_LOAD_CRL_FILE
-#define X509_verify_cert_error_string X509_VERIFY_CERT_ERROR_STRING
-#define d2i_PKCS12_fp D2I_PKCS12_FP
-#define i2t_ASN1_OBJECT I2T_ASN1_OBJECT
-#define sk_num SK_NUM
-#define sk_pop SK_POP
-#define sk_pop_free SK_POP_FREE
-#define sk_value SK_VALUE
+#define X509_EXTENSION_get_object X509_EXTENSION_GET_OBJECT
+#define X509_LOOKUP_file X509_LOOKUP_FILE
+#define X509_NAME_ENTRY_get_data X509_NAME_ENTRY_GET_DATA
+#define X509_NAME_get_entry X509_NAME_GET_ENTRY
+#define X509_NAME_get_index_by_NID X509_NAME_GET_INDEX_BY_NID
+#define X509_NAME_print_ex X509_NAME_PRINT_EX
+#define X509_STORE_CTX_get_current_cert X509_STORE_CTX_GET_CURRENT_CERT
+#define X509_STORE_add_lookup X509_STORE_ADD_LOOKUP
+#define X509_STORE_set_flags X509_STORE_SET_FLAGS
+#define X509_check_issued X509_CHECK_ISSUED
+#define X509_free X509_FREE
+#define X509_get_ext_d2i X509_GET_EXT_D2I
+#define X509_get_issuer_name X509_GET_ISSUER_NAME
+#define X509_get_pubkey X509_GET_PUBKEY
+#define X509_get_serialNumber X509_GET_SERIALNUMBER
+#define X509_get_subject_name X509_GET_SUBJECT_NAME
+#define X509_load_crl_file X509_LOAD_CRL_FILE
+#define X509_verify_cert_error_string X509_VERIFY_CERT_ERROR_STRING
+#define d2i_PKCS12_fp D2I_PKCS12_FP
+#define i2t_ASN1_OBJECT I2T_ASN1_OBJECT
+#define sk_num SK_NUM
+#define sk_pop SK_POP
+#define sk_pop_free SK_POP_FREE
+#define sk_value SK_VALUE
#ifdef __VAX
#define OPENSSL_NO_SHA256
#endif
#define SHA256_Final SHA256_FINAL
#define SHA256_Init SHA256_INIT
#define SHA256_Update SHA256_UPDATE
-
-#define USE_UPPERCASE_GSSAPI 1
-#define gss_seal GSS_SEAL
-#define gss_unseal GSS_UNSEAL
-
-#define USE_UPPERCASE_KRBAPI 1
-
-/* AI_NUMERICHOST needed for IP V6 support in Curl */
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#ifndef AI_NUMERICHOST
-#ifdef ENABLE_IPV6
-#undef ENABLE_IPV6
-#endif
-#endif
-#endif
-
-/* VAX symbols are always in uppercase */
-#ifdef __VAX
-#define inflate INFLATE
-#define inflateEnd INFLATEEND
-#define inflateInit2_ INFLATEINIT2_
-#define inflateInit_ INFLATEINIT_
-#define zlibVersion ZLIBVERSION
-#endif
-
-/* Older VAX OpenSSL port defines these as Macros */
-/* Need to include the headers first and then redefine */
-/* that way a newer port will also work if some one has one */
-#ifdef __VAX
-
-# if (OPENSSL_VERSION_NUMBER < 0x00907001L)
-# define des_set_odd_parity DES_SET_ODD_PARITY
-# define des_set_key DES_SET_KEY
-# define des_ecb_encrypt DES_ECB_ENCRYPT
-
-# endif
-# include <openssl/evp.h>
-# ifndef OpenSSL_add_all_algorithms
-# define OpenSSL_add_all_algorithms OPENSSL_ADD_ALL_ALGORITHMS
- void OPENSSL_ADD_ALL_ALGORITHMS(void);
-# endif
-
- /* Curl defines these to lower case and VAX needs them in upper case */
- /* So we need static routines */
-# if (OPENSSL_VERSION_NUMBER < 0x00907001L)
-
-# undef des_set_odd_parity
-# undef DES_set_odd_parity
-# undef des_set_key
-# undef DES_set_key
-# undef des_ecb_encrypt
-# undef DES_ecb_encrypt
-
- static void des_set_odd_parity(des_cblock *key) {
- DES_SET_ODD_PARITY(key);
- }
-
- static int des_set_key(const_des_cblock *key,
- des_key_schedule schedule) {
- return DES_SET_KEY(key, schedule);
- }
-
- static void des_ecb_encrypt(const_des_cblock *input,
- des_cblock *output,
+
+#define USE_UPPERCASE_GSSAPI 1
+#define gss_seal GSS_SEAL
+#define gss_unseal GSS_UNSEAL
+
+#define USE_UPPERCASE_KRBAPI 1
+
+/* AI_NUMERICHOST needed for IP V6 support in Curl */
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#ifndef AI_NUMERICHOST
+#ifdef ENABLE_IPV6
+#undef ENABLE_IPV6
+#endif
+#endif
+#endif
+
+/* VAX symbols are always in uppercase */
+#ifdef __VAX
+#define inflate INFLATE
+#define inflateEnd INFLATEEND
+#define inflateInit2_ INFLATEINIT2_
+#define inflateInit_ INFLATEINIT_
+#define zlibVersion ZLIBVERSION
+#endif
+
+/* Older VAX OpenSSL port defines these as Macros */
+/* Need to include the headers first and then redefine */
+/* that way a newer port will also work if some one has one */
+#ifdef __VAX
+
+# if (OPENSSL_VERSION_NUMBER < 0x00907001L)
+# define des_set_odd_parity DES_SET_ODD_PARITY
+# define des_set_key DES_SET_KEY
+# define des_ecb_encrypt DES_ECB_ENCRYPT
+
+# endif
+# include <openssl/evp.h>
+# ifndef OpenSSL_add_all_algorithms
+# define OpenSSL_add_all_algorithms OPENSSL_ADD_ALL_ALGORITHMS
+ void OPENSSL_ADD_ALL_ALGORITHMS(void);
+# endif
+
+ /* Curl defines these to lower case and VAX needs them in upper case */
+ /* So we need static routines */
+# if (OPENSSL_VERSION_NUMBER < 0x00907001L)
+
+# undef des_set_odd_parity
+# undef DES_set_odd_parity
+# undef des_set_key
+# undef DES_set_key
+# undef des_ecb_encrypt
+# undef DES_ecb_encrypt
+
+ static void des_set_odd_parity(des_cblock *key) {
+ DES_SET_ODD_PARITY(key);
+ }
+
+ static int des_set_key(const_des_cblock *key,
+ des_key_schedule schedule) {
+ return DES_SET_KEY(key, schedule);
+ }
+
+ static void des_ecb_encrypt(const_des_cblock *input,
+ des_cblock *output,
des_key_schedule ks, int enc) {
- DES_ECB_ENCRYPT(input, output, ks, enc);
- }
-#endif
-/* Need this to stop a macro redefinition error */
-#if OPENSSL_VERSION_NUMBER < 0x00907000L
-# ifdef X509_STORE_set_flags
-# undef X509_STORE_set_flags
-# define X509_STORE_set_flags(x,y) Curl_nop_stmt
-# endif
-#endif
-#endif
-
-#endif /* HEADER_CURL_SETUP_VMS_H */
+ DES_ECB_ENCRYPT(input, output, ks, enc);
+ }
+#endif
+/* Need this to stop a macro redefinition error */
+#if OPENSSL_VERSION_NUMBER < 0x00907000L
+# ifdef X509_STORE_set_flags
+# undef X509_STORE_set_flags
+# define X509_STORE_set_flags(x,y) Curl_nop_stmt
+# endif
+#endif
+#endif
+
+#endif /* HEADER_CURL_SETUP_VMS_H */
diff --git a/contrib/libs/curl/lib/share.c b/contrib/libs/curl/lib/share.c
index 99fb6b8e54..5ce9830335 100644
--- a/contrib/libs/curl/lib/share.c
+++ b/contrib/libs/curl/lib/share.c
@@ -1,259 +1,259 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-#include "urldata.h"
-#include "share.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "share.h"
#include "psl.h"
#include "vtls/vtls.h"
-#include "curl_memory.h"
-
-/* The last #include file should be: */
-#include "memdebug.h"
-
+#include "curl_memory.h"
+
+/* The last #include file should be: */
+#include "memdebug.h"
+
struct Curl_share *
-curl_share_init(void)
-{
- struct Curl_share *share = calloc(1, sizeof(struct Curl_share));
+curl_share_init(void)
+{
+ struct Curl_share *share = calloc(1, sizeof(struct Curl_share));
if(share) {
- share->specifier |= (1<<CURL_LOCK_DATA_SHARE);
-
+ share->specifier |= (1<<CURL_LOCK_DATA_SHARE);
+
if(Curl_mk_dnscache(&share->hostcache)) {
free(share);
return NULL;
}
}
- return share;
-}
-
-#undef curl_share_setopt
-CURLSHcode
+ return share;
+}
+
+#undef curl_share_setopt
+CURLSHcode
curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...)
-{
- va_list param;
- int type;
- curl_lock_function lockfunc;
- curl_unlock_function unlockfunc;
- void *ptr;
- CURLSHcode res = CURLSHE_OK;
-
- if(share->dirty)
- /* don't allow setting options while one or more handles are already
- using this share */
- return CURLSHE_IN_USE;
-
- va_start(param, option);
-
- switch(option) {
- case CURLSHOPT_SHARE:
- /* this is a type this share will share */
- type = va_arg(param, int);
+{
+ va_list param;
+ int type;
+ curl_lock_function lockfunc;
+ curl_unlock_function unlockfunc;
+ void *ptr;
+ CURLSHcode res = CURLSHE_OK;
+
+ if(share->dirty)
+ /* don't allow setting options while one or more handles are already
+ using this share */
+ return CURLSHE_IN_USE;
+
+ va_start(param, option);
+
+ switch(option) {
+ case CURLSHOPT_SHARE:
+ /* this is a type this share will share */
+ type = va_arg(param, int);
switch(type) {
- case CURL_LOCK_DATA_DNS:
- break;
-
- case CURL_LOCK_DATA_COOKIE:
-#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
- if(!share->cookies) {
+ case CURL_LOCK_DATA_DNS:
+ break;
+
+ case CURL_LOCK_DATA_COOKIE:
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+ if(!share->cookies) {
share->cookies = Curl_cookie_init(NULL, NULL, NULL, TRUE);
- if(!share->cookies)
- res = CURLSHE_NOMEM;
- }
-#else /* CURL_DISABLE_HTTP */
- res = CURLSHE_NOT_BUILT_IN;
-#endif
- break;
-
- case CURL_LOCK_DATA_SSL_SESSION:
-#ifdef USE_SSL
- if(!share->sslsession) {
- share->max_ssl_sessions = 8;
- share->sslsession = calloc(share->max_ssl_sessions,
+ if(!share->cookies)
+ res = CURLSHE_NOMEM;
+ }
+#else /* CURL_DISABLE_HTTP */
+ res = CURLSHE_NOT_BUILT_IN;
+#endif
+ break;
+
+ case CURL_LOCK_DATA_SSL_SESSION:
+#ifdef USE_SSL
+ if(!share->sslsession) {
+ share->max_ssl_sessions = 8;
+ share->sslsession = calloc(share->max_ssl_sessions,
sizeof(struct Curl_ssl_session));
- share->sessionage = 0;
- if(!share->sslsession)
- res = CURLSHE_NOMEM;
- }
-#else
- res = CURLSHE_NOT_BUILT_IN;
-#endif
- break;
-
+ share->sessionage = 0;
+ if(!share->sslsession)
+ res = CURLSHE_NOMEM;
+ }
+#else
+ res = CURLSHE_NOT_BUILT_IN;
+#endif
+ break;
+
case CURL_LOCK_DATA_CONNECT:
if(Curl_conncache_init(&share->conn_cache, 103))
res = CURLSHE_NOMEM;
- break;
-
+ break;
+
case CURL_LOCK_DATA_PSL:
#ifndef USE_LIBPSL
res = CURLSHE_NOT_BUILT_IN;
#endif
break;
- default:
- res = CURLSHE_BAD_OPTION;
- }
+ default:
+ res = CURLSHE_BAD_OPTION;
+ }
if(!res)
share->specifier |= (1<<type);
- break;
-
- case CURLSHOPT_UNSHARE:
- /* this is a type this share will no longer share */
- type = va_arg(param, int);
- share->specifier &= ~(1<<type);
+ break;
+
+ case CURLSHOPT_UNSHARE:
+ /* this is a type this share will no longer share */
+ type = va_arg(param, int);
+ share->specifier &= ~(1<<type);
switch(type) {
- case CURL_LOCK_DATA_DNS:
- break;
-
- case CURL_LOCK_DATA_COOKIE:
-#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
- if(share->cookies) {
- Curl_cookie_cleanup(share->cookies);
- share->cookies = NULL;
- }
-#else /* CURL_DISABLE_HTTP */
- res = CURLSHE_NOT_BUILT_IN;
-#endif
- break;
-
- case CURL_LOCK_DATA_SSL_SESSION:
-#ifdef USE_SSL
- Curl_safefree(share->sslsession);
-#else
- res = CURLSHE_NOT_BUILT_IN;
-#endif
- break;
-
- case CURL_LOCK_DATA_CONNECT:
- break;
-
- default:
- res = CURLSHE_BAD_OPTION;
- break;
- }
- break;
-
- case CURLSHOPT_LOCKFUNC:
- lockfunc = va_arg(param, curl_lock_function);
- share->lockfunc = lockfunc;
- break;
-
- case CURLSHOPT_UNLOCKFUNC:
- unlockfunc = va_arg(param, curl_unlock_function);
- share->unlockfunc = unlockfunc;
- break;
-
- case CURLSHOPT_USERDATA:
- ptr = va_arg(param, void *);
- share->clientdata = ptr;
- break;
-
- default:
- res = CURLSHE_BAD_OPTION;
- break;
- }
-
- va_end(param);
-
- return res;
-}
-
-CURLSHcode
+ case CURL_LOCK_DATA_DNS:
+ break;
+
+ case CURL_LOCK_DATA_COOKIE:
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+ if(share->cookies) {
+ Curl_cookie_cleanup(share->cookies);
+ share->cookies = NULL;
+ }
+#else /* CURL_DISABLE_HTTP */
+ res = CURLSHE_NOT_BUILT_IN;
+#endif
+ break;
+
+ case CURL_LOCK_DATA_SSL_SESSION:
+#ifdef USE_SSL
+ Curl_safefree(share->sslsession);
+#else
+ res = CURLSHE_NOT_BUILT_IN;
+#endif
+ break;
+
+ case CURL_LOCK_DATA_CONNECT:
+ break;
+
+ default:
+ res = CURLSHE_BAD_OPTION;
+ break;
+ }
+ break;
+
+ case CURLSHOPT_LOCKFUNC:
+ lockfunc = va_arg(param, curl_lock_function);
+ share->lockfunc = lockfunc;
+ break;
+
+ case CURLSHOPT_UNLOCKFUNC:
+ unlockfunc = va_arg(param, curl_unlock_function);
+ share->unlockfunc = unlockfunc;
+ break;
+
+ case CURLSHOPT_USERDATA:
+ ptr = va_arg(param, void *);
+ share->clientdata = ptr;
+ break;
+
+ default:
+ res = CURLSHE_BAD_OPTION;
+ break;
+ }
+
+ va_end(param);
+
+ return res;
+}
+
+CURLSHcode
curl_share_cleanup(struct Curl_share *share)
-{
- if(share == NULL)
- return CURLSHE_INVALID;
-
- if(share->lockfunc)
- share->lockfunc(NULL, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE,
- share->clientdata);
-
- if(share->dirty) {
- if(share->unlockfunc)
- share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata);
- return CURLSHE_IN_USE;
- }
-
+{
+ if(share == NULL)
+ return CURLSHE_INVALID;
+
+ if(share->lockfunc)
+ share->lockfunc(NULL, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE,
+ share->clientdata);
+
+ if(share->dirty) {
+ if(share->unlockfunc)
+ share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata);
+ return CURLSHE_IN_USE;
+ }
+
Curl_conncache_close_all_connections(&share->conn_cache);
Curl_conncache_destroy(&share->conn_cache);
Curl_hash_destroy(&share->hostcache);
-
-#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
Curl_cookie_cleanup(share->cookies);
-#endif
-
-#ifdef USE_SSL
- if(share->sslsession) {
- size_t i;
- for(i = 0; i < share->max_ssl_sessions; i++)
- Curl_ssl_kill_session(&(share->sslsession[i]));
- free(share->sslsession);
- }
-#endif
-
+#endif
+
+#ifdef USE_SSL
+ if(share->sslsession) {
+ size_t i;
+ for(i = 0; i < share->max_ssl_sessions; i++)
+ Curl_ssl_kill_session(&(share->sslsession[i]));
+ free(share->sslsession);
+ }
+#endif
+
Curl_psl_destroy(&share->psl);
- if(share->unlockfunc)
- share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata);
- free(share);
-
- return CURLSHE_OK;
-}
-
-
-CURLSHcode
+ if(share->unlockfunc)
+ share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata);
+ free(share);
+
+ return CURLSHE_OK;
+}
+
+
+CURLSHcode
Curl_share_lock(struct Curl_easy *data, curl_lock_data type,
- curl_lock_access accesstype)
-{
- struct Curl_share *share = data->share;
-
- if(share == NULL)
- return CURLSHE_INVALID;
-
- if(share->specifier & (1<<type)) {
- if(share->lockfunc) /* only call this if set! */
- share->lockfunc(data, type, accesstype, share->clientdata);
- }
- /* else if we don't share this, pretend successful lock */
-
- return CURLSHE_OK;
-}
-
-CURLSHcode
+ curl_lock_access accesstype)
+{
+ struct Curl_share *share = data->share;
+
+ if(share == NULL)
+ return CURLSHE_INVALID;
+
+ if(share->specifier & (1<<type)) {
+ if(share->lockfunc) /* only call this if set! */
+ share->lockfunc(data, type, accesstype, share->clientdata);
+ }
+ /* else if we don't share this, pretend successful lock */
+
+ return CURLSHE_OK;
+}
+
+CURLSHcode
Curl_share_unlock(struct Curl_easy *data, curl_lock_data type)
-{
- struct Curl_share *share = data->share;
-
- if(share == NULL)
- return CURLSHE_INVALID;
-
- if(share->specifier & (1<<type)) {
- if(share->unlockfunc) /* only call this if set! */
- share->unlockfunc (data, type, share->clientdata);
- }
-
- return CURLSHE_OK;
-}
+{
+ struct Curl_share *share = data->share;
+
+ if(share == NULL)
+ return CURLSHE_INVALID;
+
+ if(share->specifier & (1<<type)) {
+ if(share->unlockfunc) /* only call this if set! */
+ share->unlockfunc (data, type, share->clientdata);
+ }
+
+ return CURLSHE_OK;
+}
diff --git a/contrib/libs/curl/lib/share.h b/contrib/libs/curl/lib/share.h
index e9e19026b3..01aa9cda59 100644
--- a/contrib/libs/curl/lib/share.h
+++ b/contrib/libs/curl/lib/share.h
@@ -1,66 +1,66 @@
-#ifndef HEADER_CURL_SHARE_H
-#define HEADER_CURL_SHARE_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SHARE_H
+#define HEADER_CURL_SHARE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-#include <curl/curl.h>
-#include "cookie.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+#include <curl/curl.h>
+#include "cookie.h"
#include "psl.h"
-#include "urldata.h"
+#include "urldata.h"
#include "conncache.h"
-
-/* SalfordC says "A structure member may not be volatile". Hence:
- */
-#ifdef __SALFORDC__
-#define CURL_VOLATILE
-#else
-#define CURL_VOLATILE volatile
-#endif
-
-/* this struct is libcurl-private, don't export details */
-struct Curl_share {
- unsigned int specifier;
- CURL_VOLATILE unsigned int dirty;
-
- curl_lock_function lockfunc;
- curl_unlock_function unlockfunc;
- void *clientdata;
+
+/* SalfordC says "A structure member may not be volatile". Hence:
+ */
+#ifdef __SALFORDC__
+#define CURL_VOLATILE
+#else
+#define CURL_VOLATILE volatile
+#endif
+
+/* this struct is libcurl-private, don't export details */
+struct Curl_share {
+ unsigned int specifier;
+ CURL_VOLATILE unsigned int dirty;
+
+ curl_lock_function lockfunc;
+ curl_unlock_function unlockfunc;
+ void *clientdata;
struct conncache conn_cache;
struct Curl_hash hostcache;
-#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
- struct CookieInfo *cookies;
-#endif
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+ struct CookieInfo *cookies;
+#endif
#ifdef USE_LIBPSL
struct PslCache psl;
#endif
-
+
struct Curl_ssl_session *sslsession;
- size_t max_ssl_sessions;
- long sessionage;
-};
-
+ size_t max_ssl_sessions;
+ long sessionage;
+};
+
CURLSHcode Curl_share_lock(struct Curl_easy *, curl_lock_data,
curl_lock_access);
CURLSHcode Curl_share_unlock(struct Curl_easy *, curl_lock_data);
-
-#endif /* HEADER_CURL_SHARE_H */
+
+#endif /* HEADER_CURL_SHARE_H */
diff --git a/contrib/libs/curl/lib/slist.c b/contrib/libs/curl/lib/slist.c
index a2f9ece5c1..907c203f38 100644
--- a/contrib/libs/curl/lib/slist.c
+++ b/contrib/libs/curl/lib/slist.c
@@ -1,144 +1,144 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#include <curl/curl.h>
-#include "slist.h"
-
+#include "slist.h"
+
/* The last #include files should be: */
#include "curl_memory.h"
-#include "memdebug.h"
-
-/* returns last node in linked list */
-static struct curl_slist *slist_get_last(struct curl_slist *list)
-{
- struct curl_slist *item;
-
- /* if caller passed us a NULL, return now */
- if(!list)
- return NULL;
-
- /* loop through to find the last item */
- item = list;
- while(item->next) {
- item = item->next;
- }
- return item;
-}
-
-/*
- * Curl_slist_append_nodup() appends a string to the linked list. Rather than
- * copying the string in dynamic storage, it takes its ownership. The string
- * should have been malloc()ated. Curl_slist_append_nodup always returns
- * the address of the first record, so that you can use this function as an
- * initialization function as well as an append function.
- * If an error occurs, NULL is returned and the string argument is NOT
- * released.
- */
-struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, char *data)
-{
- struct curl_slist *last;
- struct curl_slist *new_item;
-
- DEBUGASSERT(data);
-
- new_item = malloc(sizeof(struct curl_slist));
- if(!new_item)
- return NULL;
-
- new_item->next = NULL;
- new_item->data = data;
-
- /* if this is the first item, then new_item *is* the list */
- if(!list)
- return new_item;
-
- last = slist_get_last(list);
- last->next = new_item;
- return list;
-}
-
-/*
- * curl_slist_append() appends a string to the linked list. It always returns
- * the address of the first record, so that you can use this function as an
- * initialization function as well as an append function. If you find this
- * bothersome, then simply create a separate _init function and call it
- * appropriately from within the program.
- */
-struct curl_slist *curl_slist_append(struct curl_slist *list,
- const char *data)
-{
- char *dupdata = strdup(data);
-
- if(!dupdata)
- return NULL;
-
- list = Curl_slist_append_nodup(list, dupdata);
- if(!list)
- free(dupdata);
-
- return list;
-}
-
-/*
- * Curl_slist_duplicate() duplicates a linked list. It always returns the
- * address of the first record of the cloned list or NULL in case of an
- * error (or if the input list was NULL).
- */
-struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist)
-{
- struct curl_slist *outlist = NULL;
- struct curl_slist *tmp;
-
- while(inlist) {
- tmp = curl_slist_append(outlist, inlist->data);
-
- if(!tmp) {
- curl_slist_free_all(outlist);
- return NULL;
- }
-
- outlist = tmp;
- inlist = inlist->next;
- }
- return outlist;
-}
-
-/* be nice and clean up resources */
-void curl_slist_free_all(struct curl_slist *list)
-{
- struct curl_slist *next;
- struct curl_slist *item;
-
- if(!list)
- return;
-
- item = list;
- do {
- next = item->next;
- Curl_safefree(item->data);
- free(item);
- item = next;
- } while(next);
-}
+#include "memdebug.h"
+
+/* returns last node in linked list */
+static struct curl_slist *slist_get_last(struct curl_slist *list)
+{
+ struct curl_slist *item;
+
+ /* if caller passed us a NULL, return now */
+ if(!list)
+ return NULL;
+
+ /* loop through to find the last item */
+ item = list;
+ while(item->next) {
+ item = item->next;
+ }
+ return item;
+}
+
+/*
+ * Curl_slist_append_nodup() appends a string to the linked list. Rather than
+ * copying the string in dynamic storage, it takes its ownership. The string
+ * should have been malloc()ated. Curl_slist_append_nodup always returns
+ * the address of the first record, so that you can use this function as an
+ * initialization function as well as an append function.
+ * If an error occurs, NULL is returned and the string argument is NOT
+ * released.
+ */
+struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, char *data)
+{
+ struct curl_slist *last;
+ struct curl_slist *new_item;
+
+ DEBUGASSERT(data);
+
+ new_item = malloc(sizeof(struct curl_slist));
+ if(!new_item)
+ return NULL;
+
+ new_item->next = NULL;
+ new_item->data = data;
+
+ /* if this is the first item, then new_item *is* the list */
+ if(!list)
+ return new_item;
+
+ last = slist_get_last(list);
+ last->next = new_item;
+ return list;
+}
+
+/*
+ * curl_slist_append() appends a string to the linked list. It always returns
+ * the address of the first record, so that you can use this function as an
+ * initialization function as well as an append function. If you find this
+ * bothersome, then simply create a separate _init function and call it
+ * appropriately from within the program.
+ */
+struct curl_slist *curl_slist_append(struct curl_slist *list,
+ const char *data)
+{
+ char *dupdata = strdup(data);
+
+ if(!dupdata)
+ return NULL;
+
+ list = Curl_slist_append_nodup(list, dupdata);
+ if(!list)
+ free(dupdata);
+
+ return list;
+}
+
+/*
+ * Curl_slist_duplicate() duplicates a linked list. It always returns the
+ * address of the first record of the cloned list or NULL in case of an
+ * error (or if the input list was NULL).
+ */
+struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist)
+{
+ struct curl_slist *outlist = NULL;
+ struct curl_slist *tmp;
+
+ while(inlist) {
+ tmp = curl_slist_append(outlist, inlist->data);
+
+ if(!tmp) {
+ curl_slist_free_all(outlist);
+ return NULL;
+ }
+
+ outlist = tmp;
+ inlist = inlist->next;
+ }
+ return outlist;
+}
+
+/* be nice and clean up resources */
+void curl_slist_free_all(struct curl_slist *list)
+{
+ struct curl_slist *next;
+ struct curl_slist *item;
+
+ if(!list)
+ return;
+
+ item = list;
+ do {
+ next = item->next;
+ Curl_safefree(item->data);
+ free(item);
+ item = next;
+ } while(next);
+}
diff --git a/contrib/libs/curl/lib/slist.h b/contrib/libs/curl/lib/slist.h
index 354968f9e3..3114259cfe 100644
--- a/contrib/libs/curl/lib/slist.h
+++ b/contrib/libs/curl/lib/slist.h
@@ -1,39 +1,39 @@
-#ifndef HEADER_CURL_SLIST_H
-#define HEADER_CURL_SLIST_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SLIST_H
+#define HEADER_CURL_SLIST_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/*
- * Curl_slist_duplicate() duplicates a linked list. It always returns the
- * address of the first record of the cloned list or NULL in case of an
- * error (or if the input list was NULL).
- */
-struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist);
-
-/*
- * Curl_slist_append_nodup() takes ownership of the given string and appends
- * it to the list.
- */
-struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list,
- char *data);
-
-#endif /* HEADER_CURL_SLIST_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * Curl_slist_duplicate() duplicates a linked list. It always returns the
+ * address of the first record of the cloned list or NULL in case of an
+ * error (or if the input list was NULL).
+ */
+struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist);
+
+/*
+ * Curl_slist_append_nodup() takes ownership of the given string and appends
+ * it to the list.
+ */
+struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list,
+ char *data);
+
+#endif /* HEADER_CURL_SLIST_H */
diff --git a/contrib/libs/curl/lib/smtp.c b/contrib/libs/curl/lib/smtp.c
index 8241dd4756..509d802f1c 100644
--- a/contrib/libs/curl/lib/smtp.c
+++ b/contrib/libs/curl/lib/smtp.c
@@ -1,108 +1,108 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * RFC1870 SMTP Service Extension for Message Size
- * RFC2195 CRAM-MD5 authentication
- * RFC2831 DIGEST-MD5 authentication
- * RFC3207 SMTP over TLS
- * RFC4422 Simple Authentication and Security Layer (SASL)
- * RFC4616 PLAIN authentication
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * RFC1870 SMTP Service Extension for Message Size
+ * RFC2195 CRAM-MD5 authentication
+ * RFC2831 DIGEST-MD5 authentication
+ * RFC3207 SMTP over TLS
+ * RFC4422 Simple Authentication and Security Layer (SASL)
+ * RFC4616 PLAIN authentication
* RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
- * RFC4954 SMTP Authentication
- * RFC5321 SMTP protocol
+ * RFC4954 SMTP Authentication
+ * RFC5321 SMTP protocol
* RFC5890 Internationalized Domain Names for Applications (IDNA)
* RFC6531 SMTP Extension for Internationalized Email
* RFC6532 Internationalized Email Headers
- * RFC6749 OAuth 2.0 Authorization Framework
+ * RFC6749 OAuth 2.0 Authorization Framework
* RFC8314 Use of TLS for Email Submission and Access
* Draft SMTP URL Interface <draft-earhart-url-smtp-00.txt>
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_SMTP
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_UTSNAME_H
-#include <sys/utsname.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
-#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
-#undef in_addr_t
-#define in_addr_t unsigned long
-#endif
-
-#include <curl/curl.h>
-#include "urldata.h"
-#include "sendf.h"
-#include "hostip.h"
-#include "progress.h"
-#include "transfer.h"
-#include "escape.h"
-#include "http.h" /* for HTTP proxy tunnel stuff */
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_SMTP
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_UTSNAME_H
+#include <sys/utsname.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "progress.h"
+#include "transfer.h"
+#include "escape.h"
+#include "http.h" /* for HTTP proxy tunnel stuff */
#include "mime.h"
-#include "socks.h"
-#include "smtp.h"
-#include "strtoofft.h"
+#include "socks.h"
+#include "smtp.h"
+#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
-#include "connect.h"
-#include "strerror.h"
-#include "select.h"
-#include "multiif.h"
-#include "url.h"
-#include "curl_gethostname.h"
-#include "curl_sasl.h"
-#include "warnless.h"
+#include "connect.h"
+#include "strerror.h"
+#include "select.h"
+#include "multiif.h"
+#include "url.h"
+#include "curl_gethostname.h"
+#include "curl_sasl.h"
+#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* Local API functions */
-static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *done);
-static CURLcode smtp_do(struct connectdata *conn, bool *done);
-static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
- bool premature);
-static CURLcode smtp_connect(struct connectdata *conn, bool *done);
-static CURLcode smtp_disconnect(struct connectdata *conn, bool dead);
-static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done);
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* Local API functions */
+static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *done);
+static CURLcode smtp_do(struct connectdata *conn, bool *done);
+static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
+ bool premature);
+static CURLcode smtp_connect(struct connectdata *conn, bool *done);
+static CURLcode smtp_disconnect(struct connectdata *conn, bool dead);
+static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done);
static int smtp_getsock(struct connectdata *conn, curl_socket_t *socks);
-static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done);
-static CURLcode smtp_setup_connection(struct connectdata *conn);
-static CURLcode smtp_parse_url_options(struct connectdata *conn);
-static CURLcode smtp_parse_url_path(struct connectdata *conn);
+static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done);
+static CURLcode smtp_setup_connection(struct connectdata *conn);
+static CURLcode smtp_parse_url_options(struct connectdata *conn);
+static CURLcode smtp_parse_url_path(struct connectdata *conn);
static CURLcode smtp_parse_custom_request(struct connectdata *conn);
static CURLcode smtp_parse_address(struct connectdata *conn, const char *fqma,
char **address, struct hostname *host);
@@ -110,63 +110,63 @@ static CURLcode smtp_perform_auth(struct connectdata *conn, const char *mech,
const char *initresp);
static CURLcode smtp_continue_auth(struct connectdata *conn, const char *resp);
static void smtp_get_message(char *buffer, char **outptr);
-
-/*
- * SMTP protocol handler.
- */
-
-const struct Curl_handler Curl_handler_smtp = {
- "SMTP", /* scheme */
- smtp_setup_connection, /* setup_connection */
- smtp_do, /* do_it */
- smtp_done, /* done */
- ZERO_NULL, /* do_more */
- smtp_connect, /* connect_it */
- smtp_multi_statemach, /* connecting */
- smtp_doing, /* doing */
- smtp_getsock, /* proto_getsock */
- smtp_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- smtp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+
+/*
+ * SMTP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_smtp = {
+ "SMTP", /* scheme */
+ smtp_setup_connection, /* setup_connection */
+ smtp_do, /* do_it */
+ smtp_done, /* done */
+ ZERO_NULL, /* do_more */
+ smtp_connect, /* connect_it */
+ smtp_multi_statemach, /* connecting */
+ smtp_doing, /* doing */
+ smtp_getsock, /* proto_getsock */
+ smtp_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ smtp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_SMTP, /* defport */
- CURLPROTO_SMTP, /* protocol */
+ PORT_SMTP, /* defport */
+ CURLPROTO_SMTP, /* protocol */
CURLPROTO_SMTP, /* family */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */
PROTOPT_URLOPTIONS
-};
-
-#ifdef USE_SSL
-/*
- * SMTPS protocol handler.
- */
-
-const struct Curl_handler Curl_handler_smtps = {
- "SMTPS", /* scheme */
- smtp_setup_connection, /* setup_connection */
- smtp_do, /* do_it */
- smtp_done, /* done */
- ZERO_NULL, /* do_more */
- smtp_connect, /* connect_it */
- smtp_multi_statemach, /* connecting */
- smtp_doing, /* doing */
- smtp_getsock, /* proto_getsock */
- smtp_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- smtp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+};
+
+#ifdef USE_SSL
+/*
+ * SMTPS protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_smtps = {
+ "SMTPS", /* scheme */
+ smtp_setup_connection, /* setup_connection */
+ smtp_do, /* do_it */
+ smtp_done, /* done */
+ ZERO_NULL, /* do_more */
+ smtp_connect, /* connect_it */
+ smtp_multi_statemach, /* connecting */
+ smtp_doing, /* doing */
+ smtp_getsock, /* proto_getsock */
+ smtp_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ smtp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_SMTPS, /* defport */
+ PORT_SMTPS, /* defport */
CURLPROTO_SMTPS, /* protocol */
CURLPROTO_SMTP, /* family */
- PROTOPT_CLOSEACTION | PROTOPT_SSL
+ PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */
-};
-#endif
-
+};
+#endif
+
/* SASL parameters for the smtp protocol */
static const struct SASLproto saslsmtp = {
"smtp", /* The service name */
@@ -176,39 +176,39 @@ static const struct SASLproto saslsmtp = {
smtp_perform_auth, /* Send authentication command */
smtp_continue_auth, /* Send authentication continuation */
smtp_get_message /* Get SASL response message */
-};
-
-#ifdef USE_SSL
-static void smtp_to_smtps(struct connectdata *conn)
-{
+};
+
+#ifdef USE_SSL
+static void smtp_to_smtps(struct connectdata *conn)
+{
/* Change the connection handler */
- conn->handler = &Curl_handler_smtps;
+ conn->handler = &Curl_handler_smtps;
/* Set the connection's upgraded to TLS flag */
conn->bits.tls_upgraded = TRUE;
-}
-#else
-#define smtp_to_smtps(x) Curl_nop_stmt
-#endif
-
-/***********************************************************************
- *
+}
+#else
+#define smtp_to_smtps(x) Curl_nop_stmt
+#endif
+
+/***********************************************************************
+ *
* smtp_endofresp()
- *
- * Checks for an ending SMTP status code at the start of the given string, but
- * also detects various capabilities from the EHLO response including the
- * supported authentication mechanisms.
- */
-static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len,
- int *resp)
-{
- struct smtp_conn *smtpc = &conn->proto.smtpc;
- bool result = FALSE;
-
+ *
+ * Checks for an ending SMTP status code at the start of the given string, but
+ * also detects various capabilities from the EHLO response including the
+ * supported authentication mechanisms.
+ */
+static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len,
+ int *resp)
+{
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+ bool result = FALSE;
+
/* Nothing for us */
- if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
+ if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
return FALSE;
-
+
/* Do we have a command response? This should be the response code followed
by a space and optionally some text as per RFC-5321 and as outlined in
Section 4. Examples of RFC-4954 but some e-mail servers ignore this and
@@ -220,7 +220,7 @@ static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len,
memset(tmpline, '\0', sizeof(tmpline));
memcpy(tmpline, line, (len == 5 ? 5 : 3));
*resp = curlx_sltosi(strtol(tmpline, NULL, 10));
-
+
/* Make sure real server never sends internal value */
if(*resp == 1)
*resp = 0;
@@ -231,10 +231,10 @@ static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len,
result = TRUE;
*resp = 1; /* Internal response code */
}
-
+
return result;
}
-
+
/***********************************************************************
*
* smtp_get_message()
@@ -245,187 +245,187 @@ static void smtp_get_message(char *buffer, char **outptr)
{
size_t len = strlen(buffer);
char *message = NULL;
-
+
if(len > 4) {
/* Find the start of the message */
len -= 4;
for(message = buffer + 4; *message == ' ' || *message == '\t';
message++, len--)
;
-
+
/* Find the end of the message */
for(; len--;)
if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
message[len] != '\t')
break;
-
+
/* Terminate the message */
if(++len) {
message[len] = '\0';
- }
- }
+ }
+ }
else
/* junk input => zero length output */
message = &buffer[len];
-
+
*outptr = message;
-}
-
-/***********************************************************************
- *
- * state()
- *
- * This is the ONLY way to change SMTP state!
- */
-static void state(struct connectdata *conn, smtpstate newstate)
-{
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
- /* for debug purposes */
- static const char * const names[] = {
- "STOP",
- "SERVERGREET",
- "EHLO",
- "HELO",
- "STARTTLS",
- "UPGRADETLS",
+}
+
+/***********************************************************************
+ *
+ * state()
+ *
+ * This is the ONLY way to change SMTP state!
+ */
+static void state(struct connectdata *conn, smtpstate newstate)
+{
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
+ /* for debug purposes */
+ static const char * const names[] = {
+ "STOP",
+ "SERVERGREET",
+ "EHLO",
+ "HELO",
+ "STARTTLS",
+ "UPGRADETLS",
"AUTH",
"COMMAND",
- "MAIL",
- "RCPT",
- "DATA",
- "POSTDATA",
- "QUIT",
- /* LAST */
- };
-
- if(smtpc->state != newstate)
- infof(conn->data, "SMTP %p state change from %s to %s\n",
- (void *)smtpc, names[smtpc->state], names[newstate]);
-#endif
-
- smtpc->state = newstate;
-}
-
-/***********************************************************************
- *
- * smtp_perform_ehlo()
- *
- * Sends the EHLO command to not only initialise communication with the ESMTP
- * server but to also obtain a list of server side supported capabilities.
- */
-static CURLcode smtp_perform_ehlo(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-
+ "MAIL",
+ "RCPT",
+ "DATA",
+ "POSTDATA",
+ "QUIT",
+ /* LAST */
+ };
+
+ if(smtpc->state != newstate)
+ infof(conn->data, "SMTP %p state change from %s to %s\n",
+ (void *)smtpc, names[smtpc->state], names[newstate]);
+#endif
+
+ smtpc->state = newstate;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform_ehlo()
+ *
+ * Sends the EHLO command to not only initialise communication with the ESMTP
+ * server but to also obtain a list of server side supported capabilities.
+ */
+static CURLcode smtp_perform_ehlo(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+
smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */
smtpc->sasl.authused = SASL_AUTH_NONE; /* Clear the authentication mechanism
used for esmtp connections */
smtpc->tls_supported = FALSE; /* Clear the TLS capability */
smtpc->auth_supported = FALSE; /* Clear the AUTH capability */
-
- /* Send the EHLO command */
- result = Curl_pp_sendf(&smtpc->pp, "EHLO %s", smtpc->domain);
-
- if(!result)
- state(conn, SMTP_EHLO);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_perform_helo()
- *
- * Sends the HELO command to initialise communication with the SMTP server.
- */
-static CURLcode smtp_perform_helo(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-
+
+ /* Send the EHLO command */
+ result = Curl_pp_sendf(&smtpc->pp, "EHLO %s", smtpc->domain);
+
+ if(!result)
+ state(conn, SMTP_EHLO);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform_helo()
+ *
+ * Sends the HELO command to initialise communication with the SMTP server.
+ */
+static CURLcode smtp_perform_helo(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+
smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used
in smtp connections */
-
- /* Send the HELO command */
- result = Curl_pp_sendf(&smtpc->pp, "HELO %s", smtpc->domain);
-
- if(!result)
- state(conn, SMTP_HELO);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_perform_starttls()
- *
- * Sends the STLS command to start the upgrade to TLS.
- */
-static CURLcode smtp_perform_starttls(struct connectdata *conn)
-{
- /* Send the STARTTLS command */
+
+ /* Send the HELO command */
+ result = Curl_pp_sendf(&smtpc->pp, "HELO %s", smtpc->domain);
+
+ if(!result)
+ state(conn, SMTP_HELO);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform_starttls()
+ *
+ * Sends the STLS command to start the upgrade to TLS.
+ */
+static CURLcode smtp_perform_starttls(struct connectdata *conn)
+{
+ /* Send the STARTTLS command */
CURLcode result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "STARTTLS");
-
- if(!result)
- state(conn, SMTP_STARTTLS);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_perform_upgrade_tls()
- *
- * Performs the upgrade to TLS.
- */
-static CURLcode smtp_perform_upgrade_tls(struct connectdata *conn)
-{
+
+ if(!result)
+ state(conn, SMTP_STARTTLS);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform_upgrade_tls()
+ *
+ * Performs the upgrade to TLS.
+ */
+static CURLcode smtp_perform_upgrade_tls(struct connectdata *conn)
+{
/* Start the SSL connection */
- struct smtp_conn *smtpc = &conn->proto.smtpc;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
CURLcode result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET,
&smtpc->ssldone);
-
- if(!result) {
- if(smtpc->state != SMTP_UPGRADETLS)
- state(conn, SMTP_UPGRADETLS);
-
- if(smtpc->ssldone) {
- smtp_to_smtps(conn);
- result = smtp_perform_ehlo(conn);
- }
- }
-
- return result;
-}
-
-/***********************************************************************
- *
+
+ if(!result) {
+ if(smtpc->state != SMTP_UPGRADETLS)
+ state(conn, SMTP_UPGRADETLS);
+
+ if(smtpc->ssldone) {
+ smtp_to_smtps(conn);
+ result = smtp_perform_ehlo(conn);
+ }
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
* smtp_perform_auth()
- *
+ *
* Sends an AUTH command allowing the client to login with the given SASL
* authentication mechanism.
- */
+ */
static CURLcode smtp_perform_auth(struct connectdata *conn,
const char *mech,
const char *initresp)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+
if(initresp) { /* AUTH <mech> ...<crlf> */
/* Send the AUTH command with the initial response */
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s %s", mech, initresp);
- }
+ }
else {
/* Send the AUTH command */
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s", mech);
- }
-
+ }
+
return result;
}
-
+
/***********************************************************************
*
* smtp_continue_auth()
@@ -435,10 +435,10 @@ static CURLcode smtp_perform_auth(struct connectdata *conn,
static CURLcode smtp_continue_auth(struct connectdata *conn, const char *resp)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
-
+
return Curl_pp_sendf(&smtpc->pp, "%s", resp);
}
-
+
/***********************************************************************
*
* smtp_perform_authentication()
@@ -458,26 +458,26 @@ static CURLcode smtp_perform_authentication(struct connectdata *conn)
!Curl_sasl_can_authenticate(&smtpc->sasl, conn)) {
state(conn, SMTP_STOP);
return result;
- }
-
+ }
+
/* Calculate the SASL login details */
result = Curl_sasl_start(&smtpc->sasl, conn, FALSE, &progress);
- if(!result) {
+ if(!result) {
if(progress == SASL_INPROGRESS)
state(conn, SMTP_AUTH);
- else {
- /* Other mechanisms not supported */
- infof(conn->data, "No known authentication mechanisms supported!\n");
- result = CURLE_LOGIN_DENIED;
- }
- }
-
- return result;
-}
-
-/***********************************************************************
- *
+ else {
+ /* Other mechanisms not supported */
+ infof(conn->data, "No known authentication mechanisms supported!\n");
+ result = CURLE_LOGIN_DENIED;
+ }
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
* smtp_perform_command()
*
* Sends a SMTP based command.
@@ -549,25 +549,25 @@ static CURLcode smtp_perform_command(struct connectdata *conn)
/***********************************************************************
*
- * smtp_perform_mail()
- *
- * Sends an MAIL command to initiate the upload of a message.
- */
-static CURLcode smtp_perform_mail(struct connectdata *conn)
-{
- char *from = NULL;
- char *auth = NULL;
- char *size = NULL;
- CURLcode result = CURLE_OK;
+ * smtp_perform_mail()
+ *
+ * Sends an MAIL command to initiate the upload of a message.
+ */
+static CURLcode smtp_perform_mail(struct connectdata *conn)
+{
+ char *from = NULL;
+ char *auth = NULL;
+ char *size = NULL;
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
+
/* We notify the server we are sending UTF-8 data if a) it supports the
SMTPUTF8 extension and b) The mailbox contains UTF-8 charaacters, in
either the local address or host name parts. This is regardless of
whether the host name is encoded using IDN ACE */
bool utf8 = FALSE;
- /* Calculate the FROM parameter */
+ /* Calculate the FROM parameter */
if(data->set.str[STRING_MAIL_FROM]) {
char *address = NULL;
struct hostname host = { NULL, NULL, NULL, NULL };
@@ -598,13 +598,13 @@ static CURLcode smtp_perform_mail(struct connectdata *conn)
free(address);
}
else
- /* Null reverse-path, RFC-5321, sect. 3.6.3 */
- from = strdup("<>");
-
- if(!from)
- return CURLE_OUT_OF_MEMORY;
-
- /* Calculate the optional AUTH parameter */
+ /* Null reverse-path, RFC-5321, sect. 3.6.3 */
+ from = strdup("<>");
+
+ if(!from)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Calculate the optional AUTH parameter */
if(data->set.str[STRING_MAIL_AUTH] && conn->proto.smtpc.sasl.authused) {
if(data->set.str[STRING_MAIL_AUTH][0] != '\0') {
char *address = NULL;
@@ -638,17 +638,17 @@ static CURLcode smtp_perform_mail(struct connectdata *conn)
free(address);
}
- else
- /* Empty AUTH, RFC-2554, sect. 5 */
- auth = strdup("<>");
-
- if(!auth) {
+ else
+ /* Empty AUTH, RFC-2554, sect. 5 */
+ auth = strdup("<>");
+
+ if(!auth) {
free(from);
-
- return CURLE_OUT_OF_MEMORY;
- }
- }
-
+
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
+
/* Prepare the mime data if some. */
if(data->set.mimepost.kind != MIMEKIND_NONE) {
/* Use the whole structure as data. */
@@ -682,18 +682,18 @@ static CURLcode smtp_perform_mail(struct connectdata *conn)
data->state.in = (void *) &data->set.mimepost;
}
- /* Calculate the optional SIZE parameter */
+ /* Calculate the optional SIZE parameter */
if(conn->proto.smtpc.size_supported && data->state.infilesize > 0) {
size = aprintf("%" CURL_FORMAT_CURL_OFF_T, data->state.infilesize);
-
- if(!size) {
+
+ if(!size) {
free(from);
free(auth);
-
- return CURLE_OUT_OF_MEMORY;
- }
- }
-
+
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
+
/* If the mailboxes in the FROM and AUTH parameters don't include a UTF-8
based address then quickly scan through the recipient list and check if
any there do, as we need to correctly identify our support for SMTPUTF8
@@ -711,7 +711,7 @@ static CURLcode smtp_perform_mail(struct connectdata *conn)
}
}
- /* Send the MAIL command */
+ /* Send the MAIL command */
result = Curl_pp_sendf(&conn->proto.smtpc.pp,
"MAIL FROM:%s%s%s%s%s%s",
from, /* Mandatory */
@@ -721,32 +721,32 @@ static CURLcode smtp_perform_mail(struct connectdata *conn)
size ? size : "", /* */
utf8 ? " SMTPUTF8" /* Internationalised mailbox */
: ""); /* included in our envelope */
-
+
free(from);
free(auth);
free(size);
-
- if(!result)
- state(conn, SMTP_MAIL);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_perform_rcpt_to()
- *
- * Sends a RCPT TO command for a given recipient as part of the message upload
- * process.
- */
-static CURLcode smtp_perform_rcpt_to(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+
+ if(!result)
+ state(conn, SMTP_MAIL);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform_rcpt_to()
+ *
+ * Sends a RCPT TO command for a given recipient as part of the message upload
+ * process.
+ */
+static CURLcode smtp_perform_rcpt_to(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
char *address = NULL;
struct hostname host = { NULL, NULL, NULL, NULL };
-
+
/* Parse the recipient mailbox into the local address and host name parts,
converting the host name to an IDN A-label if necessary */
result = smtp_parse_address(conn, smtp->rcpt->data,
@@ -754,7 +754,7 @@ static CURLcode smtp_perform_rcpt_to(struct connectdata *conn)
if(result)
return result;
- /* Send the RCPT TO command */
+ /* Send the RCPT TO command */
if(host.name)
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s@%s>", address,
host.name);
@@ -768,103 +768,103 @@ static CURLcode smtp_perform_rcpt_to(struct connectdata *conn)
if(!result)
state(conn, SMTP_RCPT);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_perform_quit()
- *
- * Performs the quit action prior to sclose() being called.
- */
-static CURLcode smtp_perform_quit(struct connectdata *conn)
-{
- /* Send the QUIT command */
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform_quit()
+ *
+ * Performs the quit action prior to sclose() being called.
+ */
+static CURLcode smtp_perform_quit(struct connectdata *conn)
+{
+ /* Send the QUIT command */
CURLcode result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "QUIT");
-
- if(!result)
- state(conn, SMTP_QUIT);
-
- return result;
-}
-
-/* For the initial server greeting */
-static CURLcode smtp_state_servergreet_resp(struct connectdata *conn,
- int smtpcode,
- smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+
+ if(!result)
+ state(conn, SMTP_QUIT);
+
+ return result;
+}
+
+/* For the initial server greeting */
+static CURLcode smtp_state_servergreet_resp(struct connectdata *conn,
+ int smtpcode,
+ smtpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(smtpcode/100 != 2) {
- failf(data, "Got unexpected smtp-server response: %d", smtpcode);
+
+ (void)instate; /* no use for this yet */
+
+ if(smtpcode/100 != 2) {
+ failf(data, "Got unexpected smtp-server response: %d", smtpcode);
result = CURLE_WEIRD_SERVER_REPLY;
- }
- else
- result = smtp_perform_ehlo(conn);
-
- return result;
-}
-
-/* For STARTTLS responses */
-static CURLcode smtp_state_starttls_resp(struct connectdata *conn,
- int smtpcode,
- smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+ else
+ result = smtp_perform_ehlo(conn);
+
+ return result;
+}
+
+/* For STARTTLS responses */
+static CURLcode smtp_state_starttls_resp(struct connectdata *conn,
+ int smtpcode,
+ smtpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(smtpcode != 220) {
- if(data->set.use_ssl != CURLUSESSL_TRY) {
+
+ (void)instate; /* no use for this yet */
+
+ if(smtpcode != 220) {
+ if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied, code %d", smtpcode);
- result = CURLE_USE_SSL_FAILED;
- }
- else
+ result = CURLE_USE_SSL_FAILED;
+ }
+ else
result = smtp_perform_authentication(conn);
- }
- else
- result = smtp_perform_upgrade_tls(conn);
-
- return result;
-}
-
-/* For EHLO responses */
-static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode,
- smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+ else
+ result = smtp_perform_upgrade_tls(conn);
+
+ return result;
+}
+
+/* For EHLO responses */
+static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode,
+ smtpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
const char *line = data->state.buffer;
size_t len = strlen(line);
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
if(smtpcode/100 != 2 && smtpcode != 1) {
if(data->set.use_ssl <= CURLUSESSL_TRY || conn->ssl[FIRSTSOCKET].use)
- result = smtp_perform_helo(conn);
- else {
- failf(data, "Remote access denied: %d", smtpcode);
- result = CURLE_REMOTE_ACCESS_DENIED;
- }
- }
+ result = smtp_perform_helo(conn);
+ else {
+ failf(data, "Remote access denied: %d", smtpcode);
+ result = CURLE_REMOTE_ACCESS_DENIED;
+ }
+ }
else if(len >= 4) {
line += 4;
len -= 4;
-
+
/* Does the server support the STARTTLS capability? */
if(len >= 8 && !memcmp(line, "STARTTLS", 8))
smtpc->tls_supported = TRUE;
-
+
/* Does the server support the SIZE capability? */
else if(len >= 4 && !memcmp(line, "SIZE", 4))
smtpc->size_supported = TRUE;
-
+
/* Does the server support the UTF-8 capability? */
else if(len >= 8 && !memcmp(line, "SMTPUTF8", 8))
smtpc->utf8_supported = TRUE;
@@ -872,44 +872,44 @@ static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode,
/* Does the server support authentication? */
else if(len >= 5 && !memcmp(line, "AUTH ", 5)) {
smtpc->auth_supported = TRUE;
-
+
/* Advance past the AUTH keyword */
line += 5;
len -= 5;
-
+
/* Loop through the data line */
for(;;) {
size_t llen;
size_t wordlen;
unsigned int mechbit;
-
+
while(len &&
(*line == ' ' || *line == '\t' ||
*line == '\r' || *line == '\n')) {
-
+
line++;
len--;
}
-
+
if(!len)
break;
-
+
/* Extract the word */
for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
line[wordlen] != '\t' && line[wordlen] != '\r' &&
line[wordlen] != '\n';)
wordlen++;
-
+
/* Test the word for a matching authentication mechanism */
mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
if(mechbit && llen == wordlen)
smtpc->sasl.authmechs |= mechbit;
-
+
line += wordlen;
len -= wordlen;
- }
- }
-
+ }
+ }
+
if(smtpcode != 1) {
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested */
@@ -923,51 +923,51 @@ static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode,
failf(data, "STARTTLS not supported.");
result = CURLE_USE_SSL_FAILED;
}
- }
+ }
else
result = smtp_perform_authentication(conn);
- }
- }
+ }
+ }
else {
failf(data, "Unexpectedly short EHLO response");
result = CURLE_WEIRD_SERVER_REPLY;
}
-
- return result;
-}
-
+
+ return result;
+}
+
/* For HELO responses */
static CURLcode smtp_state_helo_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
if(smtpcode/100 != 2) {
failf(data, "Remote access denied: %d", smtpcode);
result = CURLE_REMOTE_ACCESS_DENIED;
- }
+ }
else
/* End of connect phase */
state(conn, SMTP_STOP);
-
- return result;
-}
-
+
+ return result;
+}
+
/* For SASL authentication responses */
static CURLcode smtp_state_auth_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct smtp_conn *smtpc = &conn->proto.smtpc;
saslprogress progress;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
result = Curl_sasl_continue(&smtpc->sasl, conn, smtpcode, &progress);
if(!result)
switch(progress) {
@@ -980,40 +980,40 @@ static CURLcode smtp_state_auth_resp(struct connectdata *conn,
break;
default:
break;
- }
-
- return result;
-}
-
+ }
+
+ return result;
+}
+
/* For command responses */
static CURLcode smtp_state_command_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
char *line = data->state.buffer;
size_t len = strlen(line);
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
if((smtp->rcpt && smtpcode/100 != 2 && smtpcode != 553 && smtpcode != 1) ||
(!smtp->rcpt && smtpcode/100 != 2 && smtpcode != 1)) {
failf(data, "Command failed: %d", smtpcode);
result = CURLE_RECV_ERROR;
- }
- else {
+ }
+ else {
/* Temporarily add the LF character back and send as body to the client */
if(!data->set.opt_no_body) {
line[len] = '\n';
result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
line[len] = '\0';
- }
-
+ }
+
if(smtpcode != 1) {
if(smtp->rcpt) {
smtp->rcpt = smtp->rcpt->next;
-
+
if(smtp->rcpt) {
/* Send the next command */
result = smtp_perform_command(conn);
@@ -1021,48 +1021,48 @@ static CURLcode smtp_state_command_resp(struct connectdata *conn, int smtpcode,
else
/* End of DO phase */
state(conn, SMTP_STOP);
- }
+ }
else
/* End of DO phase */
state(conn, SMTP_STOP);
- }
- }
-
- return result;
-}
-
-/* For MAIL responses */
-static CURLcode smtp_state_mail_resp(struct connectdata *conn, int smtpcode,
- smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+ }
+ }
+
+ return result;
+}
+
+/* For MAIL responses */
+static CURLcode smtp_state_mail_resp(struct connectdata *conn, int smtpcode,
+ smtpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(smtpcode/100 != 2) {
- failf(data, "MAIL failed: %d", smtpcode);
- result = CURLE_SEND_ERROR;
- }
+
+ (void)instate; /* no use for this yet */
+
+ if(smtpcode/100 != 2) {
+ failf(data, "MAIL failed: %d", smtpcode);
+ result = CURLE_SEND_ERROR;
+ }
else
/* Start the RCPT TO command */
- result = smtp_perform_rcpt_to(conn);
-
- return result;
-}
-
-/* For RCPT responses */
-static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode,
- smtpstate instate)
-{
- CURLcode result = CURLE_OK;
+ result = smtp_perform_rcpt_to(conn);
+
+ return result;
+}
+
+/* For RCPT responses */
+static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode,
+ smtpstate instate)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
bool is_smtp_err = FALSE;
bool is_smtp_blocking_err = FALSE;
-
- (void)instate; /* no use for this yet */
-
+
+ (void)instate; /* no use for this yet */
+
is_smtp_err = (smtpcode/100 != 2) ? TRUE : FALSE;
/* If there's multiple RCPT TO to be issued, it's possible to ignore errors
@@ -1079,8 +1079,8 @@ static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode,
failf(data, "RCPT failed: %d", smtpcode);
result = CURLE_SEND_ERROR;
}
- }
- else {
+ }
+ else {
/* Some RCPT TO commands have succeeded. */
smtp->rcpt_had_ok = TRUE;
}
@@ -1090,7 +1090,7 @@ static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode,
if(smtp->rcpt)
/* Send the next RCPT TO command */
- result = smtp_perform_rcpt_to(conn);
+ result = smtp_perform_rcpt_to(conn);
else {
/* We weren't able to issue a successful RCPT TO command while going
over recipients (potentially multiple). Sending back last error. */
@@ -1101,286 +1101,286 @@ static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode,
else {
/* Send the DATA command */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "DATA");
-
+
if(!result)
state(conn, SMTP_DATA);
}
- }
- }
-
- return result;
-}
-
-/* For DATA response */
-static CURLcode smtp_state_data_resp(struct connectdata *conn, int smtpcode,
- smtpstate instate)
-{
+ }
+ }
+
+ return result;
+}
+
+/* For DATA response */
+static CURLcode smtp_state_data_resp(struct connectdata *conn, int smtpcode,
+ smtpstate instate)
+{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- (void)instate; /* no use for this yet */
-
- if(smtpcode != 354) {
+
+ (void)instate; /* no use for this yet */
+
+ if(smtpcode != 354) {
failf(data, "DATA failed: %d", smtpcode);
result = CURLE_SEND_ERROR;
- }
+ }
else {
/* Set the progress upload size */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
-
+
/* SMTP upload */
Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET);
-
+
/* End of DO phase */
state(conn, SMTP_STOP);
}
-
+
return result;
-}
-
-/* For POSTDATA responses, which are received after the entire DATA
- part has been sent to the server */
-static CURLcode smtp_state_postdata_resp(struct connectdata *conn,
- int smtpcode,
- smtpstate instate)
-{
- CURLcode result = CURLE_OK;
-
- (void)instate; /* no use for this yet */
-
- if(smtpcode != 250)
- result = CURLE_RECV_ERROR;
-
- /* End of DONE phase */
- state(conn, SMTP_STOP);
-
- return result;
-}
-
-static CURLcode smtp_statemach_act(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- curl_socket_t sock = conn->sock[FIRSTSOCKET];
+}
+
+/* For POSTDATA responses, which are received after the entire DATA
+ part has been sent to the server */
+static CURLcode smtp_state_postdata_resp(struct connectdata *conn,
+ int smtpcode,
+ smtpstate instate)
+{
+ CURLcode result = CURLE_OK;
+
+ (void)instate; /* no use for this yet */
+
+ if(smtpcode != 250)
+ result = CURLE_RECV_ERROR;
+
+ /* End of DONE phase */
+ state(conn, SMTP_STOP);
+
+ return result;
+}
+
+static CURLcode smtp_statemach_act(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct Curl_easy *data = conn->data;
- int smtpcode;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
- struct pingpong *pp = &smtpc->pp;
- size_t nread = 0;
-
- /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */
- if(smtpc->state == SMTP_UPGRADETLS)
- return smtp_perform_upgrade_tls(conn);
-
- /* Flush any data that needs to be sent */
- if(pp->sendleft)
- return Curl_pp_flushsend(pp);
-
+ int smtpcode;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+ struct pingpong *pp = &smtpc->pp;
+ size_t nread = 0;
+
+ /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */
+ if(smtpc->state == SMTP_UPGRADETLS)
+ return smtp_perform_upgrade_tls(conn);
+
+ /* Flush any data that needs to be sent */
+ if(pp->sendleft)
+ return Curl_pp_flushsend(pp);
+
do {
/* Read the response from the server */
result = Curl_pp_readresp(sock, pp, &smtpcode, &nread);
if(result)
return result;
-
+
/* Store the latest response for later retrieval if necessary */
if(smtpc->state != SMTP_QUIT && smtpcode != 1)
data->info.httpcode = smtpcode;
-
+
if(!smtpcode)
break;
- /* We have now received a full SMTP server response */
- switch(smtpc->state) {
- case SMTP_SERVERGREET:
- result = smtp_state_servergreet_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_EHLO:
- result = smtp_state_ehlo_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_HELO:
- result = smtp_state_helo_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_STARTTLS:
- result = smtp_state_starttls_resp(conn, smtpcode, smtpc->state);
- break;
-
+ /* We have now received a full SMTP server response */
+ switch(smtpc->state) {
+ case SMTP_SERVERGREET:
+ result = smtp_state_servergreet_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_EHLO:
+ result = smtp_state_ehlo_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_HELO:
+ result = smtp_state_helo_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_STARTTLS:
+ result = smtp_state_starttls_resp(conn, smtpcode, smtpc->state);
+ break;
+
case SMTP_AUTH:
result = smtp_state_auth_resp(conn, smtpcode, smtpc->state);
- break;
-
+ break;
+
case SMTP_COMMAND:
result = smtp_state_command_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_MAIL:
- result = smtp_state_mail_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_RCPT:
- result = smtp_state_rcpt_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_DATA:
- result = smtp_state_data_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_POSTDATA:
- result = smtp_state_postdata_resp(conn, smtpcode, smtpc->state);
- break;
-
- case SMTP_QUIT:
- /* fallthrough, just stop! */
- default:
- /* internal error */
- state(conn, SMTP_STOP);
- break;
- }
+ break;
+
+ case SMTP_MAIL:
+ result = smtp_state_mail_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_RCPT:
+ result = smtp_state_rcpt_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_DATA:
+ result = smtp_state_data_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_POSTDATA:
+ result = smtp_state_postdata_resp(conn, smtpcode, smtpc->state);
+ break;
+
+ case SMTP_QUIT:
+ /* fallthrough, just stop! */
+ default:
+ /* internal error */
+ state(conn, SMTP_STOP);
+ break;
+ }
} while(!result && smtpc->state != SMTP_STOP && Curl_pp_moredata(pp));
-
- return result;
-}
-
-/* Called repeatedly until done from multi.c */
-static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-
- if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone) {
- result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
- if(result || !smtpc->ssldone)
- return result;
- }
-
+
+ return result;
+}
+
+/* Called repeatedly until done from multi.c */
+static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+
+ if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone) {
+ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
+ if(result || !smtpc->ssldone)
+ return result;
+ }
+
result = Curl_pp_statemach(&smtpc->pp, FALSE, FALSE);
- *done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE;
-
- return result;
-}
-
+ *done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE;
+
+ return result;
+}
+
static CURLcode smtp_block_statemach(struct connectdata *conn,
bool disconnecting)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-
- while(smtpc->state != SMTP_STOP && !result)
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+
+ while(smtpc->state != SMTP_STOP && !result)
result = Curl_pp_statemach(&smtpc->pp, TRUE, disconnecting);
-
- return result;
-}
-
+
+ return result;
+}
+
/* Allocate and initialize the SMTP struct for the current Curl_easy if
- required */
-static CURLcode smtp_init(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+ required */
+static CURLcode smtp_init(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- struct SMTP *smtp;
-
+ struct SMTP *smtp;
+
smtp = data->req.p.smtp = calloc(sizeof(struct SMTP), 1);
- if(!smtp)
- result = CURLE_OUT_OF_MEMORY;
-
- return result;
-}
-
-/* For the SMTP "protocol connect" and "doing" phases only */
+ if(!smtp)
+ result = CURLE_OUT_OF_MEMORY;
+
+ return result;
+}
+
+/* For the SMTP "protocol connect" and "doing" phases only */
static int smtp_getsock(struct connectdata *conn, curl_socket_t *socks)
-{
+{
return Curl_pp_getsock(&conn->proto.smtpc.pp, socks);
-}
-
-/***********************************************************************
- *
- * smtp_connect()
- *
- * This function should do everything that is to be considered a part of
- * the connection phase.
- *
- * The variable pointed to by 'done' will be TRUE if the protocol-layer
- * connect phase is done when this function returns, or FALSE if not.
- */
-static CURLcode smtp_connect(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
- struct pingpong *pp = &smtpc->pp;
-
- *done = FALSE; /* default to not done yet */
-
- /* We always support persistent connections in SMTP */
+}
+
+/***********************************************************************
+ *
+ * smtp_connect()
+ *
+ * This function should do everything that is to be considered a part of
+ * the connection phase.
+ *
+ * The variable pointed to by 'done' will be TRUE if the protocol-layer
+ * connect phase is done when this function returns, or FALSE if not.
+ */
+static CURLcode smtp_connect(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+ struct pingpong *pp = &smtpc->pp;
+
+ *done = FALSE; /* default to not done yet */
+
+ /* We always support persistent connections in SMTP */
connkeep(conn, "SMTP default");
-
- /* Set the default response time-out */
- pp->response_time = RESP_TIMEOUT;
- pp->statemach_act = smtp_statemach_act;
- pp->endofresp = smtp_endofresp;
- pp->conn = conn;
-
+
+ /* Set the default response time-out */
+ pp->response_time = RESP_TIMEOUT;
+ pp->statemach_act = smtp_statemach_act;
+ pp->endofresp = smtp_endofresp;
+ pp->conn = conn;
+
/* Initialize the SASL storage */
Curl_sasl_init(&smtpc->sasl, &saslsmtp);
-
- /* Initialise the pingpong layer */
+
+ /* Initialise the pingpong layer */
Curl_pp_setup(pp);
- Curl_pp_init(pp);
-
- /* Parse the URL options */
- result = smtp_parse_url_options(conn);
- if(result)
- return result;
-
- /* Parse the URL path */
- result = smtp_parse_url_path(conn);
- if(result)
- return result;
-
- /* Start off waiting for the server greeting response */
- state(conn, SMTP_SERVERGREET);
-
- result = smtp_multi_statemach(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_done()
- *
- * The DONE function. This does what needs to be done after a single DO has
- * performed.
- *
- * Input argument is already checked for validity.
- */
-static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
- bool premature)
-{
- CURLcode result = CURLE_OK;
+ Curl_pp_init(pp);
+
+ /* Parse the URL options */
+ result = smtp_parse_url_options(conn);
+ if(result)
+ return result;
+
+ /* Parse the URL path */
+ result = smtp_parse_url_path(conn);
+ if(result)
+ return result;
+
+ /* Start off waiting for the server greeting response */
+ state(conn, SMTP_SERVERGREET);
+
+ result = smtp_multi_statemach(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_done()
+ *
+ * The DONE function. This does what needs to be done after a single DO has
+ * performed.
+ *
+ * Input argument is already checked for validity.
+ */
+static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
- struct pingpong *pp = &conn->proto.smtpc.pp;
+ struct pingpong *pp = &conn->proto.smtpc.pp;
char *eob;
- ssize_t len;
- ssize_t bytes_written;
-
- (void)premature;
-
+ ssize_t len;
+ ssize_t bytes_written;
+
+ (void)premature;
+
if(!smtp || !pp->conn)
- return CURLE_OK;
-
+ return CURLE_OK;
+
/* Cleanup our per-request based variables */
Curl_safefree(smtp->custom);
- if(status) {
+ if(status) {
connclose(conn, "SMTP done with bad status"); /* marked for closure */
- result = status; /* use the already set error code */
- }
+ result = status; /* use the already set error code */
+ }
else if(!data->set.connect_only && data->set.mail_rcpt &&
(data->set.upload || data->set.mimepost.kind)) {
- /* Calculate the EOB taking into account any terminating CRLF from the
- previous line of the email or the CRLF of the DATA command when there
+ /* Calculate the EOB taking into account any terminating CRLF from the
+ previous line of the email or the CRLF of the DATA command when there
is "no mail data". RFC-5321, sect. 4.1.1.4.
Note: As some SSL backends, such as OpenSSL, will cause Curl_write() to
@@ -1390,72 +1390,72 @@ static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
if(smtp->trailing_crlf || !conn->data->state.infilesize) {
eob = strdup(&SMTP_EOB[2]);
len = SMTP_EOB_LEN - 2;
- }
+ }
else {
eob = strdup(SMTP_EOB);
len = SMTP_EOB_LEN;
}
-
+
if(!eob)
return CURLE_OUT_OF_MEMORY;
- /* Send the end of block data */
- result = Curl_write(conn, conn->writesockfd, eob, len, &bytes_written);
+ /* Send the end of block data */
+ result = Curl_write(conn, conn->writesockfd, eob, len, &bytes_written);
if(result) {
free(eob);
- return result;
+ return result;
}
-
- if(bytes_written != len) {
- /* The whole chunk was not sent so keep it around and adjust the
- pingpong structure accordingly */
+
+ if(bytes_written != len) {
+ /* The whole chunk was not sent so keep it around and adjust the
+ pingpong structure accordingly */
pp->sendthis = eob;
- pp->sendsize = len;
- pp->sendleft = len - bytes_written;
- }
+ pp->sendsize = len;
+ pp->sendleft = len - bytes_written;
+ }
else {
- /* Successfully sent so adjust the response timeout relative to now */
+ /* Successfully sent so adjust the response timeout relative to now */
pp->response = Curl_now();
-
+
free(eob);
}
- state(conn, SMTP_POSTDATA);
-
+ state(conn, SMTP_POSTDATA);
+
/* Run the state-machine */
result = smtp_block_statemach(conn, FALSE);
- }
-
- /* Clear the transfer mode for the next request */
- smtp->transfer = FTPTRANSFER_BODY;
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_perform()
- *
+ }
+
+ /* Clear the transfer mode for the next request */
+ smtp->transfer = FTPTRANSFER_BODY;
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_perform()
+ *
* This is the actual DO function for SMTP. Transfer a mail, send a command
* or get some data according to the options previously setup.
- */
-static CURLcode smtp_perform(struct connectdata *conn, bool *connected,
- bool *dophase_done)
-{
- /* This is SMTP and no proxy */
- CURLcode result = CURLE_OK;
+ */
+static CURLcode smtp_perform(struct connectdata *conn, bool *connected,
+ bool *dophase_done)
+{
+ /* This is SMTP and no proxy */
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
-
- DEBUGF(infof(conn->data, "DO phase starts\n"));
-
+
+ DEBUGF(infof(conn->data, "DO phase starts\n"));
+
if(data->set.opt_no_body) {
- /* Requested no body means no transfer */
- smtp->transfer = FTPTRANSFER_INFO;
- }
-
- *dophase_done = FALSE; /* not done yet */
-
+ /* Requested no body means no transfer */
+ smtp->transfer = FTPTRANSFER_INFO;
+ }
+
+ *dophase_done = FALSE; /* not done yet */
+
/* Store the first recipient (or NULL if not specified) */
smtp->rcpt = data->set.mail_rcpt;
@@ -1470,7 +1470,7 @@ static CURLcode smtp_perform(struct connectdata *conn, bool *connected,
smtp->trailing_crlf = TRUE;
smtp->eob = 2;
- /* Start the first command in the DO phase */
+ /* Start the first command in the DO phase */
if((data->set.upload || data->set.mimepost.kind) && data->set.mail_rcpt)
/* MAIL transfer */
result = smtp_perform_mail(conn);
@@ -1478,224 +1478,224 @@ static CURLcode smtp_perform(struct connectdata *conn, bool *connected,
/* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */
result = smtp_perform_command(conn);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
/* Run the state-machine */
- result = smtp_multi_statemach(conn, dophase_done);
-
- *connected = conn->bits.tcpconnect[FIRSTSOCKET];
-
- if(*dophase_done)
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_do()
- *
- * This function is registered as 'curl_do' function. It decodes the path
- * parts etc as a wrapper to the actual DO function (smtp_perform).
- *
- * The input argument is already checked for validity.
- */
-static CURLcode smtp_do(struct connectdata *conn, bool *done)
-{
- CURLcode result = CURLE_OK;
-
- *done = FALSE; /* default to false */
-
+ result = smtp_multi_statemach(conn, dophase_done);
+
+ *connected = conn->bits.tcpconnect[FIRSTSOCKET];
+
+ if(*dophase_done)
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_do()
+ *
+ * This function is registered as 'curl_do' function. It decodes the path
+ * parts etc as a wrapper to the actual DO function (smtp_perform).
+ *
+ * The input argument is already checked for validity.
+ */
+static CURLcode smtp_do(struct connectdata *conn, bool *done)
+{
+ CURLcode result = CURLE_OK;
+
+ *done = FALSE; /* default to false */
+
/* Parse the custom request */
result = smtp_parse_custom_request(conn);
if(result)
return result;
- result = smtp_regular_transfer(conn, done);
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_disconnect()
- *
- * Disconnect from an SMTP server. Cleanup protocol-specific per-connection
- * resources. BLOCKING.
- */
+ result = smtp_regular_transfer(conn, done);
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_disconnect()
+ *
+ * Disconnect from an SMTP server. Cleanup protocol-specific per-connection
+ * resources. BLOCKING.
+ */
static CURLcode smtp_disconnect(struct connectdata *conn, bool dead_connection)
-{
- struct smtp_conn *smtpc = &conn->proto.smtpc;
-
- /* We cannot send quit unconditionally. If this connection is stale or
- bad in any way, sending quit and waiting around here will make the
- disconnect wait in vain and cause more problems than we need to. */
-
- /* The SMTP session may or may not have been allocated/setup at this
- point! */
+{
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
+
+ /* We cannot send quit unconditionally. If this connection is stale or
+ bad in any way, sending quit and waiting around here will make the
+ disconnect wait in vain and cause more problems than we need to. */
+
+ /* The SMTP session may or may not have been allocated/setup at this
+ point! */
if(!dead_connection && smtpc->pp.conn && smtpc->pp.conn->bits.protoconnstart)
- if(!smtp_perform_quit(conn))
+ if(!smtp_perform_quit(conn))
(void)smtp_block_statemach(conn, TRUE); /* ignore errors on QUIT */
-
- /* Disconnect from the server */
- Curl_pp_disconnect(&smtpc->pp);
-
- /* Cleanup the SASL module */
+
+ /* Disconnect from the server */
+ Curl_pp_disconnect(&smtpc->pp);
+
+ /* Cleanup the SASL module */
Curl_sasl_cleanup(conn, smtpc->sasl.authused);
-
- /* Cleanup our connection based variables */
- Curl_safefree(smtpc->domain);
-
- return CURLE_OK;
-}
-
-/* Call this when the DO phase has completed */
-static CURLcode smtp_dophase_done(struct connectdata *conn, bool connected)
-{
+
+ /* Cleanup our connection based variables */
+ Curl_safefree(smtpc->domain);
+
+ return CURLE_OK;
+}
+
+/* Call this when the DO phase has completed */
+static CURLcode smtp_dophase_done(struct connectdata *conn, bool connected)
+{
struct SMTP *smtp = conn->data->req.p.smtp;
-
- (void)connected;
-
- if(smtp->transfer != FTPTRANSFER_BODY)
- /* no data to transfer */
+
+ (void)connected;
+
+ if(smtp->transfer != FTPTRANSFER_BODY)
+ /* no data to transfer */
Curl_setup_transfer(conn->data, -1, -1, FALSE, -1);
-
- return CURLE_OK;
-}
-
-/* Called from multi.c while DOing */
-static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done)
-{
- CURLcode result = smtp_multi_statemach(conn, dophase_done);
-
- if(result)
- DEBUGF(infof(conn->data, "DO phase failed\n"));
- else if(*dophase_done) {
- result = smtp_dophase_done(conn, FALSE /* not connected */);
-
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_regular_transfer()
- *
- * The input argument is already checked for validity.
- *
- * Performs all commands done before a regular transfer between a local and a
- * remote host.
- */
-static CURLcode smtp_regular_transfer(struct connectdata *conn,
- bool *dophase_done)
-{
- CURLcode result = CURLE_OK;
- bool connected = FALSE;
+
+ return CURLE_OK;
+}
+
+/* Called from multi.c while DOing */
+static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done)
+{
+ CURLcode result = smtp_multi_statemach(conn, dophase_done);
+
+ if(result)
+ DEBUGF(infof(conn->data, "DO phase failed\n"));
+ else if(*dophase_done) {
+ result = smtp_dophase_done(conn, FALSE /* not connected */);
+
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_regular_transfer()
+ *
+ * The input argument is already checked for validity.
+ *
+ * Performs all commands done before a regular transfer between a local and a
+ * remote host.
+ */
+static CURLcode smtp_regular_transfer(struct connectdata *conn,
+ bool *dophase_done)
+{
+ CURLcode result = CURLE_OK;
+ bool connected = FALSE;
struct Curl_easy *data = conn->data;
-
- /* Make sure size is unknown at this point */
- data->req.size = -1;
-
- /* Set the progress data */
- Curl_pgrsSetUploadCounter(data, 0);
- Curl_pgrsSetDownloadCounter(data, 0);
+
+ /* Make sure size is unknown at this point */
+ data->req.size = -1;
+
+ /* Set the progress data */
+ Curl_pgrsSetUploadCounter(data, 0);
+ Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, -1);
Curl_pgrsSetDownloadSize(data, -1);
-
- /* Carry out the perform */
- result = smtp_perform(conn, &connected, dophase_done);
-
- /* Perform post DO phase operations if necessary */
- if(!result && *dophase_done)
- result = smtp_dophase_done(conn, connected);
-
- return result;
-}
-
-static CURLcode smtp_setup_connection(struct connectdata *conn)
-{
- CURLcode result;
-
+
+ /* Carry out the perform */
+ result = smtp_perform(conn, &connected, dophase_done);
+
+ /* Perform post DO phase operations if necessary */
+ if(!result && *dophase_done)
+ result = smtp_dophase_done(conn, connected);
+
+ return result;
+}
+
+static CURLcode smtp_setup_connection(struct connectdata *conn)
+{
+ CURLcode result;
+
/* Clear the TLS upgraded flag */
conn->bits.tls_upgraded = FALSE;
-
- /* Initialise the SMTP layer */
- result = smtp_init(conn);
- if(result)
- return result;
-
- return CURLE_OK;
-}
-
-/***********************************************************************
- *
- * smtp_parse_url_options()
- *
- * Parse the URL login options.
- */
-static CURLcode smtp_parse_url_options(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
+
+ /* Initialise the SMTP layer */
+ result = smtp_init(conn);
+ if(result)
+ return result;
+
+ return CURLE_OK;
+}
+
+/***********************************************************************
+ *
+ * smtp_parse_url_options()
+ *
+ * Parse the URL login options.
+ */
+static CURLcode smtp_parse_url_options(struct connectdata *conn)
+{
+ CURLcode result = CURLE_OK;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
const char *ptr = conn->options;
-
+
smtpc->sasl.resetprefs = TRUE;
while(!result && ptr && *ptr) {
- const char *key = ptr;
+ const char *key = ptr;
const char *value;
-
- while(*ptr && *ptr != '=')
+
+ while(*ptr && *ptr != '=')
ptr++;
-
+
value = ptr + 1;
-
+
while(*ptr && *ptr != ';')
ptr++;
if(strncasecompare(key, "AUTH=", 5))
result = Curl_sasl_parse_url_auth_option(&smtpc->sasl,
value, ptr - value);
- else
- result = CURLE_URL_MALFORMAT;
+ else
+ result = CURLE_URL_MALFORMAT;
if(*ptr == ';')
ptr++;
- }
-
- return result;
-}
-
-/***********************************************************************
- *
- * smtp_parse_url_path()
- *
- * Parse the URL path into separate path components.
- */
-static CURLcode smtp_parse_url_path(struct connectdata *conn)
-{
- /* The SMTP struct is already initialised in smtp_connect() */
+ }
+
+ return result;
+}
+
+/***********************************************************************
+ *
+ * smtp_parse_url_path()
+ *
+ * Parse the URL path into separate path components.
+ */
+static CURLcode smtp_parse_url_path(struct connectdata *conn)
+{
+ /* The SMTP struct is already initialised in smtp_connect() */
struct Curl_easy *data = conn->data;
- struct smtp_conn *smtpc = &conn->proto.smtpc;
+ struct smtp_conn *smtpc = &conn->proto.smtpc;
const char *path = &data->state.up.path[1]; /* skip leading path */
- char localhost[HOSTNAME_MAX + 1];
-
- /* Calculate the path if necessary */
- if(!*path) {
- if(!Curl_gethostname(localhost, sizeof(localhost)))
- path = localhost;
- else
- path = "localhost";
- }
-
- /* URL decode the path and use it as the domain in our EHLO */
+ char localhost[HOSTNAME_MAX + 1];
+
+ /* Calculate the path if necessary */
+ if(!*path) {
+ if(!Curl_gethostname(localhost, sizeof(localhost)))
+ path = localhost;
+ else
+ path = "localhost";
+ }
+
+ /* URL decode the path and use it as the domain in our EHLO */
return Curl_urldecode(conn->data, path, 0, &smtpc->domain, NULL,
REJECT_CTRL);
-}
-
+}
+
/***********************************************************************
*
* smtp_parse_custom_request()
@@ -1703,7 +1703,7 @@ static CURLcode smtp_parse_url_path(struct connectdata *conn)
* Parse the custom request.
*/
static CURLcode smtp_parse_custom_request(struct connectdata *conn)
-{
+{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
@@ -1790,103 +1790,103 @@ static CURLcode smtp_parse_address(struct connectdata *conn, const char *fqma,
CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread)
{
- /* When sending a SMTP payload we must detect CRLF. sequences making sure
- they are sent as CRLF.. instead, as a . on the beginning of a line will
- be deleted by the server when not part of an EOB terminator and a
- genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of
- data by the server
- */
- ssize_t i;
- ssize_t si;
+ /* When sending a SMTP payload we must detect CRLF. sequences making sure
+ they are sent as CRLF.. instead, as a . on the beginning of a line will
+ be deleted by the server when not part of an EOB terminator and a
+ genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of
+ data by the server
+ */
+ ssize_t i;
+ ssize_t si;
struct Curl_easy *data = conn->data;
struct SMTP *smtp = data->req.p.smtp;
char *scratch = data->state.scratch;
char *newscratch = NULL;
char *oldscratch = NULL;
size_t eob_sent;
-
+
/* Do we need to allocate a scratch buffer? */
if(!scratch || data->set.crlf) {
oldscratch = scratch;
-
+
scratch = newscratch = malloc(2 * data->set.upload_buffer_size);
if(!newscratch) {
failf(data, "Failed to alloc scratch buffer!");
- return CURLE_OUT_OF_MEMORY;
- }
- }
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
DEBUGASSERT(data->set.upload_buffer_size >= (size_t)nread);
-
+
/* Have we already sent part of the EOB? */
eob_sent = smtp->eob;
- /* This loop can be improved by some kind of Boyer-Moore style of
- approach but that is saved for later... */
- for(i = 0, si = 0; i < nread; i++) {
- if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) {
- smtp->eob++;
-
- /* Is the EOB potentially the terminating CRLF? */
- if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob)
- smtp->trailing_crlf = TRUE;
- else
- smtp->trailing_crlf = FALSE;
- }
- else if(smtp->eob) {
- /* A previous substring matched so output that first */
+ /* This loop can be improved by some kind of Boyer-Moore style of
+ approach but that is saved for later... */
+ for(i = 0, si = 0; i < nread; i++) {
+ if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) {
+ smtp->eob++;
+
+ /* Is the EOB potentially the terminating CRLF? */
+ if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob)
+ smtp->trailing_crlf = TRUE;
+ else
+ smtp->trailing_crlf = FALSE;
+ }
+ else if(smtp->eob) {
+ /* A previous substring matched so output that first */
memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent);
si += smtp->eob - eob_sent;
-
- /* Then compare the first byte */
- if(SMTP_EOB[0] == data->req.upload_fromhere[i])
- smtp->eob = 1;
- else
- smtp->eob = 0;
-
+
+ /* Then compare the first byte */
+ if(SMTP_EOB[0] == data->req.upload_fromhere[i])
+ smtp->eob = 1;
+ else
+ smtp->eob = 0;
+
eob_sent = 0;
- /* Reset the trailing CRLF flag as there was more data */
- smtp->trailing_crlf = FALSE;
- }
-
- /* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */
- if(SMTP_EOB_FIND_LEN == smtp->eob) {
- /* Copy the replacement data to the target buffer */
+ /* Reset the trailing CRLF flag as there was more data */
+ smtp->trailing_crlf = FALSE;
+ }
+
+ /* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */
+ if(SMTP_EOB_FIND_LEN == smtp->eob) {
+ /* Copy the replacement data to the target buffer */
memcpy(&scratch[si], &SMTP_EOB_REPL[eob_sent],
SMTP_EOB_REPL_LEN - eob_sent);
si += SMTP_EOB_REPL_LEN - eob_sent;
- smtp->eob = 0;
+ smtp->eob = 0;
eob_sent = 0;
- }
- else if(!smtp->eob)
+ }
+ else if(!smtp->eob)
scratch[si++] = data->req.upload_fromhere[i];
- }
-
+ }
+
if(smtp->eob - eob_sent) {
- /* A substring matched before processing ended so output that now */
+ /* A substring matched before processing ended so output that now */
memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent);
si += smtp->eob - eob_sent;
- }
-
+ }
+
/* Only use the new buffer if we replaced something */
- if(si != nread) {
- /* Upload from the new (replaced) buffer instead */
+ if(si != nread) {
+ /* Upload from the new (replaced) buffer instead */
data->req.upload_fromhere = scratch;
-
+
/* Save the buffer so it can be freed later */
data->state.scratch = scratch;
/* Free the old scratch buffer */
free(oldscratch);
- /* Set the new amount too */
+ /* Set the new amount too */
data->req.upload_present = si;
- }
+ }
else
free(newscratch);
-
- return CURLE_OK;
-}
-
-#endif /* CURL_DISABLE_SMTP */
+
+ return CURLE_OK;
+}
+
+#endif /* CURL_DISABLE_SMTP */
diff --git a/contrib/libs/curl/lib/smtp.h b/contrib/libs/curl/lib/smtp.h
index 4ab8f03f17..c7c62ee857 100644
--- a/contrib/libs/curl/lib/smtp.h
+++ b/contrib/libs/curl/lib/smtp.h
@@ -1,96 +1,96 @@
-#ifndef HEADER_CURL_SMTP_H
-#define HEADER_CURL_SMTP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SMTP_H
+#define HEADER_CURL_SMTP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2009 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "pingpong.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "pingpong.h"
#include "curl_sasl.h"
-
-/****************************************************************************
- * SMTP unique setup
- ***************************************************************************/
-typedef enum {
- SMTP_STOP, /* do nothing state, stops the state machine */
- SMTP_SERVERGREET, /* waiting for the initial greeting immediately after
- a connect */
- SMTP_EHLO,
- SMTP_HELO,
- SMTP_STARTTLS,
- SMTP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
- (multi mode only) */
+
+/****************************************************************************
+ * SMTP unique setup
+ ***************************************************************************/
+typedef enum {
+ SMTP_STOP, /* do nothing state, stops the state machine */
+ SMTP_SERVERGREET, /* waiting for the initial greeting immediately after
+ a connect */
+ SMTP_EHLO,
+ SMTP_HELO,
+ SMTP_STARTTLS,
+ SMTP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
+ (multi mode only) */
SMTP_AUTH,
SMTP_COMMAND, /* VRFY, EXPN, NOOP, RSET and HELP */
- SMTP_MAIL, /* MAIL FROM */
- SMTP_RCPT, /* RCPT TO */
- SMTP_DATA,
- SMTP_POSTDATA,
- SMTP_QUIT,
- SMTP_LAST /* never used */
-} smtpstate;
-
+ SMTP_MAIL, /* MAIL FROM */
+ SMTP_RCPT, /* RCPT TO */
+ SMTP_DATA,
+ SMTP_POSTDATA,
+ SMTP_QUIT,
+ SMTP_LAST /* never used */
+} smtpstate;
+
/* This SMTP struct is used in the Curl_easy. All SMTP data that is
- connection-oriented must be in smtp_conn to properly deal with the fact that
+ connection-oriented must be in smtp_conn to properly deal with the fact that
perhaps the Curl_easy is changed between the times the connection is
- used. */
-struct SMTP {
- curl_pp_transfer transfer;
+ used. */
+struct SMTP {
+ curl_pp_transfer transfer;
char *custom; /* Custom Request */
- struct curl_slist *rcpt; /* Recipient list */
+ struct curl_slist *rcpt; /* Recipient list */
bool rcpt_had_ok; /* Whether any of RCPT TO commands (depends on
total number of recipients) succeeded so far */
int rcpt_last_error; /* The last error received for RCPT TO command */
- size_t eob; /* Number of bytes of the EOB (End Of Body) that
- have been received so far */
- bool trailing_crlf; /* Specifies if the tailing CRLF is present */
-};
-
-/* smtp_conn is used for struct connection-oriented data in the connectdata
- struct */
-struct smtp_conn {
- struct pingpong pp;
- smtpstate state; /* Always use smtp.c:state() to change state! */
- bool ssldone; /* Is connect() over SSL done? */
- char *domain; /* Client address/name to send in the EHLO */
+ size_t eob; /* Number of bytes of the EOB (End Of Body) that
+ have been received so far */
+ bool trailing_crlf; /* Specifies if the tailing CRLF is present */
+};
+
+/* smtp_conn is used for struct connection-oriented data in the connectdata
+ struct */
+struct smtp_conn {
+ struct pingpong pp;
+ smtpstate state; /* Always use smtp.c:state() to change state! */
+ bool ssldone; /* Is connect() over SSL done? */
+ char *domain; /* Client address/name to send in the EHLO */
struct SASL sasl; /* SASL-related storage */
- bool tls_supported; /* StartTLS capability supported by server */
- bool size_supported; /* If server supports SIZE extension according to
- RFC 1870 */
+ bool tls_supported; /* StartTLS capability supported by server */
+ bool size_supported; /* If server supports SIZE extension according to
+ RFC 1870 */
bool utf8_supported; /* If server supports SMTPUTF8 extension according
to RFC 6531 */
bool auth_supported; /* AUTH capability supported by server */
-};
-
-extern const struct Curl_handler Curl_handler_smtp;
-extern const struct Curl_handler Curl_handler_smtps;
-
-/* this is the 5-bytes End-Of-Body marker for SMTP */
-#define SMTP_EOB "\x0d\x0a\x2e\x0d\x0a"
-#define SMTP_EOB_LEN 5
-#define SMTP_EOB_FIND_LEN 3
-
-/* if found in data, replace it with this string instead */
-#define SMTP_EOB_REPL "\x0d\x0a\x2e\x2e"
-#define SMTP_EOB_REPL_LEN 4
-
+};
+
+extern const struct Curl_handler Curl_handler_smtp;
+extern const struct Curl_handler Curl_handler_smtps;
+
+/* this is the 5-bytes End-Of-Body marker for SMTP */
+#define SMTP_EOB "\x0d\x0a\x2e\x0d\x0a"
+#define SMTP_EOB_LEN 5
+#define SMTP_EOB_FIND_LEN 3
+
+/* if found in data, replace it with this string instead */
+#define SMTP_EOB_REPL "\x0d\x0a\x2e\x2e"
+#define SMTP_EOB_REPL_LEN 4
+
CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread);
-
-#endif /* HEADER_CURL_SMTP_H */
+
+#endif /* HEADER_CURL_SMTP_H */
diff --git a/contrib/libs/curl/lib/sockaddr.h b/contrib/libs/curl/lib/sockaddr.h
index e2c43d3fec..84c08d9bb5 100644
--- a/contrib/libs/curl/lib/sockaddr.h
+++ b/contrib/libs/curl/lib/sockaddr.h
@@ -1,42 +1,42 @@
-#ifndef HEADER_CURL_SOCKADDR_H
-#define HEADER_CURL_SOCKADDR_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SOCKADDR_H
+#define HEADER_CURL_SOCKADDR_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-struct Curl_sockaddr_storage {
- union {
- struct sockaddr sa;
- struct sockaddr_in sa_in;
-#ifdef ENABLE_IPV6
- struct sockaddr_in6 sa_in6;
-#endif
-#ifdef HAVE_STRUCT_SOCKADDR_STORAGE
- struct sockaddr_storage sa_stor;
-#else
- char cbuf[256]; /* this should be big enough to fit a lot */
-#endif
- } buffer;
-};
-
-#endif /* HEADER_CURL_SOCKADDR_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+struct Curl_sockaddr_storage {
+ union {
+ struct sockaddr sa;
+ struct sockaddr_in sa_in;
+#ifdef ENABLE_IPV6
+ struct sockaddr_in6 sa_in6;
+#endif
+#ifdef HAVE_STRUCT_SOCKADDR_STORAGE
+ struct sockaddr_storage sa_stor;
+#else
+ char cbuf[256]; /* this should be big enough to fit a lot */
+#endif
+ } buffer;
+};
+
+#endif /* HEADER_CURL_SOCKADDR_H */
diff --git a/contrib/libs/curl/lib/socks.c b/contrib/libs/curl/lib/socks.c
index 17ffc38c8e..a2d1e621f9 100644
--- a/contrib/libs/curl/lib/socks.c
+++ b/contrib/libs/curl/lib/socks.c
@@ -1,104 +1,104 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if !defined(CURL_DISABLE_PROXY)
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-#include "urldata.h"
-#include "sendf.h"
-#include "select.h"
-#include "connect.h"
-#include "timeval.h"
-#include "socks.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_PROXY)
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#include "urldata.h"
+#include "sendf.h"
+#include "select.h"
+#include "connect.h"
+#include "timeval.h"
+#include "socks.h"
#include "multiif.h" /* for getsock macros */
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "memdebug.h"
+
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
-/*
- * Helper read-from-socket functions. Does the same as Curl_read() but it
- * blocks until all bytes amount of buffersize will be read. No more, no less.
- *
+/*
+ * Helper read-from-socket functions. Does the same as Curl_read() but it
+ * blocks until all bytes amount of buffersize will be read. No more, no less.
+ *
* This is STUPID BLOCKING behavior. Only used by the SOCKS GSSAPI functions.
- */
-int Curl_blockread_all(struct connectdata *conn, /* connection data */
- curl_socket_t sockfd, /* read from this socket */
- char *buf, /* store read data here */
- ssize_t buffersize, /* max amount to read */
- ssize_t *n) /* amount bytes read */
-{
+ */
+int Curl_blockread_all(struct connectdata *conn, /* connection data */
+ curl_socket_t sockfd, /* read from this socket */
+ char *buf, /* store read data here */
+ ssize_t buffersize, /* max amount to read */
+ ssize_t *n) /* amount bytes read */
+{
ssize_t nread = 0;
- ssize_t allread = 0;
- int result;
- *n = 0;
- for(;;) {
+ ssize_t allread = 0;
+ int result;
+ *n = 0;
+ for(;;) {
timediff_t timeout_ms = Curl_timeleft(conn->data, NULL, TRUE);
if(timeout_ms < 0) {
- /* we already got the timeout */
- result = CURLE_OPERATION_TIMEDOUT;
- break;
- }
+ /* we already got the timeout */
+ result = CURLE_OPERATION_TIMEDOUT;
+ break;
+ }
if(!timeout_ms)
timeout_ms = TIMEDIFF_T_MAX;
if(SOCKET_READABLE(sockfd, timeout_ms) <= 0) {
- result = ~CURLE_OK;
- break;
- }
- result = Curl_read_plain(sockfd, buf, buffersize, &nread);
- if(CURLE_AGAIN == result)
- continue;
+ result = ~CURLE_OK;
+ break;
+ }
+ result = Curl_read_plain(sockfd, buf, buffersize, &nread);
+ if(CURLE_AGAIN == result)
+ continue;
if(result)
- break;
-
- if(buffersize == nread) {
- allread += nread;
- *n = allread;
- result = CURLE_OK;
- break;
- }
- if(!nread) {
- result = ~CURLE_OK;
- break;
- }
-
- buffersize -= nread;
- buf += nread;
- allread += nread;
- }
- return result;
-}
+ break;
+
+ if(buffersize == nread) {
+ allread += nread;
+ *n = allread;
+ result = CURLE_OK;
+ break;
+ }
+ if(!nread) {
+ result = ~CURLE_OK;
+ break;
+ }
+
+ buffersize -= nread;
+ buf += nread;
+ allread += nread;
+ }
+ return result;
+}
#endif
-
+
#ifndef DEBUGBUILD
#define sxstate(x,y) socksstate(x,y)
#else
@@ -173,24 +173,24 @@ int Curl_SOCKS_getsock(struct connectdata *conn, curl_socket_t *sock,
return rc;
}
-/*
-* This function logs in to a SOCKS4 proxy and sends the specifics to the final
-* destination server.
-*
-* Reference :
+/*
+* This function logs in to a SOCKS4 proxy and sends the specifics to the final
+* destination server.
+*
+* Reference :
* https://www.openssh.com/txt/socks4.protocol
-*
-* Note :
-* Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
-* Nonsupport "Identification Protocol (RFC1413)"
-*/
+*
+* Note :
+* Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
+* Nonsupport "Identification Protocol (RFC1413)"
+*/
CURLproxycode Curl_SOCKS4(const char *proxy_user,
const char *hostname,
int remote_port,
int sockindex,
struct connectdata *conn,
bool *done)
-{
+{
const bool protocol4a =
(conn->socks_proxy.proxytype == CURLPROXY_SOCKS4A) ? TRUE : FALSE;
unsigned char *socksreq = &conn->cnnct.socksreq[0];
@@ -201,10 +201,10 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
struct Curl_dns_entry *dns = NULL;
ssize_t actualread;
ssize_t written;
-
+
if(!SOCKS_STATE(sx->state) && !*done)
sxstate(conn, CONNECT_SOCKS_INIT);
-
+
switch(sx->state) {
case CONNECT_SOCKS_INIT:
/* SOCKS4 can only do IPv4, insist! */
@@ -212,7 +212,7 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
if(conn->bits.httpproxy)
infof(conn->data, "SOCKS4%s: connecting to HTTP proxy %s port %d\n",
protocol4a ? "a" : "", hostname, remote_port);
-
+
infof(data, "SOCKS4 communication to %s:%d\n", hostname, remote_port);
/*
@@ -230,12 +230,12 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
socksreq[1] = 1; /* connect */
socksreq[2] = (unsigned char)((remote_port >> 8) & 0xff); /* PORT MSB */
socksreq[3] = (unsigned char)(remote_port & 0xff); /* PORT LSB */
-
+
/* DNS resolve only for SOCKS4, not SOCKS4a */
if(!protocol4a) {
enum resolve_t rc =
Curl_resolv(conn, hostname, remote_port, FALSE, &dns);
-
+
if(rc == CURLRESOLV_ERROR)
return CURLPX_RESOLVE_HOST;
else if(rc == CURLRESOLV_PENDING) {
@@ -246,15 +246,15 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
sxstate(conn, CONNECT_RESOLVED);
goto CONNECT_RESOLVED;
}
-
+
/* socks4a doesn't resolve anything locally */
sxstate(conn, CONNECT_REQ_INIT);
goto CONNECT_REQ_INIT;
-
+
case CONNECT_RESOLVING:
/* check if we have the name resolved by now */
dns = Curl_fetch_addr(conn, hostname, (int)conn->port);
-
+
if(dns) {
#ifdef CURLRES_ASYNCH
conn->async.dns = dns;
@@ -276,15 +276,15 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
case CONNECT_RESOLVED: {
struct Curl_addrinfo *hp = NULL;
char buf[64];
- /*
- * We cannot use 'hostent' as a struct that Curl_resolv() returns. It
- * returns a Curl_addrinfo pointer that may not always look the same.
- */
- if(dns)
+ /*
+ * We cannot use 'hostent' as a struct that Curl_resolv() returns. It
+ * returns a Curl_addrinfo pointer that may not always look the same.
+ */
+ if(dns)
hp = dns->addr;
- if(hp) {
- Curl_printable_address(hp, buf, sizeof(buf));
-
+ if(hp) {
+ Curl_printable_address(hp, buf, sizeof(buf));
+
if(hp->ai_family == AF_INET) {
struct sockaddr_in *saddr_in;
@@ -295,20 +295,20 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
socksreq[7] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[3];
infof(data, "SOCKS4 connect to IPv4 %s (locally resolved)\n", buf);
- }
+ }
else {
- hp = NULL; /* fail! */
+ hp = NULL; /* fail! */
failf(data, "SOCKS4 connection to %s not supported\n", buf);
}
- Curl_resolv_unlock(data, dns); /* not used anymore from now on */
- }
- if(!hp) {
- failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.",
- hostname);
+ Curl_resolv_unlock(data, dns); /* not used anymore from now on */
+ }
+ if(!hp) {
+ failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.",
+ hostname);
return CURLPX_RESOLVE_HOST;
- }
- }
+ }
+ }
/* FALLTHROUGH */
CONNECT_REQ_INIT:
case CONNECT_REQ_INIT:
@@ -324,15 +324,15 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
}
/* copy the proxy name WITH trailing zero */
memcpy(socksreq + 8, proxy_user, plen + 1);
- }
-
+ }
+
/*
* Make connection
*/
{
size_t packetsize = 9 +
strlen((char *)socksreq + 8); /* size including NUL */
-
+
/* If SOCKS4a, set special invalid IP address 0.0.0.x */
if(protocol4a) {
size_t hostnamelen = 0;
@@ -353,38 +353,38 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
sx->outp = socksreq;
sx->outstanding = packetsize;
sxstate(conn, CONNECT_REQ_SENDING);
- }
+ }
/* FALLTHROUGH */
case CONNECT_REQ_SENDING:
- /* Send request */
+ /* Send request */
result = Curl_write_plain(conn, sockfd, (char *)sx->outp,
sx->outstanding, &written);
if(result && (CURLE_AGAIN != result)) {
- failf(data, "Failed to send SOCKS4 connect request.");
+ failf(data, "Failed to send SOCKS4 connect request.");
return CURLPX_SEND_CONNECT;
- }
+ }
if(written != sx->outstanding) {
/* not done, remain in state */
sx->outstanding -= written;
sx->outp += written;
return CURLPX_OK;
- }
-
+ }
+
/* done sending! */
sx->outstanding = 8; /* receive data size */
sx->outp = socksreq;
sxstate(conn, CONNECT_SOCKS_READ);
-
+
/* FALLTHROUGH */
case CONNECT_SOCKS_READ:
- /* Receive response */
+ /* Receive response */
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
failf(data, "SOCKS4: Failed receiving connect request ack: %s",
curl_easy_strerror(result));
return CURLPX_RECV_CONNECT;
- }
+ }
else if(!result && !actualread) {
/* connection closed */
failf(data, "connection to proxy closed");
@@ -401,7 +401,7 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
default: /* lots of unused states in SOCKS4 */
break;
}
-
+
/*
* Response format
*
@@ -420,14 +420,14 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
* 93: request rejected because the client program and identd
* report different user-ids
*/
-
+
/* wrong version ? */
if(socksreq[0] != 0) {
failf(data,
"SOCKS4 reply has wrong version, version should be 0.");
return CURLPX_BAD_VERSION;
}
-
+
/* Result */
switch(socksreq[1]) {
case 90:
@@ -471,16 +471,16 @@ CURLproxycode Curl_SOCKS4(const char *proxy_user,
(((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLPX_UNKNOWN_FAIL;
- }
-
+ }
+
*done = TRUE;
return CURLPX_OK; /* Proxy was successful! */
-}
-
-/*
- * This function logs in to a SOCKS5 proxy and sends the specifics to the final
- * destination server.
- */
+}
+
+/*
+ * This function logs in to a SOCKS5 proxy and sends the specifics to the final
+ * destination server.
+ */
CURLproxycode Curl_SOCKS5(const char *proxy_user,
const char *proxy_password,
const char *hostname,
@@ -488,40 +488,40 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
int sockindex,
struct connectdata *conn,
bool *done)
-{
- /*
- According to the RFC1928, section "6. Replies". This is what a SOCK5
- replies:
-
- +----+-----+-------+------+----------+----------+
- |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
- +----+-----+-------+------+----------+----------+
- | 1 | 1 | X'00' | 1 | Variable | 2 |
- +----+-----+-------+------+----------+----------+
-
- Where:
-
- o VER protocol version: X'05'
- o REP Reply field:
- o X'00' succeeded
- */
+{
+ /*
+ According to the RFC1928, section "6. Replies". This is what a SOCK5
+ replies:
+
+ +----+-----+-------+------+----------+----------+
+ |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
+ +----+-----+-------+------+----------+----------+
+ | 1 | 1 | X'00' | 1 | Variable | 2 |
+ +----+-----+-------+------+----------+----------+
+
+ Where:
+
+ o VER protocol version: X'05'
+ o REP Reply field:
+ o X'00' succeeded
+ */
unsigned char *socksreq = &conn->cnnct.socksreq[0];
char dest[256] = "unknown"; /* printable hostname:port */
int idx;
- ssize_t actualread;
- ssize_t written;
+ ssize_t actualread;
+ ssize_t written;
CURLcode result;
curl_socket_t sockfd = conn->sock[sockindex];
struct Curl_easy *data = conn->data;
bool socks5_resolve_local =
(conn->socks_proxy.proxytype == CURLPROXY_SOCKS5) ? TRUE : FALSE;
- const size_t hostname_len = strlen(hostname);
- ssize_t len = 0;
+ const size_t hostname_len = strlen(hostname);
+ ssize_t len = 0;
const unsigned long auth = data->set.socks5auth;
bool allow_gssapi = FALSE;
struct connstate *sx = &conn->cnnct;
struct Curl_dns_entry *dns = NULL;
-
+
if(!SOCKS_STATE(sx->state) && !*done)
sxstate(conn, CONNECT_SOCKS_INIT);
@@ -530,14 +530,14 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
if(conn->bits.httpproxy)
infof(conn->data, "SOCKS5: connecting to HTTP proxy %s port %d\n",
hostname, remote_port);
-
+
/* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */
if(!socks5_resolve_local && hostname_len > 255) {
infof(conn->data, "SOCKS5: server resolving disabled for hostnames of "
"length > 255 [actual len=%zu]\n", hostname_len);
socks5_resolve_local = TRUE;
}
-
+
if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI))
infof(conn->data,
"warning: unsupported value passed to CURLOPT_SOCKS5_AUTH: %lu\n",
@@ -545,11 +545,11 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
if(!(auth & CURLAUTH_BASIC))
/* disable username/password auth */
proxy_user = NULL;
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(auth & CURLAUTH_GSSAPI)
allow_gssapi = TRUE;
-#endif
-
+#endif
+
idx = 0;
socksreq[idx++] = 5; /* version */
idx++; /* number of authentication methods */
@@ -560,7 +560,7 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
socksreq[idx++] = 2; /* username/password */
/* write the number of authentication methods */
socksreq[1] = (unsigned char) (idx - 2);
-
+
result = Curl_write_plain(conn, sockfd, (char *)socksreq, idx, &written);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Unable to send initial SOCKS5 request.");
@@ -625,7 +625,7 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
sxstate(conn, CONNECT_AUTH_INIT);
goto CONNECT_AUTH_INIT;
}
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
else if(allow_gssapi && (socksreq[1] == 1)) {
sxstate(conn, CONNECT_GSSAPI_INIT);
result = Curl_SOCKS5_gssapi_negotiate(sockindex, conn);
@@ -633,8 +633,8 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
failf(data, "Unable to negotiate SOCKS5 GSS-API context.");
return CURLPX_GSSAPI;
}
- }
-#endif
+ }
+#endif
else {
/* error */
if(!allow_gssapi && (socksreq[1] == 1)) {
@@ -661,26 +661,26 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
CONNECT_AUTH_INIT:
case CONNECT_AUTH_INIT: {
- /* Needs user name and password */
+ /* Needs user name and password */
size_t proxy_user_len, proxy_password_len;
if(proxy_user && proxy_password) {
proxy_user_len = strlen(proxy_user);
- proxy_password_len = strlen(proxy_password);
- }
- else {
+ proxy_password_len = strlen(proxy_password);
+ }
+ else {
proxy_user_len = 0;
- proxy_password_len = 0;
- }
-
- /* username/password request looks like
- * +----+------+----------+------+----------+
- * |VER | ULEN | UNAME | PLEN | PASSWD |
- * +----+------+----------+------+----------+
- * | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
- * +----+------+----------+------+----------+
- */
- len = 0;
- socksreq[len++] = 1; /* username/pw subnegotiation version */
+ proxy_password_len = 0;
+ }
+
+ /* username/password request looks like
+ * +----+------+----------+------+----------+
+ * |VER | ULEN | UNAME | PLEN | PASSWD |
+ * +----+------+----------+------+----------+
+ * | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
+ * +----+------+----------+------+----------+
+ */
+ len = 0;
+ socksreq[len++] = 1; /* username/pw subnegotiation version */
socksreq[len++] = (unsigned char) proxy_user_len;
if(proxy_user && proxy_user_len) {
/* the length must fit in a single byte */
@@ -691,16 +691,16 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
memcpy(socksreq + len, proxy_user, proxy_user_len);
}
len += proxy_user_len;
- socksreq[len++] = (unsigned char) proxy_password_len;
+ socksreq[len++] = (unsigned char) proxy_password_len;
if(proxy_password && proxy_password_len) {
/* the length must fit in a single byte */
if(proxy_password_len > 255) {
failf(data, "Excessive password length for proxy auth");
return CURLPX_LONG_PASSWD;
}
- memcpy(socksreq + len, proxy_password, proxy_password_len);
+ memcpy(socksreq + len, proxy_password, proxy_password_len);
}
- len += proxy_password_len;
+ len += proxy_password_len;
sxstate(conn, CONNECT_AUTH_SEND);
sx->outstanding = len;
sx->outp = socksreq;
@@ -710,9 +710,9 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
result = Curl_write_plain(conn, sockfd, (char *)sx->outp,
sx->outstanding, &written);
if(result && (CURLE_AGAIN != result)) {
- failf(data, "Failed to send SOCKS5 sub-negotiation request.");
+ failf(data, "Failed to send SOCKS5 sub-negotiation request.");
return CURLPX_SEND_AUTH;
- }
+ }
if(sx->outstanding != written) {
/* remain in state */
sx->outstanding -= written;
@@ -727,9 +727,9 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
- failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
+ failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
return CURLPX_RECV_AUTH;
- }
+ }
else if(!result && !actualread) {
/* connection closed */
failf(data, "connection to proxy closed");
@@ -741,14 +741,14 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
sx->outp += actualread;
return CURLPX_OK;
}
- /* ignore the first (VER) byte */
+ /* ignore the first (VER) byte */
else if(socksreq[1] != 0) { /* status */
- failf(data, "User was rejected by the SOCKS5 server (%d %d).",
- socksreq[0], socksreq[1]);
+ failf(data, "User was rejected by the SOCKS5 server (%d %d).",
+ socksreq[0], socksreq[1]);
return CURLPX_USER_REJECTED;
- }
-
- /* Everything is good so far, user was authenticated! */
+ }
+
+ /* Everything is good so far, user was authenticated! */
sxstate(conn, CONNECT_REQ_INIT);
/* FALLTHROUGH */
CONNECT_REQ_INIT:
@@ -763,16 +763,16 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
if(rc == CURLRESOLV_PENDING) {
sxstate(conn, CONNECT_RESOLVING);
return CURLPX_OK;
- }
+ }
sxstate(conn, CONNECT_RESOLVED);
goto CONNECT_RESOLVED;
- }
+ }
goto CONNECT_RESOLVE_REMOTE;
-
+
case CONNECT_RESOLVING:
/* check if we have the name resolved by now */
dns = Curl_fetch_addr(conn, hostname, remote_port);
-
+
if(dns) {
#ifdef CURLRES_ASYNCH
conn->async.dns = dns;
@@ -780,7 +780,7 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
#endif
infof(data, "SOCKS5: hostname '%s' found\n", hostname);
}
-
+
if(!dns) {
result = Curl_resolv_check(data->conn, &dns);
if(!dns) {
@@ -788,24 +788,24 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
return CURLPX_RESOLVE_HOST;
return CURLPX_OK;
}
- }
+ }
/* FALLTHROUGH */
CONNECT_RESOLVED:
case CONNECT_RESOLVED: {
struct Curl_addrinfo *hp = NULL;
size_t destlen;
- if(dns)
+ if(dns)
hp = dns->addr;
if(!hp) {
failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.",
hostname);
return CURLPX_RESOLVE_HOST;
}
-
+
Curl_printable_address(hp, dest, sizeof(dest));
destlen = strlen(dest);
msnprintf(dest + destlen, sizeof(dest) - destlen, ":%d", remote_port);
-
+
len = 0;
socksreq[len++] = 5; /* version (SOCKS5) */
socksreq[len++] = 1; /* connect */
@@ -818,33 +818,33 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
saddr_in = (struct sockaddr_in *)(void *)hp->ai_addr;
for(i = 0; i < 4; i++) {
socksreq[len++] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[i];
- }
+ }
infof(data, "SOCKS5 connect to IPv4 %s (locally resolved)\n", dest);
}
-#ifdef ENABLE_IPV6
+#ifdef ENABLE_IPV6
else if(hp->ai_family == AF_INET6) {
int i;
struct sockaddr_in6 *saddr_in6;
socksreq[len++] = 4; /* ATYP: IPv6 = 4 */
-
+
saddr_in6 = (struct sockaddr_in6 *)(void *)hp->ai_addr;
for(i = 0; i < 16; i++) {
socksreq[len++] =
((unsigned char *)&saddr_in6->sin6_addr.s6_addr)[i];
- }
-
+ }
+
infof(data, "SOCKS5 connect to IPv6 %s (locally resolved)\n", dest);
- }
+ }
#endif
else {
hp = NULL; /* fail! */
failf(data, "SOCKS5 connection to %s not supported\n", dest);
- }
-
+ }
+
Curl_resolv_unlock(data, dns); /* not used anymore from now on */
goto CONNECT_REQ_SEND;
- }
+ }
CONNECT_RESOLVE_REMOTE:
case CONNECT_RESOLVE_REMOTE:
/* Authentication is complete, now specify destination to the proxy */
@@ -852,7 +852,7 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
socksreq[len++] = 5; /* version (SOCKS5) */
socksreq[len++] = 1; /* connect */
socksreq[len++] = 0; /* must be zero */
-
+
if(!socks5_resolve_local) {
socksreq[len++] = 3; /* ATYP: domain name = 3 */
socksreq[len++] = (char) hostname_len; /* one byte address length */
@@ -862,20 +862,20 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
hostname, remote_port);
}
/* FALLTHROUGH */
-
+
CONNECT_REQ_SEND:
case CONNECT_REQ_SEND:
/* PORT MSB */
socksreq[len++] = (unsigned char)((remote_port >> 8) & 0xff);
/* PORT LSB */
socksreq[len++] = (unsigned char)(remote_port & 0xff);
-
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(conn->socks5_gssapi_enctype) {
failf(data, "SOCKS5 GSS-API protection not yet implemented.");
return CURLPX_GSSAPI_PROTECTION;
}
-#endif
+#endif
sx->outp = socksreq;
sx->outstanding = len;
sxstate(conn, CONNECT_REQ_SENDING);
@@ -921,7 +921,7 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
sx->outp += actualread;
return CURLPX_OK;
}
-
+
if(socksreq[0] != 5) { /* version */
failf(data,
"SOCKS5 reply has wrong version, version should be 5.");
@@ -949,23 +949,23 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
}
return rc;
}
-
+
/* Fix: in general, returned BND.ADDR is variable length parameter by RFC
1928, so the reply packet should be read until the end to avoid errors
at subsequent protocol level.
-
+
+----+-----+-------+------+----------+----------+
|VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
-
+
ATYP:
o IP v4 address: X'01', BND.ADDR = 4 byte
o domain name: X'03', BND.ADDR = [ 1 byte length, string ]
o IP v6 address: X'04', BND.ADDR = 16 byte
*/
-
+
/* Calculate real packet size */
if(socksreq[3] == 3) {
/* domain name */
@@ -983,24 +983,24 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
failf(data, "SOCKS5 reply has wrong address type.");
return CURLPX_BAD_ADDRESS_TYPE;
}
-
+
/* At this point we already read first 10 bytes */
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(!conn->socks5_gssapi_enctype) {
/* decrypt_gssapi_blockread already read the whole packet */
-#endif
+#endif
if(len > 10) {
sx->outstanding = len - 10; /* get the rest */
sx->outp = &socksreq[10];
sxstate(conn, CONNECT_REQ_READ_MORE);
- }
+ }
else {
sxstate(conn, CONNECT_DONE);
break;
}
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
- }
-#endif
+ }
+#endif
/* FALLTHROUGH */
case CONNECT_REQ_READ_MORE:
result = Curl_read_plain(sockfd, (char *)sx->outp,
@@ -1026,6 +1026,6 @@ CURLproxycode Curl_SOCKS5(const char *proxy_user,
*done = TRUE;
return CURLPX_OK; /* Proxy was successful! */
-}
-
-#endif /* CURL_DISABLE_PROXY */
+}
+
+#endif /* CURL_DISABLE_PROXY */
diff --git a/contrib/libs/curl/lib/socks.h b/contrib/libs/curl/lib/socks.h
index d3ae12e366..1fae58b6fa 100644
--- a/contrib/libs/curl/lib/socks.h
+++ b/contrib/libs/curl/lib/socks.h
@@ -1,64 +1,64 @@
-#ifndef HEADER_CURL_SOCKS_H
-#define HEADER_CURL_SOCKS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SOCKS_H
+#define HEADER_CURL_SOCKS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef CURL_DISABLE_PROXY
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef CURL_DISABLE_PROXY
#define Curl_SOCKS4(a,b,c,d,e) CURLE_NOT_BUILT_IN
-#define Curl_SOCKS5(a,b,c,d,e,f) CURLE_NOT_BUILT_IN
+#define Curl_SOCKS5(a,b,c,d,e,f) CURLE_NOT_BUILT_IN
#define Curl_SOCKS_getsock(x,y,z) 0
-#else
-/*
- * Helper read-from-socket functions. Does the same as Curl_read() but it
- * blocks until all bytes amount of buffersize will be read. No more, no less.
- *
+#else
+/*
+ * Helper read-from-socket functions. Does the same as Curl_read() but it
+ * blocks until all bytes amount of buffersize will be read. No more, no less.
+ *
* This is STUPID BLOCKING behavior
- */
-int Curl_blockread_all(struct connectdata *conn,
- curl_socket_t sockfd,
- char *buf,
- ssize_t buffersize,
- ssize_t *n);
-
+ */
+int Curl_blockread_all(struct connectdata *conn,
+ curl_socket_t sockfd,
+ char *buf,
+ ssize_t buffersize,
+ ssize_t *n);
+
int Curl_SOCKS_getsock(struct connectdata *conn,
curl_socket_t *sock,
int sockindex);
-/*
- * This function logs in to a SOCKS4(a) proxy and sends the specifics to the
- * final destination server.
- */
+/*
+ * This function logs in to a SOCKS4(a) proxy and sends the specifics to the
+ * final destination server.
+ */
CURLproxycode Curl_SOCKS4(const char *proxy_name,
const char *hostname,
int remote_port,
int sockindex,
struct connectdata *conn,
bool *done);
-
-/*
- * This function logs in to a SOCKS5 proxy and sends the specifics to the
- * final destination server.
- */
+
+/*
+ * This function logs in to a SOCKS5 proxy and sends the specifics to the
+ * final destination server.
+ */
CURLproxycode Curl_SOCKS5(const char *proxy_name,
const char *proxy_password,
const char *hostname,
@@ -66,15 +66,15 @@ CURLproxycode Curl_SOCKS5(const char *proxy_name,
int sockindex,
struct connectdata *conn,
bool *done);
-
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
-/*
+
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+/*
* This function handles the SOCKS5 GSS-API negotiation and initialisation
- */
-CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
- struct connectdata *conn);
-#endif
-
-#endif /* CURL_DISABLE_PROXY */
-
-#endif /* HEADER_CURL_SOCKS_H */
+ */
+CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
+ struct connectdata *conn);
+#endif
+
+#endif /* CURL_DISABLE_PROXY */
+
+#endif /* HEADER_CURL_SOCKS_H */
diff --git a/contrib/libs/curl/lib/socks_gssapi.c b/contrib/libs/curl/lib/socks_gssapi.c
index 4e5e2611b7..a96579692b 100644
--- a/contrib/libs/curl/lib/socks_gssapi.c
+++ b/contrib/libs/curl/lib/socks_gssapi.c
@@ -1,532 +1,532 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) 2009, Markus Moeller, <markus_moeller@compuserve.com>
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_PROXY)
-
-#include "curl_gssapi.h"
-#include "urldata.h"
-#include "sendf.h"
-#include "connect.h"
-#include "timeval.h"
-#include "socks.h"
-#include "warnless.h"
-
+
+#include "curl_gssapi.h"
+#include "urldata.h"
+#include "sendf.h"
+#include "connect.h"
+#include "timeval.h"
+#include "socks.h"
+#include "warnless.h"
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-static gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT;
-
-/*
+#include "curl_memory.h"
+#include "memdebug.h"
+
+static gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT;
+
+/*
* Helper GSS-API error functions.
- */
+ */
static int check_gss_err(struct Curl_easy *data,
- OM_uint32 major_status,
- OM_uint32 minor_status,
+ OM_uint32 major_status,
+ OM_uint32 minor_status,
const char *function)
-{
- if(GSS_ERROR(major_status)) {
+{
+ if(GSS_ERROR(major_status)) {
OM_uint32 maj_stat, min_stat;
- OM_uint32 msg_ctx = 0;
- gss_buffer_desc status_string;
- char buf[1024];
- size_t len;
-
- len = 0;
- msg_ctx = 0;
- while(!msg_ctx) {
- /* convert major status code (GSS-API error) to text */
- maj_stat = gss_display_status(&min_stat, major_status,
- GSS_C_GSS_CODE,
- GSS_C_NULL_OID,
- &msg_ctx, &status_string);
- if(maj_stat == GSS_S_COMPLETE) {
- if(sizeof(buf) > len + status_string.length + 1) {
+ OM_uint32 msg_ctx = 0;
+ gss_buffer_desc status_string;
+ char buf[1024];
+ size_t len;
+
+ len = 0;
+ msg_ctx = 0;
+ while(!msg_ctx) {
+ /* convert major status code (GSS-API error) to text */
+ maj_stat = gss_display_status(&min_stat, major_status,
+ GSS_C_GSS_CODE,
+ GSS_C_NULL_OID,
+ &msg_ctx, &status_string);
+ if(maj_stat == GSS_S_COMPLETE) {
+ if(sizeof(buf) > len + status_string.length + 1) {
strcpy(buf + len, (char *) status_string.value);
- len += status_string.length;
- }
- gss_release_buffer(&min_stat, &status_string);
- break;
- }
- gss_release_buffer(&min_stat, &status_string);
- }
- if(sizeof(buf) > len + 3) {
+ len += status_string.length;
+ }
+ gss_release_buffer(&min_stat, &status_string);
+ break;
+ }
+ gss_release_buffer(&min_stat, &status_string);
+ }
+ if(sizeof(buf) > len + 3) {
strcpy(buf + len, ".\n");
- len += 2;
- }
- msg_ctx = 0;
- while(!msg_ctx) {
- /* convert minor status code (underlying routine error) to text */
- maj_stat = gss_display_status(&min_stat, minor_status,
- GSS_C_MECH_CODE,
- GSS_C_NULL_OID,
- &msg_ctx, &status_string);
- if(maj_stat == GSS_S_COMPLETE) {
- if(sizeof(buf) > len + status_string.length)
+ len += 2;
+ }
+ msg_ctx = 0;
+ while(!msg_ctx) {
+ /* convert minor status code (underlying routine error) to text */
+ maj_stat = gss_display_status(&min_stat, minor_status,
+ GSS_C_MECH_CODE,
+ GSS_C_NULL_OID,
+ &msg_ctx, &status_string);
+ if(maj_stat == GSS_S_COMPLETE) {
+ if(sizeof(buf) > len + status_string.length)
strcpy(buf + len, (char *) status_string.value);
- gss_release_buffer(&min_stat, &status_string);
- break;
- }
- gss_release_buffer(&min_stat, &status_string);
- }
+ gss_release_buffer(&min_stat, &status_string);
+ break;
+ }
+ gss_release_buffer(&min_stat, &status_string);
+ }
failf(data, "GSS-API error: %s failed:\n%s", function, buf);
return 1;
- }
-
+ }
+
return 0;
-}
-
-CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
- struct connectdata *conn)
-{
+}
+
+CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
+ struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- curl_socket_t sock = conn->sock[sockindex];
- CURLcode code;
- ssize_t actualread;
- ssize_t written;
- int result;
- OM_uint32 gss_major_status, gss_minor_status, gss_status;
- OM_uint32 gss_ret_flags;
- int gss_conf_state, gss_enc;
- gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
- gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER;
- gss_buffer_desc gss_recv_token = GSS_C_EMPTY_BUFFER;
- gss_buffer_desc gss_w_token = GSS_C_EMPTY_BUFFER;
+ curl_socket_t sock = conn->sock[sockindex];
+ CURLcode code;
+ ssize_t actualread;
+ ssize_t written;
+ int result;
+ OM_uint32 gss_major_status, gss_minor_status, gss_status;
+ OM_uint32 gss_ret_flags;
+ int gss_conf_state, gss_enc;
+ gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc gss_recv_token = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc gss_w_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc *gss_token = GSS_C_NO_BUFFER;
- gss_name_t server = GSS_C_NO_NAME;
- gss_name_t gss_client_name = GSS_C_NO_NAME;
- unsigned short us_length;
+ gss_name_t server = GSS_C_NO_NAME;
+ gss_name_t gss_client_name = GSS_C_NO_NAME;
+ unsigned short us_length;
char *user = NULL;
unsigned char socksreq[4]; /* room for GSS-API exchange header only */
const char *serviceptr = data->set.str[STRING_PROXY_SERVICE_NAME] ?
data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd";
const size_t serviceptr_length = strlen(serviceptr);
-
+
/* GSS-API request looks like
- * +----+------+-----+----------------+
- * |VER | MTYP | LEN | TOKEN |
- * +----+------+----------------------+
- * | 1 | 1 | 2 | up to 2^16 - 1 |
- * +----+------+-----+----------------+
- */
-
- /* prepare service name */
+ * +----+------+-----+----------------+
+ * |VER | MTYP | LEN | TOKEN |
+ * +----+------+----------------------+
+ * | 1 | 1 | 2 | up to 2^16 - 1 |
+ * +----+------+-----+----------------+
+ */
+
+ /* prepare service name */
if(strchr(serviceptr, '/')) {
service.length = serviceptr_length;
service.value = malloc(service.length);
- if(!service.value)
- return CURLE_OUT_OF_MEMORY;
- memcpy(service.value, serviceptr, service.length);
-
- gss_major_status = gss_import_name(&gss_minor_status, &service,
- (gss_OID) GSS_C_NULL_OID, &server);
- }
- else {
+ if(!service.value)
+ return CURLE_OUT_OF_MEMORY;
+ memcpy(service.value, serviceptr, service.length);
+
+ gss_major_status = gss_import_name(&gss_minor_status, &service,
+ (gss_OID) GSS_C_NULL_OID, &server);
+ }
+ else {
service.value = malloc(serviceptr_length +
strlen(conn->socks_proxy.host.name) + 2);
- if(!service.value)
- return CURLE_OUT_OF_MEMORY;
+ if(!service.value)
+ return CURLE_OUT_OF_MEMORY;
service.length = serviceptr_length +
strlen(conn->socks_proxy.host.name) + 1;
msnprintf(service.value, service.length + 1, "%s@%s",
serviceptr, conn->socks_proxy.host.name);
-
- gss_major_status = gss_import_name(&gss_minor_status, &service,
+
+ gss_major_status = gss_import_name(&gss_minor_status, &service,
GSS_C_NT_HOSTBASED_SERVICE, &server);
- }
-
- gss_release_buffer(&gss_status, &service); /* clear allocated memory */
-
+ }
+
+ gss_release_buffer(&gss_status, &service); /* clear allocated memory */
+
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_import_name()")) {
- failf(data, "Failed to create service name.");
- gss_release_name(&gss_status, &server);
- return CURLE_COULDNT_CONNECT;
- }
-
+ failf(data, "Failed to create service name.");
+ gss_release_name(&gss_status, &server);
+ return CURLE_COULDNT_CONNECT;
+ }
+
(void)curlx_nonblock(sock, FALSE);
- /* As long as we need to keep sending some context info, and there's no */
- /* errors, keep sending it... */
- for(;;) {
- gss_major_status = Curl_gss_init_sec_context(data,
- &gss_minor_status,
- &gss_context,
- server,
+ /* As long as we need to keep sending some context info, and there's no */
+ /* errors, keep sending it... */
+ for(;;) {
+ gss_major_status = Curl_gss_init_sec_context(data,
+ &gss_minor_status,
+ &gss_context,
+ server,
&Curl_krb5_mech_oid,
- NULL,
- gss_token,
- &gss_send_token,
+ NULL,
+ gss_token,
+ &gss_send_token,
TRUE,
- &gss_ret_flags);
-
- if(gss_token != GSS_C_NO_BUFFER)
- gss_release_buffer(&gss_status, &gss_recv_token);
+ &gss_ret_flags);
+
+ if(gss_token != GSS_C_NO_BUFFER)
+ gss_release_buffer(&gss_status, &gss_recv_token);
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_init_sec_context")) {
- gss_release_name(&gss_status, &server);
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_release_buffer(&gss_status, &gss_send_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ gss_release_name(&gss_status, &server);
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_release_buffer(&gss_status, &gss_send_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
failf(data, "Failed to initial GSS-API token.");
- return CURLE_COULDNT_CONNECT;
- }
-
- if(gss_send_token.length != 0) {
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(gss_send_token.length != 0) {
socksreq[0] = 1; /* GSS-API subnegotiation version */
- socksreq[1] = 1; /* authentication message type */
- us_length = htons((short)gss_send_token.length);
+ socksreq[1] = 1; /* authentication message type */
+ us_length = htons((short)gss_send_token.length);
memcpy(socksreq + 2, &us_length, sizeof(short));
-
- code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
+
+ code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
failf(data, "Failed to send GSS-API authentication request.");
- gss_release_name(&gss_status, &server);
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_release_buffer(&gss_status, &gss_send_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- code = Curl_write_plain(conn, sock, (char *)gss_send_token.value,
- gss_send_token.length, &written);
-
+ gss_release_name(&gss_status, &server);
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_release_buffer(&gss_status, &gss_send_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ code = Curl_write_plain(conn, sock, (char *)gss_send_token.value,
+ gss_send_token.length, &written);
+
if(code || ((ssize_t)gss_send_token.length != written)) {
failf(data, "Failed to send GSS-API authentication token.");
- gss_release_name(&gss_status, &server);
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_release_buffer(&gss_status, &gss_send_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- }
-
- gss_release_buffer(&gss_status, &gss_send_token);
- gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_release_name(&gss_status, &server);
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_release_buffer(&gss_status, &gss_send_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ }
+
+ gss_release_buffer(&gss_status, &gss_send_token);
+ gss_release_buffer(&gss_status, &gss_recv_token);
if(gss_major_status != GSS_S_CONTINUE_NEEDED)
break;
-
- /* analyse response */
-
+
+ /* analyse response */
+
/* GSS-API response looks like
- * +----+------+-----+----------------+
- * |VER | MTYP | LEN | TOKEN |
- * +----+------+----------------------+
- * | 1 | 1 | 2 | up to 2^16 - 1 |
- * +----+------+-----+----------------+
- */
-
+ * +----+------+-----+----------------+
+ * |VER | MTYP | LEN | TOKEN |
+ * +----+------+----------------------+
+ * | 1 | 1 | 2 | up to 2^16 - 1 |
+ * +----+------+-----+----------------+
+ */
+
result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive GSS-API authentication response.");
- gss_release_name(&gss_status, &server);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- /* ignore the first (VER) byte */
- if(socksreq[1] == 255) { /* status / message type */
- failf(data, "User was rejected by the SOCKS5 server (%d %d).",
- socksreq[0], socksreq[1]);
- gss_release_name(&gss_status, &server);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(socksreq[1] != 1) { /* status / messgae type */
+ gss_release_name(&gss_status, &server);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ /* ignore the first (VER) byte */
+ if(socksreq[1] == 255) { /* status / message type */
+ failf(data, "User was rejected by the SOCKS5 server (%d %d).",
+ socksreq[0], socksreq[1]);
+ gss_release_name(&gss_status, &server);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(socksreq[1] != 1) { /* status / messgae type */
failf(data, "Invalid GSS-API authentication response type (%d %d).",
- socksreq[0], socksreq[1]);
- gss_release_name(&gss_status, &server);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
+ socksreq[0], socksreq[1]);
+ gss_release_name(&gss_status, &server);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(&us_length, socksreq + 2, sizeof(short));
- us_length = ntohs(us_length);
-
+ us_length = ntohs(us_length);
+
gss_recv_token.length = us_length;
gss_recv_token.value = malloc(us_length);
- if(!gss_recv_token.value) {
- failf(data,
+ if(!gss_recv_token.value) {
+ failf(data,
"Could not allocate memory for GSS-API authentication "
- "response token.");
- gss_release_name(&gss_status, &server);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_OUT_OF_MEMORY;
- }
-
+ "response token.");
+ gss_release_name(&gss_status, &server);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
result = Curl_blockread_all(conn, sock, (char *)gss_recv_token.value,
gss_recv_token.length, &actualread);
-
+
if(result || (actualread != us_length)) {
failf(data, "Failed to receive GSS-API authentication token.");
- gss_release_name(&gss_status, &server);
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- gss_token = &gss_recv_token;
- }
-
- gss_release_name(&gss_status, &server);
-
- /* Everything is good so far, user was authenticated! */
+ gss_release_name(&gss_status, &server);
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ gss_token = &gss_recv_token;
+ }
+
+ gss_release_name(&gss_status, &server);
+
+ /* Everything is good so far, user was authenticated! */
gss_major_status = gss_inquire_context(&gss_minor_status, gss_context,
&gss_client_name, NULL, NULL, NULL,
NULL, NULL, NULL);
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_inquire_context")) {
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- gss_release_name(&gss_status, &gss_client_name);
- failf(data, "Failed to determine user name.");
- return CURLE_COULDNT_CONNECT;
- }
- gss_major_status = gss_display_name(&gss_minor_status, gss_client_name,
- &gss_send_token, NULL);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ gss_release_name(&gss_status, &gss_client_name);
+ failf(data, "Failed to determine user name.");
+ return CURLE_COULDNT_CONNECT;
+ }
+ gss_major_status = gss_display_name(&gss_minor_status, gss_client_name,
+ &gss_send_token, NULL);
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_display_name")) {
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- gss_release_name(&gss_status, &gss_client_name);
- gss_release_buffer(&gss_status, &gss_send_token);
- failf(data, "Failed to determine user name.");
- return CURLE_COULDNT_CONNECT;
- }
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ gss_release_name(&gss_status, &gss_client_name);
+ gss_release_buffer(&gss_status, &gss_send_token);
+ failf(data, "Failed to determine user name.");
+ return CURLE_COULDNT_CONNECT;
+ }
user = malloc(gss_send_token.length + 1);
- if(!user) {
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- gss_release_name(&gss_status, &gss_client_name);
- gss_release_buffer(&gss_status, &gss_send_token);
- return CURLE_OUT_OF_MEMORY;
- }
-
- memcpy(user, gss_send_token.value, gss_send_token.length);
- user[gss_send_token.length] = '\0';
- gss_release_name(&gss_status, &gss_client_name);
- gss_release_buffer(&gss_status, &gss_send_token);
+ if(!user) {
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ gss_release_name(&gss_status, &gss_client_name);
+ gss_release_buffer(&gss_status, &gss_send_token);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ memcpy(user, gss_send_token.value, gss_send_token.length);
+ user[gss_send_token.length] = '\0';
+ gss_release_name(&gss_status, &gss_client_name);
+ gss_release_buffer(&gss_status, &gss_send_token);
infof(data, "SOCKS5 server authenticated user %s with GSS-API.\n",user);
- free(user);
+ free(user);
user = NULL;
-
- /* Do encryption */
+
+ /* Do encryption */
socksreq[0] = 1; /* GSS-API subnegotiation version */
- socksreq[1] = 2; /* encryption message type */
-
- gss_enc = 0; /* no data protection */
- /* do confidentiality protection if supported */
- if(gss_ret_flags & GSS_C_CONF_FLAG)
- gss_enc = 2;
- /* else do integrity protection */
- else if(gss_ret_flags & GSS_C_INTEG_FLAG)
- gss_enc = 1;
-
+ socksreq[1] = 2; /* encryption message type */
+
+ gss_enc = 0; /* no data protection */
+ /* do confidentiality protection if supported */
+ if(gss_ret_flags & GSS_C_CONF_FLAG)
+ gss_enc = 2;
+ /* else do integrity protection */
+ else if(gss_ret_flags & GSS_C_INTEG_FLAG)
+ gss_enc = 1;
+
infof(data, "SOCKS5 server supports GSS-API %s data protection.\n",
(gss_enc == 0)?"no":((gss_enc==1)?"integrity":"confidentiality"));
- /* force for the moment to no data protection */
- gss_enc = 0;
- /*
- * Sending the encryption type in clear seems wrong. It should be
- * protected with gss_seal()/gss_wrap(). See RFC1961 extract below
- * The NEC reference implementations on which this is based is
- * therefore at fault
- *
- * +------+------+------+.......................+
- * + ver | mtyp | len | token |
- * +------+------+------+.......................+
- * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets |
- * +------+------+------+.......................+
- *
- * Where:
- *
- * - "ver" is the protocol version number, here 1 to represent the
- * first version of the SOCKS/GSS-API protocol
- *
- * - "mtyp" is the message type, here 2 to represent a protection
- * -level negotiation message
- *
- * - "len" is the length of the "token" field in octets
- *
- * - "token" is the GSS-API encapsulated protection level
- *
- * The token is produced by encapsulating an octet containing the
- * required protection level using gss_seal()/gss_wrap() with conf_req
- * set to FALSE. The token is verified using gss_unseal()/
- * gss_unwrap().
- *
- */
- if(data->set.socks5_gssapi_nec) {
- us_length = htons((short)1);
+ /* force for the moment to no data protection */
+ gss_enc = 0;
+ /*
+ * Sending the encryption type in clear seems wrong. It should be
+ * protected with gss_seal()/gss_wrap(). See RFC1961 extract below
+ * The NEC reference implementations on which this is based is
+ * therefore at fault
+ *
+ * +------+------+------+.......................+
+ * + ver | mtyp | len | token |
+ * +------+------+------+.......................+
+ * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets |
+ * +------+------+------+.......................+
+ *
+ * Where:
+ *
+ * - "ver" is the protocol version number, here 1 to represent the
+ * first version of the SOCKS/GSS-API protocol
+ *
+ * - "mtyp" is the message type, here 2 to represent a protection
+ * -level negotiation message
+ *
+ * - "len" is the length of the "token" field in octets
+ *
+ * - "token" is the GSS-API encapsulated protection level
+ *
+ * The token is produced by encapsulating an octet containing the
+ * required protection level using gss_seal()/gss_wrap() with conf_req
+ * set to FALSE. The token is verified using gss_unseal()/
+ * gss_unwrap().
+ *
+ */
+ if(data->set.socks5_gssapi_nec) {
+ us_length = htons((short)1);
memcpy(socksreq + 2, &us_length, sizeof(short));
- }
- else {
- gss_send_token.length = 1;
- gss_send_token.value = malloc(1);
- if(!gss_send_token.value) {
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_OUT_OF_MEMORY;
- }
- memcpy(gss_send_token.value, &gss_enc, 1);
-
- gss_major_status = gss_wrap(&gss_minor_status, gss_context, 0,
- GSS_C_QOP_DEFAULT, &gss_send_token,
- &gss_conf_state, &gss_w_token);
-
+ }
+ else {
+ gss_send_token.length = 1;
+ gss_send_token.value = malloc(1);
+ if(!gss_send_token.value) {
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ memcpy(gss_send_token.value, &gss_enc, 1);
+
+ gss_major_status = gss_wrap(&gss_minor_status, gss_context, 0,
+ GSS_C_QOP_DEFAULT, &gss_send_token,
+ &gss_conf_state, &gss_w_token);
+
if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_wrap")) {
- gss_release_buffer(&gss_status, &gss_send_token);
- gss_release_buffer(&gss_status, &gss_w_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ gss_release_buffer(&gss_status, &gss_send_token);
+ gss_release_buffer(&gss_status, &gss_w_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
failf(data, "Failed to wrap GSS-API encryption value into token.");
- return CURLE_COULDNT_CONNECT;
- }
- gss_release_buffer(&gss_status, &gss_send_token);
-
- us_length = htons((short)gss_w_token.length);
+ return CURLE_COULDNT_CONNECT;
+ }
+ gss_release_buffer(&gss_status, &gss_send_token);
+
+ us_length = htons((short)gss_w_token.length);
memcpy(socksreq + 2, &us_length, sizeof(short));
- }
-
- code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
+ }
+
+ code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
failf(data, "Failed to send GSS-API encryption request.");
- gss_release_buffer(&gss_status, &gss_w_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(data->set.socks5_gssapi_nec) {
- memcpy(socksreq, &gss_enc, 1);
- code = Curl_write_plain(conn, sock, socksreq, 1, &written);
+ gss_release_buffer(&gss_status, &gss_w_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(data->set.socks5_gssapi_nec) {
+ memcpy(socksreq, &gss_enc, 1);
+ code = Curl_write_plain(conn, sock, socksreq, 1, &written);
if(code || ( 1 != written)) {
failf(data, "Failed to send GSS-API encryption type.");
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
- }
- else {
- code = Curl_write_plain(conn, sock, (char *)gss_w_token.value,
- gss_w_token.length, &written);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+ }
+ else {
+ code = Curl_write_plain(conn, sock, (char *)gss_w_token.value,
+ gss_w_token.length, &written);
if(code || ((ssize_t)gss_w_token.length != written)) {
failf(data, "Failed to send GSS-API encryption type.");
- gss_release_buffer(&gss_status, &gss_w_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
- gss_release_buffer(&gss_status, &gss_w_token);
- }
-
+ gss_release_buffer(&gss_status, &gss_w_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+ gss_release_buffer(&gss_status, &gss_w_token);
+ }
+
result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive GSS-API encryption response.");
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- /* ignore the first (VER) byte */
- if(socksreq[1] == 255) { /* status / message type */
- failf(data, "User was rejected by the SOCKS5 server (%d %d).",
- socksreq[0], socksreq[1]);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(socksreq[1] != 2) { /* status / messgae type */
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ /* ignore the first (VER) byte */
+ if(socksreq[1] == 255) { /* status / message type */
+ failf(data, "User was rejected by the SOCKS5 server (%d %d).",
+ socksreq[0], socksreq[1]);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(socksreq[1] != 2) { /* status / messgae type */
failf(data, "Invalid GSS-API encryption response type (%d %d).",
- socksreq[0], socksreq[1]);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
+ socksreq[0], socksreq[1]);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(&us_length, socksreq + 2, sizeof(short));
- us_length = ntohs(us_length);
-
+ us_length = ntohs(us_length);
+
gss_recv_token.length = us_length;
gss_recv_token.value = malloc(gss_recv_token.length);
- if(!gss_recv_token.value) {
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_OUT_OF_MEMORY;
- }
+ if(!gss_recv_token.value) {
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_OUT_OF_MEMORY;
+ }
result = Curl_blockread_all(conn, sock, (char *)gss_recv_token.value,
gss_recv_token.length, &actualread);
-
+
if(result || (actualread != us_length)) {
failf(data, "Failed to receive GSS-API encryptrion type.");
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(!data->set.socks5_gssapi_nec) {
- gss_major_status = gss_unwrap(&gss_minor_status, gss_context,
- &gss_recv_token, &gss_w_token,
- 0, GSS_C_QOP_DEFAULT);
-
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(!data->set.socks5_gssapi_nec) {
+ gss_major_status = gss_unwrap(&gss_minor_status, gss_context,
+ &gss_recv_token, &gss_w_token,
+ 0, GSS_C_QOP_DEFAULT);
+
if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_unwrap")) {
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_release_buffer(&gss_status, &gss_w_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_release_buffer(&gss_status, &gss_w_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
failf(data, "Failed to unwrap GSS-API encryption value into token.");
- return CURLE_COULDNT_CONNECT;
- }
- gss_release_buffer(&gss_status, &gss_recv_token);
-
- if(gss_w_token.length != 1) {
+ return CURLE_COULDNT_CONNECT;
+ }
+ gss_release_buffer(&gss_status, &gss_recv_token);
+
+ if(gss_w_token.length != 1) {
failf(data, "Invalid GSS-API encryption response length (%zu).",
- gss_w_token.length);
- gss_release_buffer(&gss_status, &gss_w_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
+ gss_w_token.length);
+ gss_release_buffer(&gss_status, &gss_w_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(socksreq, gss_w_token.value, gss_w_token.length);
- gss_release_buffer(&gss_status, &gss_w_token);
- }
- else {
- if(gss_recv_token.length != 1) {
+ gss_release_buffer(&gss_status, &gss_w_token);
+ }
+ else {
+ if(gss_recv_token.length != 1) {
failf(data, "Invalid GSS-API encryption response length (%zu).",
- gss_recv_token.length);
- gss_release_buffer(&gss_status, &gss_recv_token);
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
- return CURLE_COULDNT_CONNECT;
- }
-
+ gss_recv_token.length);
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(socksreq, gss_recv_token.value, gss_recv_token.length);
- gss_release_buffer(&gss_status, &gss_recv_token);
- }
-
+ gss_release_buffer(&gss_status, &gss_recv_token);
+ }
+
(void)curlx_nonblock(sock, TRUE);
- infof(data, "SOCKS5 access with%s protection granted.\n",
+ infof(data, "SOCKS5 access with%s protection granted.\n",
(socksreq[0] == 0)?"out GSS-API data":
((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality"));
-
- conn->socks5_gssapi_enctype = socksreq[0];
- if(socksreq[0] == 0)
- gss_delete_sec_context(&gss_status, &gss_context, NULL);
-
- return CURLE_OK;
-}
-
+
+ conn->socks5_gssapi_enctype = socksreq[0];
+ if(socksreq[0] == 0)
+ gss_delete_sec_context(&gss_status, &gss_context, NULL);
+
+ return CURLE_OK;
+}
+
#endif /* HAVE_GSSAPI && !CURL_DISABLE_PROXY */
diff --git a/contrib/libs/curl/lib/socks_sspi.c b/contrib/libs/curl/lib/socks_sspi.c
index b4bdb3cc58..b9ac2ade8e 100644
--- a/contrib/libs/curl/lib/socks_sspi.c
+++ b/contrib/libs/curl/lib/socks_sspi.c
@@ -1,609 +1,609 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- * Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com>
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ * Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com>
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_PROXY)
-
-#include "urldata.h"
-#include "sendf.h"
-#include "connect.h"
-#include "strerror.h"
-#include "timeval.h"
-#include "socks.h"
-#include "curl_sspi.h"
-#include "curl_multibyte.h"
-#include "warnless.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_PROXY)
+
+#include "urldata.h"
+#include "sendf.h"
+#include "connect.h"
+#include "strerror.h"
+#include "timeval.h"
+#include "socks.h"
+#include "curl_sspi.h"
+#include "curl_multibyte.h"
+#include "warnless.h"
#include "strdup.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/*
- * Helper sspi error functions.
- */
-static int check_sspi_err(struct connectdata *conn,
- SECURITY_STATUS status,
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/*
+ * Helper sspi error functions.
+ */
+static int check_sspi_err(struct connectdata *conn,
+ SECURITY_STATUS status,
const char *function)
-{
- if(status != SEC_E_OK &&
- status != SEC_I_COMPLETE_AND_CONTINUE &&
- status != SEC_I_COMPLETE_NEEDED &&
- status != SEC_I_CONTINUE_NEEDED) {
+{
+ if(status != SEC_E_OK &&
+ status != SEC_I_COMPLETE_AND_CONTINUE &&
+ status != SEC_I_COMPLETE_NEEDED &&
+ status != SEC_I_CONTINUE_NEEDED) {
char buffer[STRERROR_LEN];
- failf(conn->data, "SSPI error: %s failed: %s", function,
+ failf(conn->data, "SSPI error: %s failed: %s", function,
Curl_sspi_strerror(status, buffer, sizeof(buffer)));
- return 1;
- }
- return 0;
-}
-
-/* This is the SSPI-using version of this function */
-CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
- struct connectdata *conn)
-{
+ return 1;
+ }
+ return 0;
+}
+
+/* This is the SSPI-using version of this function */
+CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
+ struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
- curl_socket_t sock = conn->sock[sockindex];
- CURLcode code;
- ssize_t actualread;
- ssize_t written;
- int result;
+ curl_socket_t sock = conn->sock[sockindex];
+ CURLcode code;
+ ssize_t actualread;
+ ssize_t written;
+ int result;
/* Needs GSS-API authentication */
- SECURITY_STATUS status;
- unsigned long sspi_ret_flags = 0;
+ SECURITY_STATUS status;
+ unsigned long sspi_ret_flags = 0;
unsigned char gss_enc;
- SecBuffer sspi_send_token, sspi_recv_token, sspi_w_token[3];
- SecBufferDesc input_desc, output_desc, wrap_desc;
- SecPkgContext_Sizes sspi_sizes;
- CredHandle cred_handle;
- CtxtHandle sspi_context;
- PCtxtHandle context_handle = NULL;
- SecPkgCredentials_Names names;
- TimeStamp expiry;
- char *service_name = NULL;
- unsigned short us_length;
- unsigned long qop;
+ SecBuffer sspi_send_token, sspi_recv_token, sspi_w_token[3];
+ SecBufferDesc input_desc, output_desc, wrap_desc;
+ SecPkgContext_Sizes sspi_sizes;
+ CredHandle cred_handle;
+ CtxtHandle sspi_context;
+ PCtxtHandle context_handle = NULL;
+ SecPkgCredentials_Names names;
+ TimeStamp expiry;
+ char *service_name = NULL;
+ unsigned short us_length;
+ unsigned long qop;
unsigned char socksreq[4]; /* room for GSS-API exchange header only */
const char *service = data->set.str[STRING_PROXY_SERVICE_NAME] ?
data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd";
const size_t service_length = strlen(service);
-
+
/* GSS-API request looks like
- * +----+------+-----+----------------+
- * |VER | MTYP | LEN | TOKEN |
- * +----+------+----------------------+
- * | 1 | 1 | 2 | up to 2^16 - 1 |
- * +----+------+-----+----------------+
- */
-
- /* prepare service name */
- if(strchr(service, '/')) {
+ * +----+------+-----+----------------+
+ * |VER | MTYP | LEN | TOKEN |
+ * +----+------+----------------------+
+ * | 1 | 1 | 2 | up to 2^16 - 1 |
+ * +----+------+-----+----------------+
+ */
+
+ /* prepare service name */
+ if(strchr(service, '/')) {
service_name = strdup(service);
- if(!service_name)
- return CURLE_OUT_OF_MEMORY;
- }
- else {
+ if(!service_name)
+ return CURLE_OUT_OF_MEMORY;
+ }
+ else {
service_name = malloc(service_length +
strlen(conn->socks_proxy.host.name) + 2);
- if(!service_name)
- return CURLE_OUT_OF_MEMORY;
+ if(!service_name)
+ return CURLE_OUT_OF_MEMORY;
msnprintf(service_name, service_length +
strlen(conn->socks_proxy.host.name) + 2, "%s/%s",
service, conn->socks_proxy.host.name);
- }
-
- input_desc.cBuffers = 1;
- input_desc.pBuffers = &sspi_recv_token;
- input_desc.ulVersion = SECBUFFER_VERSION;
-
- sspi_recv_token.BufferType = SECBUFFER_TOKEN;
- sspi_recv_token.cbBuffer = 0;
- sspi_recv_token.pvBuffer = NULL;
-
- output_desc.cBuffers = 1;
- output_desc.pBuffers = &sspi_send_token;
- output_desc.ulVersion = SECBUFFER_VERSION;
-
- sspi_send_token.BufferType = SECBUFFER_TOKEN;
- sspi_send_token.cbBuffer = 0;
- sspi_send_token.pvBuffer = NULL;
-
- wrap_desc.cBuffers = 3;
- wrap_desc.pBuffers = sspi_w_token;
- wrap_desc.ulVersion = SECBUFFER_VERSION;
-
- cred_handle.dwLower = 0;
- cred_handle.dwUpper = 0;
-
- status = s_pSecFn->AcquireCredentialsHandle(NULL,
- (TCHAR *) TEXT("Kerberos"),
- SECPKG_CRED_OUTBOUND,
- NULL,
- NULL,
- NULL,
- NULL,
- &cred_handle,
- &expiry);
-
- if(check_sspi_err(conn, status, "AcquireCredentialsHandle")) {
- failf(data, "Failed to acquire credentials.");
+ }
+
+ input_desc.cBuffers = 1;
+ input_desc.pBuffers = &sspi_recv_token;
+ input_desc.ulVersion = SECBUFFER_VERSION;
+
+ sspi_recv_token.BufferType = SECBUFFER_TOKEN;
+ sspi_recv_token.cbBuffer = 0;
+ sspi_recv_token.pvBuffer = NULL;
+
+ output_desc.cBuffers = 1;
+ output_desc.pBuffers = &sspi_send_token;
+ output_desc.ulVersion = SECBUFFER_VERSION;
+
+ sspi_send_token.BufferType = SECBUFFER_TOKEN;
+ sspi_send_token.cbBuffer = 0;
+ sspi_send_token.pvBuffer = NULL;
+
+ wrap_desc.cBuffers = 3;
+ wrap_desc.pBuffers = sspi_w_token;
+ wrap_desc.ulVersion = SECBUFFER_VERSION;
+
+ cred_handle.dwLower = 0;
+ cred_handle.dwUpper = 0;
+
+ status = s_pSecFn->AcquireCredentialsHandle(NULL,
+ (TCHAR *) TEXT("Kerberos"),
+ SECPKG_CRED_OUTBOUND,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ &cred_handle,
+ &expiry);
+
+ if(check_sspi_err(conn, status, "AcquireCredentialsHandle")) {
+ failf(data, "Failed to acquire credentials.");
free(service_name);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- return CURLE_COULDNT_CONNECT;
- }
-
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ return CURLE_COULDNT_CONNECT;
+ }
+
(void)curlx_nonblock(sock, FALSE);
- /* As long as we need to keep sending some context info, and there's no */
- /* errors, keep sending it... */
- for(;;) {
- TCHAR *sname;
-
+ /* As long as we need to keep sending some context info, and there's no */
+ /* errors, keep sending it... */
+ for(;;) {
+ TCHAR *sname;
+
sname = curlx_convert_UTF8_to_tchar(service_name);
- if(!sname)
- return CURLE_OUT_OF_MEMORY;
-
- status = s_pSecFn->InitializeSecurityContext(&cred_handle,
- context_handle,
- sname,
- ISC_REQ_MUTUAL_AUTH |
- ISC_REQ_ALLOCATE_MEMORY |
- ISC_REQ_CONFIDENTIALITY |
- ISC_REQ_REPLAY_DETECT,
- 0,
- SECURITY_NATIVE_DREP,
- &input_desc,
- 0,
- &sspi_context,
- &output_desc,
- &sspi_ret_flags,
- &expiry);
-
+ if(!sname)
+ return CURLE_OUT_OF_MEMORY;
+
+ status = s_pSecFn->InitializeSecurityContext(&cred_handle,
+ context_handle,
+ sname,
+ ISC_REQ_MUTUAL_AUTH |
+ ISC_REQ_ALLOCATE_MEMORY |
+ ISC_REQ_CONFIDENTIALITY |
+ ISC_REQ_REPLAY_DETECT,
+ 0,
+ SECURITY_NATIVE_DREP,
+ &input_desc,
+ 0,
+ &sspi_context,
+ &output_desc,
+ &sspi_ret_flags,
+ &expiry);
+
curlx_unicodefree(sname);
-
- if(sspi_recv_token.pvBuffer) {
- s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
- sspi_recv_token.pvBuffer = NULL;
- sspi_recv_token.cbBuffer = 0;
- }
-
- if(check_sspi_err(conn, status, "InitializeSecurityContext")) {
+
+ if(sspi_recv_token.pvBuffer) {
+ s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
+ sspi_recv_token.pvBuffer = NULL;
+ sspi_recv_token.cbBuffer = 0;
+ }
+
+ if(check_sspi_err(conn, status, "InitializeSecurityContext")) {
free(service_name);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
- failf(data, "Failed to initialise security context.");
- return CURLE_COULDNT_CONNECT;
- }
-
- if(sspi_send_token.cbBuffer != 0) {
+ failf(data, "Failed to initialise security context.");
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(sspi_send_token.cbBuffer != 0) {
socksreq[0] = 1; /* GSS-API subnegotiation version */
- socksreq[1] = 1; /* authentication message type */
- us_length = htons((short)sspi_send_token.cbBuffer);
+ socksreq[1] = 1; /* authentication message type */
+ us_length = htons((short)sspi_send_token.cbBuffer);
memcpy(socksreq + 2, &us_length, sizeof(short));
-
- code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
+
+ code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
- failf(data, "Failed to send SSPI authentication request.");
+ failf(data, "Failed to send SSPI authentication request.");
free(service_name);
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- code = Curl_write_plain(conn, sock, (char *)sspi_send_token.pvBuffer,
- sspi_send_token.cbBuffer, &written);
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ code = Curl_write_plain(conn, sock, (char *)sspi_send_token.pvBuffer,
+ sspi_send_token.cbBuffer, &written);
if(code || (sspi_send_token.cbBuffer != (size_t)written)) {
- failf(data, "Failed to send SSPI authentication token.");
+ failf(data, "Failed to send SSPI authentication token.");
free(service_name);
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- }
-
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ }
+
if(sspi_send_token.pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
sspi_send_token.pvBuffer = NULL;
}
- sspi_send_token.cbBuffer = 0;
+ sspi_send_token.cbBuffer = 0;
if(sspi_recv_token.pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
sspi_recv_token.pvBuffer = NULL;
}
- sspi_recv_token.cbBuffer = 0;
+ sspi_recv_token.cbBuffer = 0;
+
+ if(status != SEC_I_CONTINUE_NEEDED)
+ break;
+
+ /* analyse response */
- if(status != SEC_I_CONTINUE_NEEDED)
- break;
-
- /* analyse response */
-
/* GSS-API response looks like
- * +----+------+-----+----------------+
- * |VER | MTYP | LEN | TOKEN |
- * +----+------+----------------------+
- * | 1 | 1 | 2 | up to 2^16 - 1 |
- * +----+------+-----+----------------+
- */
-
- result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
+ * +----+------+-----+----------------+
+ * |VER | MTYP | LEN | TOKEN |
+ * +----+------+----------------------+
+ * | 1 | 1 | 2 | up to 2^16 - 1 |
+ * +----+------+-----+----------------+
+ */
+
+ result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
- failf(data, "Failed to receive SSPI authentication response.");
+ failf(data, "Failed to receive SSPI authentication response.");
free(service_name);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- /* ignore the first (VER) byte */
- if(socksreq[1] == 255) { /* status / message type */
- failf(data, "User was rejected by the SOCKS5 server (%u %u).",
- (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ /* ignore the first (VER) byte */
+ if(socksreq[1] == 255) { /* status / message type */
+ failf(data, "User was rejected by the SOCKS5 server (%u %u).",
+ (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
free(service_name);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(socksreq[1] != 1) { /* status / messgae type */
- failf(data, "Invalid SSPI authentication response type (%u %u).",
- (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(socksreq[1] != 1) { /* status / messgae type */
+ failf(data, "Invalid SSPI authentication response type (%u %u).",
+ (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
free(service_name);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(&us_length, socksreq + 2, sizeof(short));
- us_length = ntohs(us_length);
-
- sspi_recv_token.cbBuffer = us_length;
- sspi_recv_token.pvBuffer = malloc(us_length);
-
- if(!sspi_recv_token.pvBuffer) {
+ us_length = ntohs(us_length);
+
+ sspi_recv_token.cbBuffer = us_length;
+ sspi_recv_token.pvBuffer = malloc(us_length);
+
+ if(!sspi_recv_token.pvBuffer) {
free(service_name);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_OUT_OF_MEMORY;
- }
- result = Curl_blockread_all(conn, sock, (char *)sspi_recv_token.pvBuffer,
- sspi_recv_token.cbBuffer, &actualread);
-
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ result = Curl_blockread_all(conn, sock, (char *)sspi_recv_token.pvBuffer,
+ sspi_recv_token.cbBuffer, &actualread);
+
if(result || (actualread != us_length)) {
- failf(data, "Failed to receive SSPI authentication token.");
+ failf(data, "Failed to receive SSPI authentication token.");
free(service_name);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- context_handle = &sspi_context;
- }
-
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ context_handle = &sspi_context;
+ }
+
free(service_name);
-
- /* Everything is good so far, user was authenticated! */
- status = s_pSecFn->QueryCredentialsAttributes(&cred_handle,
- SECPKG_CRED_ATTR_NAMES,
- &names);
- s_pSecFn->FreeCredentialsHandle(&cred_handle);
- if(check_sspi_err(conn, status, "QueryCredentialAttributes")) {
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- s_pSecFn->FreeContextBuffer(names.sUserName);
- failf(data, "Failed to determine user name.");
- return CURLE_COULDNT_CONNECT;
- }
+
+ /* Everything is good so far, user was authenticated! */
+ status = s_pSecFn->QueryCredentialsAttributes(&cred_handle,
+ SECPKG_CRED_ATTR_NAMES,
+ &names);
+ s_pSecFn->FreeCredentialsHandle(&cred_handle);
+ if(check_sspi_err(conn, status, "QueryCredentialAttributes")) {
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ s_pSecFn->FreeContextBuffer(names.sUserName);
+ failf(data, "Failed to determine user name.");
+ return CURLE_COULDNT_CONNECT;
+ }
infof(data, "SOCKS5 server authenticated user %s with GSS-API.\n",
- names.sUserName);
- s_pSecFn->FreeContextBuffer(names.sUserName);
-
- /* Do encryption */
+ names.sUserName);
+ s_pSecFn->FreeContextBuffer(names.sUserName);
+
+ /* Do encryption */
socksreq[0] = 1; /* GSS-API subnegotiation version */
- socksreq[1] = 2; /* encryption message type */
-
- gss_enc = 0; /* no data protection */
- /* do confidentiality protection if supported */
- if(sspi_ret_flags & ISC_REQ_CONFIDENTIALITY)
- gss_enc = 2;
- /* else do integrity protection */
- else if(sspi_ret_flags & ISC_REQ_INTEGRITY)
- gss_enc = 1;
-
+ socksreq[1] = 2; /* encryption message type */
+
+ gss_enc = 0; /* no data protection */
+ /* do confidentiality protection if supported */
+ if(sspi_ret_flags & ISC_REQ_CONFIDENTIALITY)
+ gss_enc = 2;
+ /* else do integrity protection */
+ else if(sspi_ret_flags & ISC_REQ_INTEGRITY)
+ gss_enc = 1;
+
infof(data, "SOCKS5 server supports GSS-API %s data protection.\n",
(gss_enc == 0)?"no":((gss_enc == 1)?"integrity":"confidentiality") );
- /* force to no data protection, avoid encryption/decryption for now */
- gss_enc = 0;
- /*
- * Sending the encryption type in clear seems wrong. It should be
- * protected with gss_seal()/gss_wrap(). See RFC1961 extract below
- * The NEC reference implementations on which this is based is
- * therefore at fault
- *
- * +------+------+------+.......................+
- * + ver | mtyp | len | token |
- * +------+------+------+.......................+
- * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets |
- * +------+------+------+.......................+
- *
- * Where:
- *
- * - "ver" is the protocol version number, here 1 to represent the
- * first version of the SOCKS/GSS-API protocol
- *
- * - "mtyp" is the message type, here 2 to represent a protection
- * -level negotiation message
- *
- * - "len" is the length of the "token" field in octets
- *
- * - "token" is the GSS-API encapsulated protection level
- *
- * The token is produced by encapsulating an octet containing the
- * required protection level using gss_seal()/gss_wrap() with conf_req
- * set to FALSE. The token is verified using gss_unseal()/
- * gss_unwrap().
- *
- */
-
- if(data->set.socks5_gssapi_nec) {
- us_length = htons((short)1);
+ /* force to no data protection, avoid encryption/decryption for now */
+ gss_enc = 0;
+ /*
+ * Sending the encryption type in clear seems wrong. It should be
+ * protected with gss_seal()/gss_wrap(). See RFC1961 extract below
+ * The NEC reference implementations on which this is based is
+ * therefore at fault
+ *
+ * +------+------+------+.......................+
+ * + ver | mtyp | len | token |
+ * +------+------+------+.......................+
+ * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets |
+ * +------+------+------+.......................+
+ *
+ * Where:
+ *
+ * - "ver" is the protocol version number, here 1 to represent the
+ * first version of the SOCKS/GSS-API protocol
+ *
+ * - "mtyp" is the message type, here 2 to represent a protection
+ * -level negotiation message
+ *
+ * - "len" is the length of the "token" field in octets
+ *
+ * - "token" is the GSS-API encapsulated protection level
+ *
+ * The token is produced by encapsulating an octet containing the
+ * required protection level using gss_seal()/gss_wrap() with conf_req
+ * set to FALSE. The token is verified using gss_unseal()/
+ * gss_unwrap().
+ *
+ */
+
+ if(data->set.socks5_gssapi_nec) {
+ us_length = htons((short)1);
memcpy(socksreq + 2, &us_length, sizeof(short));
- }
- else {
- status = s_pSecFn->QueryContextAttributes(&sspi_context,
- SECPKG_ATTR_SIZES,
- &sspi_sizes);
- if(check_sspi_err(conn, status, "QueryContextAttributes")) {
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- failf(data, "Failed to query security context attributes.");
- return CURLE_COULDNT_CONNECT;
- }
-
- sspi_w_token[0].cbBuffer = sspi_sizes.cbSecurityTrailer;
- sspi_w_token[0].BufferType = SECBUFFER_TOKEN;
- sspi_w_token[0].pvBuffer = malloc(sspi_sizes.cbSecurityTrailer);
-
- if(!sspi_w_token[0].pvBuffer) {
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_OUT_OF_MEMORY;
- }
-
- sspi_w_token[1].cbBuffer = 1;
- sspi_w_token[1].pvBuffer = malloc(1);
- if(!sspi_w_token[1].pvBuffer) {
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_OUT_OF_MEMORY;
- }
-
+ }
+ else {
+ status = s_pSecFn->QueryContextAttributes(&sspi_context,
+ SECPKG_ATTR_SIZES,
+ &sspi_sizes);
+ if(check_sspi_err(conn, status, "QueryContextAttributes")) {
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ failf(data, "Failed to query security context attributes.");
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ sspi_w_token[0].cbBuffer = sspi_sizes.cbSecurityTrailer;
+ sspi_w_token[0].BufferType = SECBUFFER_TOKEN;
+ sspi_w_token[0].pvBuffer = malloc(sspi_sizes.cbSecurityTrailer);
+
+ if(!sspi_w_token[0].pvBuffer) {
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ sspi_w_token[1].cbBuffer = 1;
+ sspi_w_token[1].pvBuffer = malloc(1);
+ if(!sspi_w_token[1].pvBuffer) {
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
memcpy(sspi_w_token[1].pvBuffer, &gss_enc, 1);
- sspi_w_token[2].BufferType = SECBUFFER_PADDING;
- sspi_w_token[2].cbBuffer = sspi_sizes.cbBlockSize;
- sspi_w_token[2].pvBuffer = malloc(sspi_sizes.cbBlockSize);
- if(!sspi_w_token[2].pvBuffer) {
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_OUT_OF_MEMORY;
- }
- status = s_pSecFn->EncryptMessage(&sspi_context,
- KERB_WRAP_NO_ENCRYPT,
- &wrap_desc,
- 0);
- if(check_sspi_err(conn, status, "EncryptMessage")) {
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- failf(data, "Failed to query security context attributes.");
- return CURLE_COULDNT_CONNECT;
- }
- sspi_send_token.cbBuffer = sspi_w_token[0].cbBuffer
- + sspi_w_token[1].cbBuffer
- + sspi_w_token[2].cbBuffer;
- sspi_send_token.pvBuffer = malloc(sspi_send_token.cbBuffer);
- if(!sspi_send_token.pvBuffer) {
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_OUT_OF_MEMORY;
- }
-
- memcpy(sspi_send_token.pvBuffer, sspi_w_token[0].pvBuffer,
- sspi_w_token[0].cbBuffer);
- memcpy((PUCHAR) sspi_send_token.pvBuffer +(int)sspi_w_token[0].cbBuffer,
- sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer);
- memcpy((PUCHAR) sspi_send_token.pvBuffer
+ sspi_w_token[2].BufferType = SECBUFFER_PADDING;
+ sspi_w_token[2].cbBuffer = sspi_sizes.cbBlockSize;
+ sspi_w_token[2].pvBuffer = malloc(sspi_sizes.cbBlockSize);
+ if(!sspi_w_token[2].pvBuffer) {
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ status = s_pSecFn->EncryptMessage(&sspi_context,
+ KERB_WRAP_NO_ENCRYPT,
+ &wrap_desc,
+ 0);
+ if(check_sspi_err(conn, status, "EncryptMessage")) {
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ failf(data, "Failed to query security context attributes.");
+ return CURLE_COULDNT_CONNECT;
+ }
+ sspi_send_token.cbBuffer = sspi_w_token[0].cbBuffer
+ + sspi_w_token[1].cbBuffer
+ + sspi_w_token[2].cbBuffer;
+ sspi_send_token.pvBuffer = malloc(sspi_send_token.cbBuffer);
+ if(!sspi_send_token.pvBuffer) {
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ memcpy(sspi_send_token.pvBuffer, sspi_w_token[0].pvBuffer,
+ sspi_w_token[0].cbBuffer);
+ memcpy((PUCHAR) sspi_send_token.pvBuffer +(int)sspi_w_token[0].cbBuffer,
+ sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer);
+ memcpy((PUCHAR) sspi_send_token.pvBuffer
+ sspi_w_token[0].cbBuffer
+ sspi_w_token[1].cbBuffer,
- sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer);
-
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- sspi_w_token[0].pvBuffer = NULL;
- sspi_w_token[0].cbBuffer = 0;
- s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- sspi_w_token[1].pvBuffer = NULL;
- sspi_w_token[1].cbBuffer = 0;
- s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
- sspi_w_token[2].pvBuffer = NULL;
- sspi_w_token[2].cbBuffer = 0;
-
- us_length = htons((short)sspi_send_token.cbBuffer);
+ sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer);
+
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ sspi_w_token[0].pvBuffer = NULL;
+ sspi_w_token[0].cbBuffer = 0;
+ s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
+ sspi_w_token[1].pvBuffer = NULL;
+ sspi_w_token[1].cbBuffer = 0;
+ s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
+ sspi_w_token[2].pvBuffer = NULL;
+ sspi_w_token[2].cbBuffer = 0;
+
+ us_length = htons((short)sspi_send_token.cbBuffer);
memcpy(socksreq + 2, &us_length, sizeof(short));
- }
-
- code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
+ }
+
+ code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
- failf(data, "Failed to send SSPI encryption request.");
+ failf(data, "Failed to send SSPI encryption request.");
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(data->set.socks5_gssapi_nec) {
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(data->set.socks5_gssapi_nec) {
memcpy(socksreq, &gss_enc, 1);
- code = Curl_write_plain(conn, sock, (char *)socksreq, 1, &written);
+ code = Curl_write_plain(conn, sock, (char *)socksreq, 1, &written);
if(code || (1 != written)) {
- failf(data, "Failed to send SSPI encryption type.");
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
- }
- else {
- code = Curl_write_plain(conn, sock, (char *)sspi_send_token.pvBuffer,
- sspi_send_token.cbBuffer, &written);
+ failf(data, "Failed to send SSPI encryption type.");
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+ }
+ else {
+ code = Curl_write_plain(conn, sock, (char *)sspi_send_token.pvBuffer,
+ sspi_send_token.cbBuffer, &written);
if(code || (sspi_send_token.cbBuffer != (size_t)written)) {
- failf(data, "Failed to send SSPI encryption type.");
+ failf(data, "Failed to send SSPI encryption type.");
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
- }
-
- result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
+ }
+
+ result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
- failf(data, "Failed to receive SSPI encryption response.");
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- /* ignore the first (VER) byte */
- if(socksreq[1] == 255) { /* status / message type */
- failf(data, "User was rejected by the SOCKS5 server (%u %u).",
- (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
- if(socksreq[1] != 2) { /* status / message type */
- failf(data, "Invalid SSPI encryption response type (%u %u).",
- (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
+ failf(data, "Failed to receive SSPI encryption response.");
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ /* ignore the first (VER) byte */
+ if(socksreq[1] == 255) { /* status / message type */
+ failf(data, "User was rejected by the SOCKS5 server (%u %u).",
+ (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(socksreq[1] != 2) { /* status / message type */
+ failf(data, "Invalid SSPI encryption response type (%u %u).",
+ (unsigned int)socksreq[0], (unsigned int)socksreq[1]);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(&us_length, socksreq + 2, sizeof(short));
- us_length = ntohs(us_length);
-
- sspi_w_token[0].cbBuffer = us_length;
- sspi_w_token[0].pvBuffer = malloc(us_length);
- if(!sspi_w_token[0].pvBuffer) {
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_OUT_OF_MEMORY;
- }
-
- result = Curl_blockread_all(conn, sock, (char *)sspi_w_token[0].pvBuffer,
- sspi_w_token[0].cbBuffer, &actualread);
-
+ us_length = ntohs(us_length);
+
+ sspi_w_token[0].cbBuffer = us_length;
+ sspi_w_token[0].pvBuffer = malloc(us_length);
+ if(!sspi_w_token[0].pvBuffer) {
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ result = Curl_blockread_all(conn, sock, (char *)sspi_w_token[0].pvBuffer,
+ sspi_w_token[0].cbBuffer, &actualread);
+
if(result || (actualread != us_length)) {
- failf(data, "Failed to receive SSPI encryption type.");
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
-
- if(!data->set.socks5_gssapi_nec) {
- wrap_desc.cBuffers = 2;
- sspi_w_token[0].BufferType = SECBUFFER_STREAM;
- sspi_w_token[1].BufferType = SECBUFFER_DATA;
- sspi_w_token[1].cbBuffer = 0;
- sspi_w_token[1].pvBuffer = NULL;
-
- status = s_pSecFn->DecryptMessage(&sspi_context,
- &wrap_desc,
- 0,
- &qop);
-
- if(check_sspi_err(conn, status, "DecryptMessage")) {
+ failf(data, "Failed to receive SSPI encryption type.");
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
+
+ if(!data->set.socks5_gssapi_nec) {
+ wrap_desc.cBuffers = 2;
+ sspi_w_token[0].BufferType = SECBUFFER_STREAM;
+ sspi_w_token[1].BufferType = SECBUFFER_DATA;
+ sspi_w_token[1].cbBuffer = 0;
+ sspi_w_token[1].pvBuffer = NULL;
+
+ status = s_pSecFn->DecryptMessage(&sspi_context,
+ &wrap_desc,
+ 0,
+ &qop);
+
+ if(check_sspi_err(conn, status, "DecryptMessage")) {
if(sspi_w_token[0].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
if(sspi_w_token[1].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- failf(data, "Failed to query security context attributes.");
- return CURLE_COULDNT_CONNECT;
- }
-
- if(sspi_w_token[1].cbBuffer != 1) {
- failf(data, "Invalid SSPI encryption response length (%lu).",
- (unsigned long)sspi_w_token[1].cbBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ failf(data, "Failed to query security context attributes.");
+ return CURLE_COULDNT_CONNECT;
+ }
+
+ if(sspi_w_token[1].cbBuffer != 1) {
+ failf(data, "Invalid SSPI encryption response length (%lu).",
+ (unsigned long)sspi_w_token[1].cbBuffer);
if(sspi_w_token[0].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
if(sspi_w_token[1].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
-
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
+
memcpy(socksreq, sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
- }
- else {
- if(sspi_w_token[0].cbBuffer != 1) {
- failf(data, "Invalid SSPI encryption response length (%lu).",
- (unsigned long)sspi_w_token[0].cbBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- return CURLE_COULDNT_CONNECT;
- }
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
+ }
+ else {
+ if(sspi_w_token[0].cbBuffer != 1) {
+ failf(data, "Invalid SSPI encryption response length (%lu).",
+ (unsigned long)sspi_w_token[0].cbBuffer);
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ return CURLE_COULDNT_CONNECT;
+ }
memcpy(socksreq, sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer);
- s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
- }
+ s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
+ }
(void)curlx_nonblock(sock, TRUE);
-
- infof(data, "SOCKS5 access with%s protection granted.\n",
+
+ infof(data, "SOCKS5 access with%s protection granted.\n",
(socksreq[0] == 0)?"out GSS-API data":
((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality"));
-
- /* For later use if encryption is required
- conn->socks5_gssapi_enctype = socksreq[0];
- if(socksreq[0] != 0)
- conn->socks5_sspi_context = sspi_context;
- else {
- s_pSecFn->DeleteSecurityContext(&sspi_context);
- conn->socks5_sspi_context = sspi_context;
- }
- */
- return CURLE_OK;
-}
-#endif
+
+ /* For later use if encryption is required
+ conn->socks5_gssapi_enctype = socksreq[0];
+ if(socksreq[0] != 0)
+ conn->socks5_sspi_context = sspi_context;
+ else {
+ s_pSecFn->DeleteSecurityContext(&sspi_context);
+ conn->socks5_sspi_context = sspi_context;
+ }
+ */
+ return CURLE_OK;
+}
+#endif
diff --git a/contrib/libs/curl/lib/speedcheck.c b/contrib/libs/curl/lib/speedcheck.c
index 00c54f48f2..2665a44c55 100644
--- a/contrib/libs/curl/lib/speedcheck.c
+++ b/contrib/libs/curl/lib/speedcheck.c
@@ -1,44 +1,44 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-#include "urldata.h"
-#include "sendf.h"
-#include "multiif.h"
-#include "speedcheck.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "sendf.h"
+#include "multiif.h"
+#include "speedcheck.h"
+
void Curl_speedinit(struct Curl_easy *data)
-{
+{
memset(&data->state.keeps_speed, 0, sizeof(struct curltime));
-}
-
+}
+
/*
* @unittest: 1606
*/
CURLcode Curl_speedcheck(struct Curl_easy *data,
struct curltime now)
-{
+{
if((data->progress.current_speed >= 0) && data->set.low_speed_time) {
if(data->progress.current_speed < data->set.low_speed_limit) {
if(!data->state.keeps_speed.tv_sec)
@@ -47,7 +47,7 @@ CURLcode Curl_speedcheck(struct Curl_easy *data,
else {
/* how long has it been under the limit */
timediff_t howlong = Curl_timediff(now, data->state.keeps_speed);
-
+
if(howlong >= data->set.low_speed_time * 1000) {
/* too long */
failf(data,
@@ -58,16 +58,16 @@ CURLcode Curl_speedcheck(struct Curl_easy *data,
return CURLE_OPERATION_TIMEDOUT;
}
}
- }
+ }
else
/* faster right now */
data->state.keeps_speed.tv_sec = 0;
- }
-
+ }
+
if(data->set.low_speed_limit)
/* if low speed limit is enabled, set the expire timer to make this
connection's speed get checked again in a second */
Curl_expire(data, 1000, EXPIRE_SPEEDCHECK);
- return CURLE_OK;
-}
+ return CURLE_OK;
+}
diff --git a/contrib/libs/curl/lib/speedcheck.h b/contrib/libs/curl/lib/speedcheck.h
index b17c346f26..1d4c7bfeff 100644
--- a/contrib/libs/curl/lib/speedcheck.h
+++ b/contrib/libs/curl/lib/speedcheck.h
@@ -1,33 +1,33 @@
-#ifndef HEADER_CURL_SPEEDCHECK_H
-#define HEADER_CURL_SPEEDCHECK_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SPEEDCHECK_H
+#define HEADER_CURL_SPEEDCHECK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "timeval.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include "timeval.h"
+
void Curl_speedinit(struct Curl_easy *data);
CURLcode Curl_speedcheck(struct Curl_easy *data,
struct curltime now);
-
-#endif /* HEADER_CURL_SPEEDCHECK_H */
+
+#endif /* HEADER_CURL_SPEEDCHECK_H */
diff --git a/contrib/libs/curl/lib/splay.c b/contrib/libs/curl/lib/splay.c
index 7bddae1160..98baf5d871 100644
--- a/contrib/libs/curl/lib/splay.c
+++ b/contrib/libs/curl/lib/splay.c
@@ -1,276 +1,276 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1997 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "splay.h"
-
-/*
- * This macro compares two node keys i and j and returns:
- *
- * negative value: when i is smaller than j
- * zero : when i is equal to j
- * positive when : when i is larger than j
- */
-#define compare(i,j) Curl_splaycomparekeys((i),(j))
-
-/*
- * Splay using the key i (which may or may not be in the tree.) The starting
- * root is t.
- */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include "splay.h"
+
+/*
+ * This macro compares two node keys i and j and returns:
+ *
+ * negative value: when i is smaller than j
+ * zero : when i is equal to j
+ * positive when : when i is larger than j
+ */
+#define compare(i,j) Curl_splaycomparekeys((i),(j))
+
+/*
+ * Splay using the key i (which may or may not be in the tree.) The starting
+ * root is t.
+ */
struct Curl_tree *Curl_splay(struct curltime i,
- struct Curl_tree *t)
-{
- struct Curl_tree N, *l, *r, *y;
-
- if(t == NULL)
- return t;
- N.smaller = N.larger = NULL;
- l = r = &N;
-
- for(;;) {
+ struct Curl_tree *t)
+{
+ struct Curl_tree N, *l, *r, *y;
+
+ if(t == NULL)
+ return t;
+ N.smaller = N.larger = NULL;
+ l = r = &N;
+
+ for(;;) {
long comp = compare(i, t->key);
- if(comp < 0) {
- if(t->smaller == NULL)
- break;
- if(compare(i, t->smaller->key) < 0) {
- y = t->smaller; /* rotate smaller */
- t->smaller = y->larger;
- y->larger = t;
- t = y;
- if(t->smaller == NULL)
- break;
- }
- r->smaller = t; /* link smaller */
- r = t;
- t = t->smaller;
- }
- else if(comp > 0) {
- if(t->larger == NULL)
- break;
- if(compare(i, t->larger->key) > 0) {
- y = t->larger; /* rotate larger */
- t->larger = y->smaller;
- y->smaller = t;
- t = y;
- if(t->larger == NULL)
- break;
- }
- l->larger = t; /* link larger */
- l = t;
- t = t->larger;
- }
- else
- break;
- }
-
- l->larger = t->smaller; /* assemble */
- r->smaller = t->larger;
- t->smaller = N.larger;
- t->larger = N.smaller;
-
- return t;
-}
-
-/* Insert key i into the tree t. Return a pointer to the resulting tree or
- * NULL if something went wrong.
- *
- * @unittest: 1309
- */
+ if(comp < 0) {
+ if(t->smaller == NULL)
+ break;
+ if(compare(i, t->smaller->key) < 0) {
+ y = t->smaller; /* rotate smaller */
+ t->smaller = y->larger;
+ y->larger = t;
+ t = y;
+ if(t->smaller == NULL)
+ break;
+ }
+ r->smaller = t; /* link smaller */
+ r = t;
+ t = t->smaller;
+ }
+ else if(comp > 0) {
+ if(t->larger == NULL)
+ break;
+ if(compare(i, t->larger->key) > 0) {
+ y = t->larger; /* rotate larger */
+ t->larger = y->smaller;
+ y->smaller = t;
+ t = y;
+ if(t->larger == NULL)
+ break;
+ }
+ l->larger = t; /* link larger */
+ l = t;
+ t = t->larger;
+ }
+ else
+ break;
+ }
+
+ l->larger = t->smaller; /* assemble */
+ r->smaller = t->larger;
+ t->smaller = N.larger;
+ t->larger = N.smaller;
+
+ return t;
+}
+
+/* Insert key i into the tree t. Return a pointer to the resulting tree or
+ * NULL if something went wrong.
+ *
+ * @unittest: 1309
+ */
struct Curl_tree *Curl_splayinsert(struct curltime i,
- struct Curl_tree *t,
- struct Curl_tree *node)
-{
+ struct Curl_tree *t,
+ struct Curl_tree *node)
+{
static const struct curltime KEY_NOTUSED = {
(time_t)-1, (unsigned int)-1
}; /* will *NEVER* appear */
-
- if(node == NULL)
- return t;
-
- if(t != NULL) {
+
+ if(node == NULL)
+ return t;
+
+ if(t != NULL) {
t = Curl_splay(i, t);
if(compare(i, t->key) == 0) {
- /* There already exists a node in the tree with the very same key. Build
+ /* There already exists a node in the tree with the very same key. Build
a doubly-linked circular list of nodes. We add the new 'node' struct
to the end of this list. */
-
+
node->key = KEY_NOTUSED; /* we set the key in the sub node to NOTUSED
to quickly identify this node as a subnode */
node->samen = t;
node->samep = t->samep;
t->samep->samen = node;
t->samep = node;
-
+
return t; /* the root node always stays the same */
- }
- }
-
- if(t == NULL) {
- node->smaller = node->larger = NULL;
- }
- else if(compare(i, t->key) < 0) {
- node->smaller = t->smaller;
- node->larger = t;
- t->smaller = NULL;
-
- }
- else {
- node->larger = t->larger;
- node->smaller = t;
- t->larger = NULL;
- }
- node->key = i;
-
+ }
+ }
+
+ if(t == NULL) {
+ node->smaller = node->larger = NULL;
+ }
+ else if(compare(i, t->key) < 0) {
+ node->smaller = t->smaller;
+ node->larger = t;
+ t->smaller = NULL;
+
+ }
+ else {
+ node->larger = t->larger;
+ node->smaller = t;
+ t->larger = NULL;
+ }
+ node->key = i;
+
/* no identical nodes (yet), we are the only one in the list of nodes */
node->samen = node;
node->samep = node;
- return node;
-}
-
-/* Finds and deletes the best-fit node from the tree. Return a pointer to the
+ return node;
+}
+
+/* Finds and deletes the best-fit node from the tree. Return a pointer to the
resulting tree. best-fit means the smallest node if it is not larger than
the key */
struct Curl_tree *Curl_splaygetbest(struct curltime i,
- struct Curl_tree *t,
- struct Curl_tree **removed)
-{
+ struct Curl_tree *t,
+ struct Curl_tree **removed)
+{
static struct curltime tv_zero = {0, 0};
- struct Curl_tree *x;
-
- if(!t) {
- *removed = NULL; /* none removed since there was no root */
- return NULL;
- }
-
+ struct Curl_tree *x;
+
+ if(!t) {
+ *removed = NULL; /* none removed since there was no root */
+ return NULL;
+ }
+
/* find smallest */
t = Curl_splay(tv_zero, t);
- if(compare(i, t->key) < 0) {
+ if(compare(i, t->key) < 0) {
/* even the smallest is too big */
*removed = NULL;
return t;
- }
-
+ }
+
/* FIRST! Check if there is a list with identical keys */
x = t->samen;
if(x != t) {
/* there is, pick one from the list */
-
+
/* 'x' is the new root node */
-
+
x->key = t->key;
x->larger = t->larger;
x->smaller = t->smaller;
x->samep = t->samep;
t->samep->samen = x;
-
- *removed = t;
+
+ *removed = t;
return x; /* new root */
}
-
+
/* we splayed the tree to the smallest element, there is no smaller */
x = t->larger;
*removed = t;
return x;
-}
-
-
-/* Deletes the very node we point out from the tree if it's there. Stores a
- * pointer to the new resulting tree in 'newroot'.
- *
+}
+
+
+/* Deletes the very node we point out from the tree if it's there. Stores a
+ * pointer to the new resulting tree in 'newroot'.
+ *
* Returns zero on success and non-zero on errors!
- * When returning error, it does not touch the 'newroot' pointer.
- *
- * NOTE: when the last node of the tree is removed, there's no tree left so
- * 'newroot' will be made to point to NULL.
- *
- * @unittest: 1309
- */
+ * When returning error, it does not touch the 'newroot' pointer.
+ *
+ * NOTE: when the last node of the tree is removed, there's no tree left so
+ * 'newroot' will be made to point to NULL.
+ *
+ * @unittest: 1309
+ */
int Curl_splayremove(struct Curl_tree *t,
struct Curl_tree *removenode,
struct Curl_tree **newroot)
-{
+{
static const struct curltime KEY_NOTUSED = {
(time_t)-1, (unsigned int)-1
}; /* will *NEVER* appear */
- struct Curl_tree *x;
-
- if(!t || !removenode)
- return 1;
-
- if(compare(KEY_NOTUSED, removenode->key) == 0) {
- /* Key set to NOTUSED means it is a subnode within a 'same' linked list
+ struct Curl_tree *x;
+
+ if(!t || !removenode)
+ return 1;
+
+ if(compare(KEY_NOTUSED, removenode->key) == 0) {
+ /* Key set to NOTUSED means it is a subnode within a 'same' linked list
and thus we can unlink it easily. */
if(removenode->samen == removenode)
/* A non-subnode should never be set to KEY_NOTUSED */
- return 3;
-
+ return 3;
+
removenode->samep->samen = removenode->samen;
removenode->samen->samep = removenode->samep;
-
- /* Ensures that double-remove gets caught. */
+
+ /* Ensures that double-remove gets caught. */
removenode->samen = removenode;
-
- *newroot = t; /* return the same root */
- return 0;
- }
-
- t = Curl_splay(removenode->key, t);
-
- /* First make sure that we got the same root node as the one we want
- to remove, as otherwise we might be trying to remove a node that
- isn't actually in the tree.
-
- We cannot just compare the keys here as a double remove in quick
- succession of a node with key != KEY_NOTUSED && same != NULL
- could return the same key but a different node. */
- if(t != removenode)
- return 2;
-
- /* Check if there is a list with identical sizes, as then we're trying to
- remove the root node of a list of nodes with identical keys. */
+
+ *newroot = t; /* return the same root */
+ return 0;
+ }
+
+ t = Curl_splay(removenode->key, t);
+
+ /* First make sure that we got the same root node as the one we want
+ to remove, as otherwise we might be trying to remove a node that
+ isn't actually in the tree.
+
+ We cannot just compare the keys here as a double remove in quick
+ succession of a node with key != KEY_NOTUSED && same != NULL
+ could return the same key but a different node. */
+ if(t != removenode)
+ return 2;
+
+ /* Check if there is a list with identical sizes, as then we're trying to
+ remove the root node of a list of nodes with identical keys. */
x = t->samen;
if(x != t) {
- /* 'x' is the new root node, we just make it use the root node's
- smaller/larger links */
-
- x->key = t->key;
- x->larger = t->larger;
- x->smaller = t->smaller;
+ /* 'x' is the new root node, we just make it use the root node's
+ smaller/larger links */
+
+ x->key = t->key;
+ x->larger = t->larger;
+ x->smaller = t->smaller;
x->samep = t->samep;
t->samep->samen = x;
- }
- else {
- /* Remove the root node */
- if(t->smaller == NULL)
- x = t->larger;
- else {
- x = Curl_splay(removenode->key, t->smaller);
- x->larger = t->larger;
- }
- }
-
- *newroot = x; /* store new root pointer */
-
- return 0;
-}
+ }
+ else {
+ /* Remove the root node */
+ if(t->smaller == NULL)
+ x = t->larger;
+ else {
+ x = Curl_splay(removenode->key, t->smaller);
+ x->larger = t->larger;
+ }
+ }
+
+ *newroot = x; /* store new root pointer */
+
+ return 0;
+}
diff --git a/contrib/libs/curl/lib/splay.h b/contrib/libs/curl/lib/splay.h
index 7b979cca37..eb9f65f1e0 100644
--- a/contrib/libs/curl/lib/splay.h
+++ b/contrib/libs/curl/lib/splay.h
@@ -1,56 +1,56 @@
-#ifndef HEADER_CURL_SPLAY_H
-#define HEADER_CURL_SPLAY_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_SPLAY_H
+#define HEADER_CURL_SPLAY_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1997 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
#include "timeval.h"
-
-struct Curl_tree {
- struct Curl_tree *smaller; /* smaller node */
- struct Curl_tree *larger; /* larger node */
+
+struct Curl_tree {
+ struct Curl_tree *smaller; /* smaller node */
+ struct Curl_tree *larger; /* larger node */
struct Curl_tree *samen; /* points to the next node with identical key */
struct Curl_tree *samep; /* points to the prev node with identical key */
struct curltime key; /* this node's "sort" key */
- void *payload; /* data the splay code doesn't care about */
-};
-
+ void *payload; /* data the splay code doesn't care about */
+};
+
struct Curl_tree *Curl_splay(struct curltime i,
- struct Curl_tree *t);
-
+ struct Curl_tree *t);
+
struct Curl_tree *Curl_splayinsert(struct curltime key,
- struct Curl_tree *t,
- struct Curl_tree *newnode);
-
+ struct Curl_tree *t,
+ struct Curl_tree *newnode);
+
struct Curl_tree *Curl_splaygetbest(struct curltime key,
- struct Curl_tree *t,
- struct Curl_tree **removed);
-
+ struct Curl_tree *t,
+ struct Curl_tree **removed);
+
int Curl_splayremove(struct Curl_tree *t,
struct Curl_tree *removenode,
struct Curl_tree **newroot);
-
+
#define Curl_splaycomparekeys(i,j) ( ((i.tv_sec) < (j.tv_sec)) ? -1 : \
( ((i.tv_sec) > (j.tv_sec)) ? 1 : \
- ( ((i.tv_usec) < (j.tv_usec)) ? -1 : \
+ ( ((i.tv_usec) < (j.tv_usec)) ? -1 : \
( ((i.tv_usec) > (j.tv_usec)) ? 1 : 0))))
-
-#endif /* HEADER_CURL_SPLAY_H */
+
+#endif /* HEADER_CURL_SPLAY_H */
diff --git a/contrib/libs/curl/lib/strdup.c b/contrib/libs/curl/lib/strdup.c
index 57fbb93ce2..9af47ea473 100644
--- a/contrib/libs/curl/lib/strdup.c
+++ b/contrib/libs/curl/lib/strdup.c
@@ -1,54 +1,54 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
-#include "curl_setup.h"
-
#include <curl/curl.h>
-#include "strdup.h"
+#include "strdup.h"
#include "curl_memory.h"
-
+
/* The last #include file should be: */
#include "memdebug.h"
-#ifndef HAVE_STRDUP
-char *curlx_strdup(const char *str)
-{
- size_t len;
- char *newstr;
-
- if(!str)
- return (char *)NULL;
-
+#ifndef HAVE_STRDUP
+char *curlx_strdup(const char *str)
+{
+ size_t len;
+ char *newstr;
+
+ if(!str)
+ return (char *)NULL;
+
len = strlen(str) + 1;
-
+
newstr = malloc(len);
- if(!newstr)
- return (char *)NULL;
-
+ if(!newstr)
+ return (char *)NULL;
+
memcpy(newstr, str, len);
- return newstr;
-}
-#endif
+ return newstr;
+}
+#endif
/***************************************************************************
*
diff --git a/contrib/libs/curl/lib/strdup.h b/contrib/libs/curl/lib/strdup.h
index 1003fa48b8..0936956f89 100644
--- a/contrib/libs/curl/lib/strdup.h
+++ b/contrib/libs/curl/lib/strdup.h
@@ -1,32 +1,32 @@
-#ifndef HEADER_CURL_STRDUP_H
-#define HEADER_CURL_STRDUP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_STRDUP_H
+#define HEADER_CURL_STRDUP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
-#ifndef HAVE_STRDUP
-extern char *curlx_strdup(const char *str);
-#endif
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
+#ifndef HAVE_STRDUP
+extern char *curlx_strdup(const char *str);
+#endif
void *Curl_memdup(const void *src, size_t buffer_length);
void *Curl_saferealloc(void *ptr, size_t size);
-
-#endif /* HEADER_CURL_STRDUP_H */
+
+#endif /* HEADER_CURL_STRDUP_H */
diff --git a/contrib/libs/curl/lib/strerror.c b/contrib/libs/curl/lib/strerror.c
index 72ee2ea536..1751fd38f5 100644
--- a/contrib/libs/curl/lib/strerror.c
+++ b/contrib/libs/curl/lib/strerror.c
@@ -1,304 +1,304 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2004 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_STRERROR_R
-# if (!defined(HAVE_POSIX_STRERROR_R) && \
- !defined(HAVE_GLIBC_STRERROR_R) && \
- !defined(HAVE_VXWORKS_STRERROR_R)) || \
- (defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)) || \
- (defined(HAVE_GLIBC_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)) || \
- (defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R))
-# error "strerror_r MUST be either POSIX, glibc or vxworks-style"
-# endif
-#endif
-
-#include <curl/curl.h>
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_STRERROR_R
+# if (!defined(HAVE_POSIX_STRERROR_R) && \
+ !defined(HAVE_GLIBC_STRERROR_R) && \
+ !defined(HAVE_VXWORKS_STRERROR_R)) || \
+ (defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)) || \
+ (defined(HAVE_GLIBC_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)) || \
+ (defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R))
+# error "strerror_r MUST be either POSIX, glibc or vxworks-style"
+# endif
+#endif
+
+#include <curl/curl.h>
+
#ifdef USE_LIBIDN2
#error #include <idn2.h>
-#endif
-
+#endif
+
#ifdef USE_WINDOWS_SSPI
#include "curl_sspi.h"
#endif
-#include "strerror.h"
+#include "strerror.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
#if defined(WIN32) || defined(_WIN32_WCE)
#define PRESERVE_WINDOWS_ERROR_CODE
#endif
-const char *
-curl_easy_strerror(CURLcode error)
-{
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+const char *
+curl_easy_strerror(CURLcode error)
+{
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
- case CURLE_OK:
- return "No error";
-
- case CURLE_UNSUPPORTED_PROTOCOL:
- return "Unsupported protocol";
-
- case CURLE_FAILED_INIT:
- return "Failed initialization";
-
- case CURLE_URL_MALFORMAT:
- return "URL using bad/illegal format or missing URL";
-
- case CURLE_NOT_BUILT_IN:
- return "A requested feature, protocol or option was not found built-in in"
- " this libcurl due to a build-time decision.";
-
- case CURLE_COULDNT_RESOLVE_PROXY:
- return "Couldn't resolve proxy name";
-
- case CURLE_COULDNT_RESOLVE_HOST:
- return "Couldn't resolve host name";
-
- case CURLE_COULDNT_CONNECT:
- return "Couldn't connect to server";
-
+ case CURLE_OK:
+ return "No error";
+
+ case CURLE_UNSUPPORTED_PROTOCOL:
+ return "Unsupported protocol";
+
+ case CURLE_FAILED_INIT:
+ return "Failed initialization";
+
+ case CURLE_URL_MALFORMAT:
+ return "URL using bad/illegal format or missing URL";
+
+ case CURLE_NOT_BUILT_IN:
+ return "A requested feature, protocol or option was not found built-in in"
+ " this libcurl due to a build-time decision.";
+
+ case CURLE_COULDNT_RESOLVE_PROXY:
+ return "Couldn't resolve proxy name";
+
+ case CURLE_COULDNT_RESOLVE_HOST:
+ return "Couldn't resolve host name";
+
+ case CURLE_COULDNT_CONNECT:
+ return "Couldn't connect to server";
+
case CURLE_WEIRD_SERVER_REPLY:
return "Weird server reply";
-
- case CURLE_REMOTE_ACCESS_DENIED:
- return "Access denied to remote resource";
-
- case CURLE_FTP_ACCEPT_FAILED:
- return "FTP: The server failed to connect to data port";
-
- case CURLE_FTP_ACCEPT_TIMEOUT:
- return "FTP: Accepting server connect has timed out";
-
- case CURLE_FTP_PRET_FAILED:
- return "FTP: The server did not accept the PRET command.";
-
- case CURLE_FTP_WEIRD_PASS_REPLY:
- return "FTP: unknown PASS reply";
-
- case CURLE_FTP_WEIRD_PASV_REPLY:
- return "FTP: unknown PASV reply";
-
- case CURLE_FTP_WEIRD_227_FORMAT:
- return "FTP: unknown 227 response format";
-
- case CURLE_FTP_CANT_GET_HOST:
- return "FTP: can't figure out the host in the PASV response";
-
+
+ case CURLE_REMOTE_ACCESS_DENIED:
+ return "Access denied to remote resource";
+
+ case CURLE_FTP_ACCEPT_FAILED:
+ return "FTP: The server failed to connect to data port";
+
+ case CURLE_FTP_ACCEPT_TIMEOUT:
+ return "FTP: Accepting server connect has timed out";
+
+ case CURLE_FTP_PRET_FAILED:
+ return "FTP: The server did not accept the PRET command.";
+
+ case CURLE_FTP_WEIRD_PASS_REPLY:
+ return "FTP: unknown PASS reply";
+
+ case CURLE_FTP_WEIRD_PASV_REPLY:
+ return "FTP: unknown PASV reply";
+
+ case CURLE_FTP_WEIRD_227_FORMAT:
+ return "FTP: unknown 227 response format";
+
+ case CURLE_FTP_CANT_GET_HOST:
+ return "FTP: can't figure out the host in the PASV response";
+
case CURLE_HTTP2:
return "Error in the HTTP2 framing layer";
- case CURLE_FTP_COULDNT_SET_TYPE:
- return "FTP: couldn't set file type";
-
- case CURLE_PARTIAL_FILE:
- return "Transferred a partial file";
-
- case CURLE_FTP_COULDNT_RETR_FILE:
- return "FTP: couldn't retrieve (RETR failed) the specified file";
-
- case CURLE_QUOTE_ERROR:
- return "Quote command returned error";
-
- case CURLE_HTTP_RETURNED_ERROR:
- return "HTTP response code said error";
-
- case CURLE_WRITE_ERROR:
- return "Failed writing received data to disk/application";
-
- case CURLE_UPLOAD_FAILED:
- return "Upload failed (at start/before it took off)";
-
- case CURLE_READ_ERROR:
- return "Failed to open/read local data from file/application";
-
- case CURLE_OUT_OF_MEMORY:
- return "Out of memory";
-
- case CURLE_OPERATION_TIMEDOUT:
- return "Timeout was reached";
-
- case CURLE_FTP_PORT_FAILED:
- return "FTP: command PORT failed";
-
- case CURLE_FTP_COULDNT_USE_REST:
- return "FTP: command REST failed";
-
- case CURLE_RANGE_ERROR:
- return "Requested range was not delivered by the server";
-
- case CURLE_HTTP_POST_ERROR:
- return "Internal problem setting up the POST";
-
- case CURLE_SSL_CONNECT_ERROR:
- return "SSL connect error";
-
- case CURLE_BAD_DOWNLOAD_RESUME:
- return "Couldn't resume download";
-
- case CURLE_FILE_COULDNT_READ_FILE:
- return "Couldn't read a file:// file";
-
- case CURLE_LDAP_CANNOT_BIND:
- return "LDAP: cannot bind";
-
- case CURLE_LDAP_SEARCH_FAILED:
- return "LDAP: search failed";
-
- case CURLE_FUNCTION_NOT_FOUND:
- return "A required function in the library was not found";
-
- case CURLE_ABORTED_BY_CALLBACK:
- return "Operation was aborted by an application callback";
-
- case CURLE_BAD_FUNCTION_ARGUMENT:
- return "A libcurl function was given a bad argument";
-
- case CURLE_INTERFACE_FAILED:
- return "Failed binding local connection end";
-
- case CURLE_TOO_MANY_REDIRECTS :
- return "Number of redirects hit maximum amount";
-
- case CURLE_UNKNOWN_OPTION:
- return "An unknown option was passed in to libcurl";
-
- case CURLE_TELNET_OPTION_SYNTAX :
- return "Malformed telnet option";
-
- case CURLE_GOT_NOTHING:
- return "Server returned nothing (no headers, no data)";
-
- case CURLE_SSL_ENGINE_NOTFOUND:
- return "SSL crypto engine not found";
-
- case CURLE_SSL_ENGINE_SETFAILED:
- return "Can not set SSL crypto engine as default";
-
- case CURLE_SSL_ENGINE_INITFAILED:
- return "Failed to initialise SSL crypto engine";
-
- case CURLE_SEND_ERROR:
- return "Failed sending data to the peer";
-
- case CURLE_RECV_ERROR:
- return "Failure when receiving data from the peer";
-
- case CURLE_SSL_CERTPROBLEM:
- return "Problem with the local SSL certificate";
-
- case CURLE_SSL_CIPHER:
- return "Couldn't use specified SSL cipher";
-
+ case CURLE_FTP_COULDNT_SET_TYPE:
+ return "FTP: couldn't set file type";
+
+ case CURLE_PARTIAL_FILE:
+ return "Transferred a partial file";
+
+ case CURLE_FTP_COULDNT_RETR_FILE:
+ return "FTP: couldn't retrieve (RETR failed) the specified file";
+
+ case CURLE_QUOTE_ERROR:
+ return "Quote command returned error";
+
+ case CURLE_HTTP_RETURNED_ERROR:
+ return "HTTP response code said error";
+
+ case CURLE_WRITE_ERROR:
+ return "Failed writing received data to disk/application";
+
+ case CURLE_UPLOAD_FAILED:
+ return "Upload failed (at start/before it took off)";
+
+ case CURLE_READ_ERROR:
+ return "Failed to open/read local data from file/application";
+
+ case CURLE_OUT_OF_MEMORY:
+ return "Out of memory";
+
+ case CURLE_OPERATION_TIMEDOUT:
+ return "Timeout was reached";
+
+ case CURLE_FTP_PORT_FAILED:
+ return "FTP: command PORT failed";
+
+ case CURLE_FTP_COULDNT_USE_REST:
+ return "FTP: command REST failed";
+
+ case CURLE_RANGE_ERROR:
+ return "Requested range was not delivered by the server";
+
+ case CURLE_HTTP_POST_ERROR:
+ return "Internal problem setting up the POST";
+
+ case CURLE_SSL_CONNECT_ERROR:
+ return "SSL connect error";
+
+ case CURLE_BAD_DOWNLOAD_RESUME:
+ return "Couldn't resume download";
+
+ case CURLE_FILE_COULDNT_READ_FILE:
+ return "Couldn't read a file:// file";
+
+ case CURLE_LDAP_CANNOT_BIND:
+ return "LDAP: cannot bind";
+
+ case CURLE_LDAP_SEARCH_FAILED:
+ return "LDAP: search failed";
+
+ case CURLE_FUNCTION_NOT_FOUND:
+ return "A required function in the library was not found";
+
+ case CURLE_ABORTED_BY_CALLBACK:
+ return "Operation was aborted by an application callback";
+
+ case CURLE_BAD_FUNCTION_ARGUMENT:
+ return "A libcurl function was given a bad argument";
+
+ case CURLE_INTERFACE_FAILED:
+ return "Failed binding local connection end";
+
+ case CURLE_TOO_MANY_REDIRECTS :
+ return "Number of redirects hit maximum amount";
+
+ case CURLE_UNKNOWN_OPTION:
+ return "An unknown option was passed in to libcurl";
+
+ case CURLE_TELNET_OPTION_SYNTAX :
+ return "Malformed telnet option";
+
+ case CURLE_GOT_NOTHING:
+ return "Server returned nothing (no headers, no data)";
+
+ case CURLE_SSL_ENGINE_NOTFOUND:
+ return "SSL crypto engine not found";
+
+ case CURLE_SSL_ENGINE_SETFAILED:
+ return "Can not set SSL crypto engine as default";
+
+ case CURLE_SSL_ENGINE_INITFAILED:
+ return "Failed to initialise SSL crypto engine";
+
+ case CURLE_SEND_ERROR:
+ return "Failed sending data to the peer";
+
+ case CURLE_RECV_ERROR:
+ return "Failure when receiving data from the peer";
+
+ case CURLE_SSL_CERTPROBLEM:
+ return "Problem with the local SSL certificate";
+
+ case CURLE_SSL_CIPHER:
+ return "Couldn't use specified SSL cipher";
+
case CURLE_PEER_FAILED_VERIFICATION:
return "SSL peer certificate or SSH remote key was not OK";
-
- case CURLE_SSL_CACERT_BADFILE:
- return "Problem with the SSL CA cert (path? access rights?)";
-
- case CURLE_BAD_CONTENT_ENCODING:
- return "Unrecognized or bad HTTP Content or Transfer-Encoding";
-
- case CURLE_LDAP_INVALID_URL:
- return "Invalid LDAP URL";
-
- case CURLE_FILESIZE_EXCEEDED:
- return "Maximum file size exceeded";
-
- case CURLE_USE_SSL_FAILED:
- return "Requested SSL level failed";
-
- case CURLE_SSL_SHUTDOWN_FAILED:
- return "Failed to shut down the SSL connection";
-
- case CURLE_SSL_CRL_BADFILE:
- return "Failed to load CRL file (path? access rights?, format?)";
-
- case CURLE_SSL_ISSUER_ERROR:
- return "Issuer check against peer certificate failed";
-
- case CURLE_SEND_FAIL_REWIND:
- return "Send failed since rewinding of the data stream failed";
-
- case CURLE_LOGIN_DENIED:
- return "Login denied";
-
- case CURLE_TFTP_NOTFOUND:
- return "TFTP: File Not Found";
-
- case CURLE_TFTP_PERM:
- return "TFTP: Access Violation";
-
- case CURLE_REMOTE_DISK_FULL:
- return "Disk full or allocation exceeded";
-
- case CURLE_TFTP_ILLEGAL:
- return "TFTP: Illegal operation";
-
- case CURLE_TFTP_UNKNOWNID:
- return "TFTP: Unknown transfer ID";
-
- case CURLE_REMOTE_FILE_EXISTS:
- return "Remote file already exists";
-
- case CURLE_TFTP_NOSUCHUSER:
- return "TFTP: No such user";
-
- case CURLE_CONV_FAILED:
- return "Conversion failed";
-
- case CURLE_CONV_REQD:
- return "Caller must register CURLOPT_CONV_ callback options";
-
- case CURLE_REMOTE_FILE_NOT_FOUND:
- return "Remote file not found";
-
- case CURLE_SSH:
- return "Error in the SSH layer";
-
- case CURLE_AGAIN:
- return "Socket not ready for send/recv";
-
- case CURLE_RTSP_CSEQ_ERROR:
- return "RTSP CSeq mismatch or invalid CSeq";
-
- case CURLE_RTSP_SESSION_ERROR:
- return "RTSP session error";
-
- case CURLE_FTP_BAD_FILE_LIST:
- return "Unable to parse FTP file list";
-
- case CURLE_CHUNK_FAILED:
- return "Chunk callback failed";
-
- case CURLE_NO_CONNECTION_AVAILABLE:
- return "The max connection limit is reached";
-
+
+ case CURLE_SSL_CACERT_BADFILE:
+ return "Problem with the SSL CA cert (path? access rights?)";
+
+ case CURLE_BAD_CONTENT_ENCODING:
+ return "Unrecognized or bad HTTP Content or Transfer-Encoding";
+
+ case CURLE_LDAP_INVALID_URL:
+ return "Invalid LDAP URL";
+
+ case CURLE_FILESIZE_EXCEEDED:
+ return "Maximum file size exceeded";
+
+ case CURLE_USE_SSL_FAILED:
+ return "Requested SSL level failed";
+
+ case CURLE_SSL_SHUTDOWN_FAILED:
+ return "Failed to shut down the SSL connection";
+
+ case CURLE_SSL_CRL_BADFILE:
+ return "Failed to load CRL file (path? access rights?, format?)";
+
+ case CURLE_SSL_ISSUER_ERROR:
+ return "Issuer check against peer certificate failed";
+
+ case CURLE_SEND_FAIL_REWIND:
+ return "Send failed since rewinding of the data stream failed";
+
+ case CURLE_LOGIN_DENIED:
+ return "Login denied";
+
+ case CURLE_TFTP_NOTFOUND:
+ return "TFTP: File Not Found";
+
+ case CURLE_TFTP_PERM:
+ return "TFTP: Access Violation";
+
+ case CURLE_REMOTE_DISK_FULL:
+ return "Disk full or allocation exceeded";
+
+ case CURLE_TFTP_ILLEGAL:
+ return "TFTP: Illegal operation";
+
+ case CURLE_TFTP_UNKNOWNID:
+ return "TFTP: Unknown transfer ID";
+
+ case CURLE_REMOTE_FILE_EXISTS:
+ return "Remote file already exists";
+
+ case CURLE_TFTP_NOSUCHUSER:
+ return "TFTP: No such user";
+
+ case CURLE_CONV_FAILED:
+ return "Conversion failed";
+
+ case CURLE_CONV_REQD:
+ return "Caller must register CURLOPT_CONV_ callback options";
+
+ case CURLE_REMOTE_FILE_NOT_FOUND:
+ return "Remote file not found";
+
+ case CURLE_SSH:
+ return "Error in the SSH layer";
+
+ case CURLE_AGAIN:
+ return "Socket not ready for send/recv";
+
+ case CURLE_RTSP_CSEQ_ERROR:
+ return "RTSP CSeq mismatch or invalid CSeq";
+
+ case CURLE_RTSP_SESSION_ERROR:
+ return "RTSP session error";
+
+ case CURLE_FTP_BAD_FILE_LIST:
+ return "Unable to parse FTP file list";
+
+ case CURLE_CHUNK_FAILED:
+ return "Chunk callback failed";
+
+ case CURLE_NO_CONNECTION_AVAILABLE:
+ return "The max connection limit is reached";
+
case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
return "SSL public key does not match pinned public key";
@@ -323,75 +323,75 @@ curl_easy_strerror(CURLcode error)
case CURLE_PROXY:
return "proxy handshake error";
- /* error codes not used by current libcurl */
- case CURLE_OBSOLETE20:
- case CURLE_OBSOLETE24:
- case CURLE_OBSOLETE29:
- case CURLE_OBSOLETE32:
- case CURLE_OBSOLETE40:
- case CURLE_OBSOLETE44:
- case CURLE_OBSOLETE46:
- case CURLE_OBSOLETE50:
+ /* error codes not used by current libcurl */
+ case CURLE_OBSOLETE20:
+ case CURLE_OBSOLETE24:
+ case CURLE_OBSOLETE29:
+ case CURLE_OBSOLETE32:
+ case CURLE_OBSOLETE40:
+ case CURLE_OBSOLETE44:
+ case CURLE_OBSOLETE46:
+ case CURLE_OBSOLETE50:
case CURLE_OBSOLETE51:
- case CURLE_OBSOLETE57:
- case CURL_LAST:
- break;
- }
- /*
- * By using a switch, gcc -Wall will complain about enum values
- * which do not appear, helping keep this function up-to-date.
- * By using gcc -Wall -Werror, you can't forget.
- *
- * A table would not have the same benefit. Most compilers will
- * generate code very similar to a table in any case, so there
- * is little performance gain from a table. And something is broken
- * for the user's application, anyways, so does it matter how fast
- * it _doesn't_ work?
- *
- * The line number for the error will be near this comment, which
- * is why it is here, and not at the start of the switch.
- */
- return "Unknown error";
-#else
+ case CURLE_OBSOLETE57:
+ case CURL_LAST:
+ break;
+ }
+ /*
+ * By using a switch, gcc -Wall will complain about enum values
+ * which do not appear, helping keep this function up-to-date.
+ * By using gcc -Wall -Werror, you can't forget.
+ *
+ * A table would not have the same benefit. Most compilers will
+ * generate code very similar to a table in any case, so there
+ * is little performance gain from a table. And something is broken
+ * for the user's application, anyways, so does it matter how fast
+ * it _doesn't_ work?
+ *
+ * The line number for the error will be near this comment, which
+ * is why it is here, and not at the start of the switch.
+ */
+ return "Unknown error";
+#else
if(!error)
- return "No error";
- else
- return "Error";
-#endif
-}
-
-const char *
-curl_multi_strerror(CURLMcode error)
-{
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+ return "No error";
+ else
+ return "Error";
+#endif
+}
+
+const char *
+curl_multi_strerror(CURLMcode error)
+{
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
- case CURLM_CALL_MULTI_PERFORM:
- return "Please call curl_multi_perform() soon";
-
- case CURLM_OK:
- return "No error";
-
- case CURLM_BAD_HANDLE:
- return "Invalid multi handle";
-
- case CURLM_BAD_EASY_HANDLE:
- return "Invalid easy handle";
-
- case CURLM_OUT_OF_MEMORY:
- return "Out of memory";
-
- case CURLM_INTERNAL_ERROR:
- return "Internal error";
-
- case CURLM_BAD_SOCKET:
- return "Invalid socket argument";
-
- case CURLM_UNKNOWN_OPTION:
- return "Unknown option";
-
- case CURLM_ADDED_ALREADY:
- return "The easy handle is already added to a multi handle";
-
+ case CURLM_CALL_MULTI_PERFORM:
+ return "Please call curl_multi_perform() soon";
+
+ case CURLM_OK:
+ return "No error";
+
+ case CURLM_BAD_HANDLE:
+ return "Invalid multi handle";
+
+ case CURLM_BAD_EASY_HANDLE:
+ return "Invalid easy handle";
+
+ case CURLM_OUT_OF_MEMORY:
+ return "Out of memory";
+
+ case CURLM_INTERNAL_ERROR:
+ return "Internal error";
+
+ case CURLM_BAD_SOCKET:
+ return "Invalid socket argument";
+
+ case CURLM_UNKNOWN_OPTION:
+ return "Unknown option";
+
+ case CURLM_ADDED_ALREADY:
+ return "The easy handle is already added to a multi handle";
+
case CURLM_RECURSIVE_API_CALL:
return "API function called from within callback";
@@ -401,67 +401,67 @@ curl_multi_strerror(CURLMcode error)
case CURLM_BAD_FUNCTION_ARGUMENT:
return "A libcurl function was given a bad argument";
- case CURLM_LAST:
- break;
- }
-
- return "Unknown error";
-#else
- if(error == CURLM_OK)
- return "No error";
- else
- return "Error";
-#endif
-}
-
-const char *
-curl_share_strerror(CURLSHcode error)
-{
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+ case CURLM_LAST:
+ break;
+ }
+
+ return "Unknown error";
+#else
+ if(error == CURLM_OK)
+ return "No error";
+ else
+ return "Error";
+#endif
+}
+
+const char *
+curl_share_strerror(CURLSHcode error)
+{
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
- case CURLSHE_OK:
- return "No error";
-
- case CURLSHE_BAD_OPTION:
- return "Unknown share option";
-
- case CURLSHE_IN_USE:
- return "Share currently in use";
-
- case CURLSHE_INVALID:
- return "Invalid share handle";
-
- case CURLSHE_NOMEM:
- return "Out of memory";
-
- case CURLSHE_NOT_BUILT_IN:
- return "Feature not enabled in this library";
-
- case CURLSHE_LAST:
- break;
- }
-
- return "CURLSHcode unknown";
-#else
- if(error == CURLSHE_OK)
- return "No error";
- else
- return "Error";
-#endif
-}
-
-#ifdef USE_WINSOCK
+ case CURLSHE_OK:
+ return "No error";
+
+ case CURLSHE_BAD_OPTION:
+ return "Unknown share option";
+
+ case CURLSHE_IN_USE:
+ return "Share currently in use";
+
+ case CURLSHE_INVALID:
+ return "Invalid share handle";
+
+ case CURLSHE_NOMEM:
+ return "Out of memory";
+
+ case CURLSHE_NOT_BUILT_IN:
+ return "Feature not enabled in this library";
+
+ case CURLSHE_LAST:
+ break;
+ }
+
+ return "CURLSHcode unknown";
+#else
+ if(error == CURLSHE_OK)
+ return "No error";
+ else
+ return "Error";
+#endif
+}
+
+#ifdef USE_WINSOCK
/* This is a helper function for Curl_strerror that converts Winsock error
* codes (WSAGetLastError) to error messages.
* Returns NULL if no error message was found for error code.
- */
-static const char *
-get_winsock_error (int err, char *buf, size_t len)
-{
+ */
+static const char *
+get_winsock_error (int err, char *buf, size_t len)
+{
#ifndef CURL_DISABLE_VERBOSE_STRINGS
const char *p;
#endif
-
+
if(!len)
return NULL;
@@ -472,175 +472,175 @@ get_winsock_error (int err, char *buf, size_t len)
return NULL;
#else
switch(err) {
- case WSAEINTR:
- p = "Call interrupted";
- break;
- case WSAEBADF:
- p = "Bad file";
- break;
- case WSAEACCES:
- p = "Bad access";
- break;
- case WSAEFAULT:
- p = "Bad argument";
- break;
- case WSAEINVAL:
- p = "Invalid arguments";
- break;
- case WSAEMFILE:
- p = "Out of file descriptors";
- break;
- case WSAEWOULDBLOCK:
- p = "Call would block";
- break;
- case WSAEINPROGRESS:
- case WSAEALREADY:
- p = "Blocking call in progress";
- break;
- case WSAENOTSOCK:
- p = "Descriptor is not a socket";
- break;
- case WSAEDESTADDRREQ:
- p = "Need destination address";
- break;
- case WSAEMSGSIZE:
- p = "Bad message size";
- break;
- case WSAEPROTOTYPE:
- p = "Bad protocol";
- break;
- case WSAENOPROTOOPT:
- p = "Protocol option is unsupported";
- break;
- case WSAEPROTONOSUPPORT:
- p = "Protocol is unsupported";
- break;
- case WSAESOCKTNOSUPPORT:
- p = "Socket is unsupported";
- break;
- case WSAEOPNOTSUPP:
- p = "Operation not supported";
- break;
- case WSAEAFNOSUPPORT:
- p = "Address family not supported";
- break;
- case WSAEPFNOSUPPORT:
- p = "Protocol family not supported";
- break;
- case WSAEADDRINUSE:
- p = "Address already in use";
- break;
- case WSAEADDRNOTAVAIL:
- p = "Address not available";
- break;
- case WSAENETDOWN:
- p = "Network down";
- break;
- case WSAENETUNREACH:
- p = "Network unreachable";
- break;
- case WSAENETRESET:
- p = "Network has been reset";
- break;
- case WSAECONNABORTED:
- p = "Connection was aborted";
- break;
- case WSAECONNRESET:
- p = "Connection was reset";
- break;
- case WSAENOBUFS:
- p = "No buffer space";
- break;
- case WSAEISCONN:
- p = "Socket is already connected";
- break;
- case WSAENOTCONN:
- p = "Socket is not connected";
- break;
- case WSAESHUTDOWN:
- p = "Socket has been shut down";
- break;
- case WSAETOOMANYREFS:
- p = "Too many references";
- break;
- case WSAETIMEDOUT:
- p = "Timed out";
- break;
- case WSAECONNREFUSED:
- p = "Connection refused";
- break;
- case WSAELOOP:
- p = "Loop??";
- break;
- case WSAENAMETOOLONG:
- p = "Name too long";
- break;
- case WSAEHOSTDOWN:
- p = "Host down";
- break;
- case WSAEHOSTUNREACH:
- p = "Host unreachable";
- break;
- case WSAENOTEMPTY:
- p = "Not empty";
- break;
- case WSAEPROCLIM:
- p = "Process limit reached";
- break;
- case WSAEUSERS:
- p = "Too many users";
- break;
- case WSAEDQUOT:
- p = "Bad quota";
- break;
- case WSAESTALE:
- p = "Something is stale";
- break;
- case WSAEREMOTE:
- p = "Remote error";
- break;
-#ifdef WSAEDISCON /* missing in SalfordC! */
- case WSAEDISCON:
- p = "Disconnected";
- break;
-#endif
- /* Extended Winsock errors */
- case WSASYSNOTREADY:
- p = "Winsock library is not ready";
- break;
- case WSANOTINITIALISED:
- p = "Winsock library not initialised";
- break;
- case WSAVERNOTSUPPORTED:
- p = "Winsock version not supported";
- break;
-
- /* getXbyY() errors (already handled in herrmsg):
- * Authoritative Answer: Host not found */
- case WSAHOST_NOT_FOUND:
- p = "Host not found";
- break;
-
- /* Non-Authoritative: Host not found, or SERVERFAIL */
- case WSATRY_AGAIN:
- p = "Host not found, try again";
- break;
-
- /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */
- case WSANO_RECOVERY:
- p = "Unrecoverable error in call to nameserver";
- break;
-
- /* Valid name, no data record of requested type */
- case WSANO_DATA:
- p = "No data record of requested type";
- break;
-
- default:
- return NULL;
- }
+ case WSAEINTR:
+ p = "Call interrupted";
+ break;
+ case WSAEBADF:
+ p = "Bad file";
+ break;
+ case WSAEACCES:
+ p = "Bad access";
+ break;
+ case WSAEFAULT:
+ p = "Bad argument";
+ break;
+ case WSAEINVAL:
+ p = "Invalid arguments";
+ break;
+ case WSAEMFILE:
+ p = "Out of file descriptors";
+ break;
+ case WSAEWOULDBLOCK:
+ p = "Call would block";
+ break;
+ case WSAEINPROGRESS:
+ case WSAEALREADY:
+ p = "Blocking call in progress";
+ break;
+ case WSAENOTSOCK:
+ p = "Descriptor is not a socket";
+ break;
+ case WSAEDESTADDRREQ:
+ p = "Need destination address";
+ break;
+ case WSAEMSGSIZE:
+ p = "Bad message size";
+ break;
+ case WSAEPROTOTYPE:
+ p = "Bad protocol";
+ break;
+ case WSAENOPROTOOPT:
+ p = "Protocol option is unsupported";
+ break;
+ case WSAEPROTONOSUPPORT:
+ p = "Protocol is unsupported";
+ break;
+ case WSAESOCKTNOSUPPORT:
+ p = "Socket is unsupported";
+ break;
+ case WSAEOPNOTSUPP:
+ p = "Operation not supported";
+ break;
+ case WSAEAFNOSUPPORT:
+ p = "Address family not supported";
+ break;
+ case WSAEPFNOSUPPORT:
+ p = "Protocol family not supported";
+ break;
+ case WSAEADDRINUSE:
+ p = "Address already in use";
+ break;
+ case WSAEADDRNOTAVAIL:
+ p = "Address not available";
+ break;
+ case WSAENETDOWN:
+ p = "Network down";
+ break;
+ case WSAENETUNREACH:
+ p = "Network unreachable";
+ break;
+ case WSAENETRESET:
+ p = "Network has been reset";
+ break;
+ case WSAECONNABORTED:
+ p = "Connection was aborted";
+ break;
+ case WSAECONNRESET:
+ p = "Connection was reset";
+ break;
+ case WSAENOBUFS:
+ p = "No buffer space";
+ break;
+ case WSAEISCONN:
+ p = "Socket is already connected";
+ break;
+ case WSAENOTCONN:
+ p = "Socket is not connected";
+ break;
+ case WSAESHUTDOWN:
+ p = "Socket has been shut down";
+ break;
+ case WSAETOOMANYREFS:
+ p = "Too many references";
+ break;
+ case WSAETIMEDOUT:
+ p = "Timed out";
+ break;
+ case WSAECONNREFUSED:
+ p = "Connection refused";
+ break;
+ case WSAELOOP:
+ p = "Loop??";
+ break;
+ case WSAENAMETOOLONG:
+ p = "Name too long";
+ break;
+ case WSAEHOSTDOWN:
+ p = "Host down";
+ break;
+ case WSAEHOSTUNREACH:
+ p = "Host unreachable";
+ break;
+ case WSAENOTEMPTY:
+ p = "Not empty";
+ break;
+ case WSAEPROCLIM:
+ p = "Process limit reached";
+ break;
+ case WSAEUSERS:
+ p = "Too many users";
+ break;
+ case WSAEDQUOT:
+ p = "Bad quota";
+ break;
+ case WSAESTALE:
+ p = "Something is stale";
+ break;
+ case WSAEREMOTE:
+ p = "Remote error";
+ break;
+#ifdef WSAEDISCON /* missing in SalfordC! */
+ case WSAEDISCON:
+ p = "Disconnected";
+ break;
+#endif
+ /* Extended Winsock errors */
+ case WSASYSNOTREADY:
+ p = "Winsock library is not ready";
+ break;
+ case WSANOTINITIALISED:
+ p = "Winsock library not initialised";
+ break;
+ case WSAVERNOTSUPPORTED:
+ p = "Winsock version not supported";
+ break;
+
+ /* getXbyY() errors (already handled in herrmsg):
+ * Authoritative Answer: Host not found */
+ case WSAHOST_NOT_FOUND:
+ p = "Host not found";
+ break;
+
+ /* Non-Authoritative: Host not found, or SERVERFAIL */
+ case WSATRY_AGAIN:
+ p = "Host not found, try again";
+ break;
+
+ /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */
+ case WSANO_RECOVERY:
+ p = "Unrecoverable error in call to nameserver";
+ break;
+
+ /* Valid name, no data record of requested type */
+ case WSANO_DATA:
+ p = "No data record of requested type";
+ break;
+
+ default:
+ return NULL;
+ }
strncpy(buf, p, len);
- buf [len-1] = '\0';
+ buf [len-1] = '\0';
return buf;
#endif
}
@@ -687,19 +687,19 @@ get_winapi_error(int err, char *buf, size_t buflen)
}
return (*buf ? buf : NULL);
-}
+}
#endif /* WIN32 || _WIN32_WCE */
-
-/*
- * Our thread-safe and smart strerror() replacement.
- *
- * The 'err' argument passed in to this function MUST be a true errno number
- * as reported on this system. We do no range checking on the number before
- * we pass it to the "number-to-message" conversion function and there might
- * be systems that don't do proper range checking in there themselves.
- *
- * We don't do range checking (on systems other than Windows) since there is
- * no good reliable and portable way to do it.
+
+/*
+ * Our thread-safe and smart strerror() replacement.
+ *
+ * The 'err' argument passed in to this function MUST be a true errno number
+ * as reported on this system. We do no range checking on the number before
+ * we pass it to the "number-to-message" conversion function and there might
+ * be systems that don't do proper range checking in there themselves.
+ *
+ * We don't do range checking (on systems other than Windows) since there is
+ * no good reliable and portable way to do it.
*
* On Windows different types of error codes overlap. This function has an
* order of preference when trying to match error codes:
@@ -708,29 +708,29 @@ get_winapi_error(int err, char *buf, size_t buflen)
* It may be more correct to call one of the variant functions instead:
* Call Curl_sspi_strerror if the error code is definitely Windows SSPI.
* Call Curl_winapi_strerror if the error code is definitely Windows API.
- */
+ */
const char *Curl_strerror(int err, char *buf, size_t buflen)
-{
+{
#ifdef PRESERVE_WINDOWS_ERROR_CODE
DWORD old_win_err = GetLastError();
#endif
int old_errno = errno;
char *p;
- size_t max;
-
+ size_t max;
+
if(!buflen)
return NULL;
- DEBUGASSERT(err >= 0);
-
+ DEBUGASSERT(err >= 0);
+
max = buflen - 1;
- *buf = '\0';
-
+ *buf = '\0';
+
#if defined(WIN32) || defined(_WIN32_WCE)
#if defined(WIN32)
- /* 'sys_nerr' is the maximum errno number, it is not widely portable */
- if(err >= 0 && err < sys_nerr)
- strncpy(buf, strerror(err), max);
+ /* 'sys_nerr' is the maximum errno number, it is not widely portable */
+ if(err >= 0 && err < sys_nerr)
+ strncpy(buf, strerror(err), max);
else
#endif
{
@@ -740,78 +740,78 @@ const char *Curl_strerror(int err, char *buf, size_t buflen)
#endif
!get_winapi_error((DWORD)err, buf, max))
msnprintf(buf, max, "Unknown error %d (%#x)", err, err);
- }
+ }
#else /* not Windows coming up */
-
-#if defined(HAVE_STRERROR_R) && defined(HAVE_POSIX_STRERROR_R)
- /*
- * The POSIX-style strerror_r() may set errno to ERANGE if insufficient
- * storage is supplied via 'strerrbuf' and 'buflen' to hold the generated
- * message string, or EINVAL if 'errnum' is not a valid error number.
- */
- if(0 != strerror_r(err, buf, max)) {
- if('\0' == buf[0])
+
+#if defined(HAVE_STRERROR_R) && defined(HAVE_POSIX_STRERROR_R)
+ /*
+ * The POSIX-style strerror_r() may set errno to ERANGE if insufficient
+ * storage is supplied via 'strerrbuf' and 'buflen' to hold the generated
+ * message string, or EINVAL if 'errnum' is not a valid error number.
+ */
+ if(0 != strerror_r(err, buf, max)) {
+ if('\0' == buf[0])
msnprintf(buf, max, "Unknown error %d", err);
- }
-#elif defined(HAVE_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R)
- /*
- * The glibc-style strerror_r() only *might* use the buffer we pass to
- * the function, but it always returns the error message as a pointer,
- * so we must copy that string unconditionally (if non-NULL).
- */
- {
- char buffer[256];
- char *msg = strerror_r(err, buffer, sizeof(buffer));
- if(msg)
- strncpy(buf, msg, max);
- else
+ }
+#elif defined(HAVE_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R)
+ /*
+ * The glibc-style strerror_r() only *might* use the buffer we pass to
+ * the function, but it always returns the error message as a pointer,
+ * so we must copy that string unconditionally (if non-NULL).
+ */
+ {
+ char buffer[256];
+ char *msg = strerror_r(err, buffer, sizeof(buffer));
+ if(msg)
+ strncpy(buf, msg, max);
+ else
msnprintf(buf, max, "Unknown error %d", err);
- }
-#elif defined(HAVE_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)
- /*
- * The vxworks-style strerror_r() does use the buffer we pass to the function.
+ }
+#elif defined(HAVE_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)
+ /*
+ * The vxworks-style strerror_r() does use the buffer we pass to the function.
* The buffer size should be at least NAME_MAX (256)
- */
- {
- char buffer[256];
- if(OK == strerror_r(err, buffer))
- strncpy(buf, buffer, max);
- else
+ */
+ {
+ char buffer[256];
+ if(OK == strerror_r(err, buffer))
+ strncpy(buf, buffer, max);
+ else
msnprintf(buf, max, "Unknown error %d", err);
- }
-#else
- {
+ }
+#else
+ {
const char *msg = strerror(err);
- if(msg)
- strncpy(buf, msg, max);
- else
+ if(msg)
+ strncpy(buf, msg, max);
+ else
msnprintf(buf, max, "Unknown error %d", err);
- }
-#endif
-
+ }
+#endif
+
#endif /* end of not Windows */
-
+
buf[max] = '\0'; /* make sure the string is null-terminated */
-
- /* strip trailing '\r\n' or '\n'. */
+
+ /* strip trailing '\r\n' or '\n'. */
p = strrchr(buf, '\n');
if(p && (p - buf) >= 2)
*p = '\0';
p = strrchr(buf, '\r');
if(p && (p - buf) >= 1)
*p = '\0';
-
+
if(errno != old_errno)
errno = old_errno;
-
+
#ifdef PRESERVE_WINDOWS_ERROR_CODE
if(old_win_err != GetLastError())
SetLastError(old_win_err);
#endif
- return buf;
-}
-
+ return buf;
+}
+
/*
* Curl_winapi_strerror:
* Variant of Curl_strerror if the error code is definitely Windows API.
@@ -853,30 +853,30 @@ const char *Curl_winapi_strerror(DWORD err, char *buf, size_t buflen)
}
#endif /* WIN32 || _WIN32_WCE */
-#ifdef USE_WINDOWS_SSPI
+#ifdef USE_WINDOWS_SSPI
/*
* Curl_sspi_strerror:
* Variant of Curl_strerror if the error code is definitely Windows SSPI.
*/
const char *Curl_sspi_strerror(int err, char *buf, size_t buflen)
-{
+{
#ifdef PRESERVE_WINDOWS_ERROR_CODE
DWORD old_win_err = GetLastError();
#endif
int old_errno = errno;
const char *txt;
-
+
if(!buflen)
return NULL;
-
+
*buf = '\0';
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+
switch(err) {
- case SEC_E_OK:
- txt = "No error";
- break;
+ case SEC_E_OK:
+ txt = "No error";
+ break;
#define SEC2TXT(sec) case sec: txt = #sec; break
SEC2TXT(CRYPT_E_REVOKED);
SEC2TXT(SEC_E_ALGORITHM_MISMATCH);
@@ -958,10 +958,10 @@ const char *Curl_sspi_strerror(int err, char *buf, size_t buflen)
SEC2TXT(SEC_I_NO_LSA_CONTEXT);
SEC2TXT(SEC_I_RENEGOTIATE);
SEC2TXT(SEC_I_SIGNATURE_NEEDED);
- default:
- txt = "Unknown error";
- }
-
+ default:
+ txt = "Unknown error";
+ }
+
if(err == SEC_E_ILLEGAL_MESSAGE) {
msnprintf(buf, buflen,
"SEC_E_ILLEGAL_MESSAGE (0x%08X) - This error usually occurs "
@@ -969,29 +969,29 @@ const char *Curl_sspi_strerror(int err, char *buf, size_t buflen)
" More detail may be available in the Windows System event log.",
err);
}
- else {
+ else {
char txtbuf[80];
char msgbuf[256];
msnprintf(txtbuf, sizeof(txtbuf), "%s (0x%08X)", txt, err);
-
+
if(get_winapi_error(err, msgbuf, sizeof(msgbuf)))
msnprintf(buf, buflen, "%s - %s", txtbuf, msgbuf);
else {
strncpy(buf, txtbuf, buflen);
buf[buflen - 1] = '\0';
- }
- }
-
-#else
- if(err == SEC_E_OK)
- txt = "No error";
- else
- txt = "Error";
+ }
+ }
+
+#else
+ if(err == SEC_E_OK)
+ txt = "No error";
+ else
+ txt = "Error";
strncpy(buf, txt, buflen);
buf[buflen - 1] = '\0';
-#endif
-
+#endif
+
if(errno != old_errno)
errno = old_errno;
@@ -1001,5 +1001,5 @@ const char *Curl_sspi_strerror(int err, char *buf, size_t buflen)
#endif
return buf;
-}
-#endif /* USE_WINDOWS_SSPI */
+}
+#endif /* USE_WINDOWS_SSPI */
diff --git a/contrib/libs/curl/lib/strerror.h b/contrib/libs/curl/lib/strerror.h
index d1a8229daf..96a7e27c51 100644
--- a/contrib/libs/curl/lib/strerror.h
+++ b/contrib/libs/curl/lib/strerror.h
@@ -1,37 +1,37 @@
-#ifndef HEADER_CURL_STRERROR_H
-#define HEADER_CURL_STRERROR_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_STRERROR_H
+#define HEADER_CURL_STRERROR_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "urldata.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "urldata.h"
+
#define STRERROR_LEN 256 /* a suitable length */
-
+
const char *Curl_strerror(int err, char *buf, size_t buflen);
#if defined(WIN32) || defined(_WIN32_WCE)
const char *Curl_winapi_strerror(DWORD err, char *buf, size_t buflen);
#endif
-#ifdef USE_WINDOWS_SSPI
+#ifdef USE_WINDOWS_SSPI
const char *Curl_sspi_strerror(int err, char *buf, size_t buflen);
-#endif
-
-#endif /* HEADER_CURL_STRERROR_H */
+#endif
+
+#endif /* HEADER_CURL_STRERROR_H */
diff --git a/contrib/libs/curl/lib/strtok.c b/contrib/libs/curl/lib/strtok.c
index 3b7e78016b..d53e587ab3 100644
--- a/contrib/libs/curl/lib/strtok.c
+++ b/contrib/libs/curl/lib/strtok.c
@@ -1,66 +1,66 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef HAVE_STRTOK_R
-#include <stddef.h>
-
-#include "strtok.h"
-
-char *
-Curl_strtok_r(char *ptr, const char *sep, char **end)
-{
- if(!ptr)
- /* we got NULL input so then we get our last position instead */
- ptr = *end;
-
- /* pass all letters that are including in the separator string */
- while(*ptr && strchr(sep, *ptr))
- ++ptr;
-
- if(*ptr) {
- /* so this is where the next piece of string starts */
- char *start = ptr;
-
- /* set the end pointer to the first byte after the start */
- *end = start + 1;
-
- /* scan through the string to find where it ends, it ends on a
- null byte or a character that exists in the separator string */
- while(**end && !strchr(sep, **end))
- ++*end;
-
- if(**end) {
- /* the end is not a null byte */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef HAVE_STRTOK_R
+#include <stddef.h>
+
+#include "strtok.h"
+
+char *
+Curl_strtok_r(char *ptr, const char *sep, char **end)
+{
+ if(!ptr)
+ /* we got NULL input so then we get our last position instead */
+ ptr = *end;
+
+ /* pass all letters that are including in the separator string */
+ while(*ptr && strchr(sep, *ptr))
+ ++ptr;
+
+ if(*ptr) {
+ /* so this is where the next piece of string starts */
+ char *start = ptr;
+
+ /* set the end pointer to the first byte after the start */
+ *end = start + 1;
+
+ /* scan through the string to find where it ends, it ends on a
+ null byte or a character that exists in the separator string */
+ while(**end && !strchr(sep, **end))
+ ++*end;
+
+ if(**end) {
+ /* the end is not a null byte */
**end = '\0'; /* null-terminate it! */
- ++*end; /* advance the last pointer to beyond the null byte */
- }
-
- return start; /* return the position where the string starts */
- }
-
- /* we ended up on a null byte, there are no more strings to find! */
- return NULL;
-}
-
-#endif /* this was only compiled if strtok_r wasn't present */
+ ++*end; /* advance the last pointer to beyond the null byte */
+ }
+
+ return start; /* return the position where the string starts */
+ }
+
+ /* we ended up on a null byte, there are no more strings to find! */
+ return NULL;
+}
+
+#endif /* this was only compiled if strtok_r wasn't present */
diff --git a/contrib/libs/curl/lib/strtok.h b/contrib/libs/curl/lib/strtok.h
index 0946ae5deb..831ef0c009 100644
--- a/contrib/libs/curl/lib/strtok.h
+++ b/contrib/libs/curl/lib/strtok.h
@@ -1,34 +1,34 @@
-#ifndef HEADER_CURL_STRTOK_H
-#define HEADER_CURL_STRTOK_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_STRTOK_H
+#define HEADER_CURL_STRTOK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-#include <stddef.h>
-
-#ifndef HAVE_STRTOK_R
-char *Curl_strtok_r(char *s, const char *delim, char **last);
-#define strtok_r Curl_strtok_r
-#else
-#include <string.h>
-#endif
-
-#endif /* HEADER_CURL_STRTOK_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+#include <stddef.h>
+
+#ifndef HAVE_STRTOK_R
+char *Curl_strtok_r(char *s, const char *delim, char **last);
+#define strtok_r Curl_strtok_r
+#else
+#include <string.h>
+#endif
+
+#endif /* HEADER_CURL_STRTOK_H */
diff --git a/contrib/libs/curl/lib/strtoofft.c b/contrib/libs/curl/lib/strtoofft.c
index 7154836bba..ac87cfc5bd 100644
--- a/contrib/libs/curl/lib/strtoofft.c
+++ b/contrib/libs/curl/lib/strtoofft.c
@@ -1,38 +1,38 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include <errno.h>
-#include "curl_setup.h"
-
-#include "strtoofft.h"
-
-/*
- * NOTE:
- *
- * In the ISO C standard (IEEE Std 1003.1), there is a strtoimax() function we
- * could use in case strtoll() doesn't exist... See
+#include "curl_setup.h"
+
+#include "strtoofft.h"
+
+/*
+ * NOTE:
+ *
+ * In the ISO C standard (IEEE Std 1003.1), there is a strtoimax() function we
+ * could use in case strtoll() doesn't exist... See
* https://www.opengroup.org/onlinepubs/009695399/functions/strtoimax.html
- */
-
+ */
+
#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
# ifdef HAVE_STRTOLL
# define strtooff strtoll
@@ -54,160 +54,160 @@
#else
# define strtooff strtol
#endif
-
+
#ifdef PRIVATE_STRTOOFF
-/* Range tests can be used for alphanum decoding if characters are consecutive,
- like in ASCII. Else an array is scanned. Determine this condition now. */
-
-#if('9' - '0') != 9 || ('Z' - 'A') != 25 || ('z' - 'a') != 25
-
-#define NO_RANGE_TEST
-
-static const char valchars[] =
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
-#endif
-
-static int get_char(char c, int base);
-
-/**
+/* Range tests can be used for alphanum decoding if characters are consecutive,
+ like in ASCII. Else an array is scanned. Determine this condition now. */
+
+#if('9' - '0') != 9 || ('Z' - 'A') != 25 || ('z' - 'a') != 25
+
+#define NO_RANGE_TEST
+
+static const char valchars[] =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+#endif
+
+static int get_char(char c, int base);
+
+/**
* Custom version of the strtooff function. This extracts a curl_off_t
- * value from the given input string and returns it.
- */
+ * value from the given input string and returns it.
+ */
static curl_off_t strtooff(const char *nptr, char **endptr, int base)
-{
- char *end;
- int is_negative = 0;
- int overflow;
- int i;
- curl_off_t value = 0;
- curl_off_t newval;
-
- /* Skip leading whitespace. */
- end = (char *)nptr;
- while(ISSPACE(end[0])) {
- end++;
- }
-
- /* Handle the sign, if any. */
- if(end[0] == '-') {
- is_negative = 1;
- end++;
- }
- else if(end[0] == '+') {
- end++;
- }
- else if(end[0] == '\0') {
- /* We had nothing but perhaps some whitespace -- there was no number. */
- if(endptr) {
- *endptr = end;
- }
- return 0;
- }
-
- /* Handle special beginnings, if present and allowed. */
- if(end[0] == '0' && end[1] == 'x') {
- if(base == 16 || base == 0) {
- end += 2;
- base = 16;
- }
- }
- else if(end[0] == '0') {
- if(base == 8 || base == 0) {
- end++;
- base = 8;
- }
- }
-
- /* Matching strtol, if the base is 0 and it doesn't look like
- * the number is octal or hex, we assume it's base 10.
- */
- if(base == 0) {
- base = 10;
- }
-
- /* Loop handling digits. */
- value = 0;
- overflow = 0;
- for(i = get_char(end[0], base);
- i != -1;
- end++, i = get_char(end[0], base)) {
- newval = base * value + i;
- if(newval < value) {
- /* We've overflowed. */
- overflow = 1;
- break;
- }
- else
- value = newval;
- }
-
- if(!overflow) {
- if(is_negative) {
- /* Fix the sign. */
- value *= -1;
- }
- }
- else {
- if(is_negative)
- value = CURL_OFF_T_MIN;
- else
- value = CURL_OFF_T_MAX;
-
+{
+ char *end;
+ int is_negative = 0;
+ int overflow;
+ int i;
+ curl_off_t value = 0;
+ curl_off_t newval;
+
+ /* Skip leading whitespace. */
+ end = (char *)nptr;
+ while(ISSPACE(end[0])) {
+ end++;
+ }
+
+ /* Handle the sign, if any. */
+ if(end[0] == '-') {
+ is_negative = 1;
+ end++;
+ }
+ else if(end[0] == '+') {
+ end++;
+ }
+ else if(end[0] == '\0') {
+ /* We had nothing but perhaps some whitespace -- there was no number. */
+ if(endptr) {
+ *endptr = end;
+ }
+ return 0;
+ }
+
+ /* Handle special beginnings, if present and allowed. */
+ if(end[0] == '0' && end[1] == 'x') {
+ if(base == 16 || base == 0) {
+ end += 2;
+ base = 16;
+ }
+ }
+ else if(end[0] == '0') {
+ if(base == 8 || base == 0) {
+ end++;
+ base = 8;
+ }
+ }
+
+ /* Matching strtol, if the base is 0 and it doesn't look like
+ * the number is octal or hex, we assume it's base 10.
+ */
+ if(base == 0) {
+ base = 10;
+ }
+
+ /* Loop handling digits. */
+ value = 0;
+ overflow = 0;
+ for(i = get_char(end[0], base);
+ i != -1;
+ end++, i = get_char(end[0], base)) {
+ newval = base * value + i;
+ if(newval < value) {
+ /* We've overflowed. */
+ overflow = 1;
+ break;
+ }
+ else
+ value = newval;
+ }
+
+ if(!overflow) {
+ if(is_negative) {
+ /* Fix the sign. */
+ value *= -1;
+ }
+ }
+ else {
+ if(is_negative)
+ value = CURL_OFF_T_MIN;
+ else
+ value = CURL_OFF_T_MAX;
+
errno = ERANGE;
- }
-
- if(endptr)
- *endptr = end;
-
- return value;
-}
-
-/**
- * Returns the value of c in the given base, or -1 if c cannot
- * be interpreted properly in that base (i.e., is out of range,
- * is a null, etc.).
- *
- * @param c the character to interpret according to base
- * @param base the base in which to interpret c
- *
- * @return the value of c in base, or -1 if c isn't in range
- */
-static int get_char(char c, int base)
-{
-#ifndef NO_RANGE_TEST
- int value = -1;
- if(c <= '9' && c >= '0') {
- value = c - '0';
- }
- else if(c <= 'Z' && c >= 'A') {
- value = c - 'A' + 10;
- }
- else if(c <= 'z' && c >= 'a') {
- value = c - 'a' + 10;
- }
-#else
+ }
+
+ if(endptr)
+ *endptr = end;
+
+ return value;
+}
+
+/**
+ * Returns the value of c in the given base, or -1 if c cannot
+ * be interpreted properly in that base (i.e., is out of range,
+ * is a null, etc.).
+ *
+ * @param c the character to interpret according to base
+ * @param base the base in which to interpret c
+ *
+ * @return the value of c in base, or -1 if c isn't in range
+ */
+static int get_char(char c, int base)
+{
+#ifndef NO_RANGE_TEST
+ int value = -1;
+ if(c <= '9' && c >= '0') {
+ value = c - '0';
+ }
+ else if(c <= 'Z' && c >= 'A') {
+ value = c - 'A' + 10;
+ }
+ else if(c <= 'z' && c >= 'a') {
+ value = c - 'a' + 10;
+ }
+#else
const char *cp;
- int value;
-
- cp = memchr(valchars, c, 10 + 26 + 26);
-
- if(!cp)
- return -1;
-
- value = cp - valchars;
-
- if(value >= 10 + 26)
- value -= 26; /* Lowercase. */
-#endif
-
- if(value >= base) {
- value = -1;
- }
-
- return value;
-}
-#endif /* Only present if we need strtoll, but don't have it. */
+ int value;
+
+ cp = memchr(valchars, c, 10 + 26 + 26);
+
+ if(!cp)
+ return -1;
+
+ value = cp - valchars;
+
+ if(value >= 10 + 26)
+ value -= 26; /* Lowercase. */
+#endif
+
+ if(value >= base) {
+ value = -1;
+ }
+
+ return value;
+}
+#endif /* Only present if we need strtoll, but don't have it. */
/*
* Parse a *positive* up to 64 bit number written in ascii.
diff --git a/contrib/libs/curl/lib/strtoofft.h b/contrib/libs/curl/lib/strtoofft.h
index eec1467a15..4d22ba36c9 100644
--- a/contrib/libs/curl/lib/strtoofft.h
+++ b/contrib/libs/curl/lib/strtoofft.h
@@ -1,52 +1,52 @@
-#ifndef HEADER_CURL_STRTOOFFT_H
-#define HEADER_CURL_STRTOOFFT_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_STRTOOFFT_H
+#define HEADER_CURL_STRTOOFFT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-/*
- * Determine which string to integral data type conversion function we use
- * to implement string conversion to our curl_off_t integral data type.
- *
- * Notice that curl_off_t might be 64 or 32 bit wide, and that it might use
- * an underlying data type which might be 'long', 'int64_t', 'long long' or
- * '__int64' and more remotely other data types.
- *
- * On systems where the size of curl_off_t is greater than the size of 'long'
- * the conversion function to use is strtoll() if it is available, otherwise,
- * we emulate its functionality with our own clone.
- *
- * On systems where the size of curl_off_t is smaller or equal than the size
- * of 'long' the conversion function to use is strtol().
- */
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+/*
+ * Determine which string to integral data type conversion function we use
+ * to implement string conversion to our curl_off_t integral data type.
+ *
+ * Notice that curl_off_t might be 64 or 32 bit wide, and that it might use
+ * an underlying data type which might be 'long', 'int64_t', 'long long' or
+ * '__int64' and more remotely other data types.
+ *
+ * On systems where the size of curl_off_t is greater than the size of 'long'
+ * the conversion function to use is strtoll() if it is available, otherwise,
+ * we emulate its functionality with our own clone.
+ *
+ * On systems where the size of curl_off_t is smaller or equal than the size
+ * of 'long' the conversion function to use is strtol().
+ */
+
typedef enum {
CURL_OFFT_OK, /* parsed fine */
CURL_OFFT_FLOW, /* over or underflow */
CURL_OFFT_INVAL /* nothing was parsed */
} CURLofft;
-
+
CURLofft curlx_strtoofft(const char *str, char **endp, int base,
curl_off_t *num);
-
-#endif /* HEADER_CURL_STRTOOFFT_H */
+
+#endif /* HEADER_CURL_STRTOOFFT_H */
diff --git a/contrib/libs/curl/lib/telnet.c b/contrib/libs/curl/lib/telnet.c
index 67792c57be..8bf64a9f2b 100644
--- a/contrib/libs/curl/lib/telnet.c
+++ b/contrib/libs/curl/lib/telnet.c
@@ -1,1191 +1,1191 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_TELNET
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
-#include "sendf.h"
-#include "telnet.h"
-#include "connect.h"
-#include "progress.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_TELNET
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
+#include "sendf.h"
+#include "telnet.h"
+#include "connect.h"
+#include "progress.h"
#include "system_win32.h"
-#include "arpa_telnet.h"
-#include "select.h"
+#include "arpa_telnet.h"
+#include "select.h"
#include "strcase.h"
-#include "warnless.h"
-
+#include "warnless.h"
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
-#define SUBBUFSIZE 512
-
-#define CURL_SB_CLEAR(x) x->subpointer = x->subbuffer
-#define CURL_SB_TERM(x) \
- do { \
- x->subend = x->subpointer; \
- CURL_SB_CLEAR(x); \
+#include "memdebug.h"
+
+#define SUBBUFSIZE 512
+
+#define CURL_SB_CLEAR(x) x->subpointer = x->subbuffer
+#define CURL_SB_TERM(x) \
+ do { \
+ x->subend = x->subpointer; \
+ CURL_SB_CLEAR(x); \
} while(0)
#define CURL_SB_ACCUM(x,c) \
do { \
if(x->subpointer < (x->subbuffer + sizeof(x->subbuffer))) \
*x->subpointer++ = (c); \
} while(0)
-
-#define CURL_SB_GET(x) ((*x->subpointer++)&0xff)
-#define CURL_SB_LEN(x) (x->subend - x->subpointer)
-
+
+#define CURL_SB_GET(x) ((*x->subpointer++)&0xff)
+#define CURL_SB_LEN(x) (x->subend - x->subpointer)
+
/* For posterity:
#define CURL_SB_PEEK(x) ((*x->subpointer)&0xff)
#define CURL_SB_EOF(x) (x->subpointer >= x->subend) */
-#ifdef CURL_DISABLE_VERBOSE_STRINGS
-#define printoption(a,b,c,d) Curl_nop_stmt
-#endif
-
-static
-CURLcode telrcv(struct connectdata *,
- const unsigned char *inbuf, /* Data received from socket */
- ssize_t count); /* Number of bytes received */
-
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+#ifdef CURL_DISABLE_VERBOSE_STRINGS
+#define printoption(a,b,c,d) Curl_nop_stmt
+#endif
+
+static
+CURLcode telrcv(struct connectdata *,
+ const unsigned char *inbuf, /* Data received from socket */
+ ssize_t count); /* Number of bytes received */
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
static void printoption(struct Curl_easy *data,
- const char *direction,
- int cmd, int option);
-#endif
-
-static void negotiate(struct connectdata *);
-static void send_negotiation(struct connectdata *, int cmd, int option);
+ const char *direction,
+ int cmd, int option);
+#endif
+
+static void negotiate(struct connectdata *);
+static void send_negotiation(struct connectdata *, int cmd, int option);
static void set_local_option(struct connectdata *conn,
int option, int newstate);
static void set_remote_option(struct connectdata *conn,
int option, int newstate);
-
+
static void printsub(struct Curl_easy *data,
- int direction, unsigned char *pointer,
- size_t length);
-static void suboption(struct connectdata *);
-static void sendsuboption(struct connectdata *conn, int option);
-
-static CURLcode telnet_do(struct connectdata *conn, bool *done);
-static CURLcode telnet_done(struct connectdata *conn,
- CURLcode, bool premature);
-static CURLcode send_telnet_data(struct connectdata *conn,
- char *buffer, ssize_t nread);
-
-/* For negotiation compliant to RFC 1143 */
-#define CURL_NO 0
-#define CURL_YES 1
-#define CURL_WANTYES 2
-#define CURL_WANTNO 3
-
-#define CURL_EMPTY 0
-#define CURL_OPPOSITE 1
-
-/*
- * Telnet receiver states for fsm
- */
-typedef enum
-{
- CURL_TS_DATA = 0,
- CURL_TS_IAC,
- CURL_TS_WILL,
- CURL_TS_WONT,
- CURL_TS_DO,
- CURL_TS_DONT,
- CURL_TS_CR,
- CURL_TS_SB, /* sub-option collection */
- CURL_TS_SE /* looking for sub-option end */
-} TelnetReceive;
-
-struct TELNET {
- int please_negotiate;
- int already_negotiated;
- int us[256];
- int usq[256];
- int us_preferred[256];
- int him[256];
- int himq[256];
- int him_preferred[256];
- int subnegotiation[256];
- char subopt_ttype[32]; /* Set with suboption TTYPE */
- char subopt_xdisploc[128]; /* Set with suboption XDISPLOC */
- unsigned short subopt_wsx; /* Set with suboption NAWS */
- unsigned short subopt_wsy; /* Set with suboption NAWS */
- struct curl_slist *telnet_vars; /* Environment variables */
-
- /* suboptions */
- unsigned char subbuffer[SUBBUFSIZE];
- unsigned char *subpointer, *subend; /* buffer for sub-options */
-
- TelnetReceive telrcv_state;
-};
-
-
-/*
- * TELNET protocol handler.
- */
-
-const struct Curl_handler Curl_handler_telnet = {
- "TELNET", /* scheme */
- ZERO_NULL, /* setup_connection */
- telnet_do, /* do_it */
- telnet_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+ int direction, unsigned char *pointer,
+ size_t length);
+static void suboption(struct connectdata *);
+static void sendsuboption(struct connectdata *conn, int option);
+
+static CURLcode telnet_do(struct connectdata *conn, bool *done);
+static CURLcode telnet_done(struct connectdata *conn,
+ CURLcode, bool premature);
+static CURLcode send_telnet_data(struct connectdata *conn,
+ char *buffer, ssize_t nread);
+
+/* For negotiation compliant to RFC 1143 */
+#define CURL_NO 0
+#define CURL_YES 1
+#define CURL_WANTYES 2
+#define CURL_WANTNO 3
+
+#define CURL_EMPTY 0
+#define CURL_OPPOSITE 1
+
+/*
+ * Telnet receiver states for fsm
+ */
+typedef enum
+{
+ CURL_TS_DATA = 0,
+ CURL_TS_IAC,
+ CURL_TS_WILL,
+ CURL_TS_WONT,
+ CURL_TS_DO,
+ CURL_TS_DONT,
+ CURL_TS_CR,
+ CURL_TS_SB, /* sub-option collection */
+ CURL_TS_SE /* looking for sub-option end */
+} TelnetReceive;
+
+struct TELNET {
+ int please_negotiate;
+ int already_negotiated;
+ int us[256];
+ int usq[256];
+ int us_preferred[256];
+ int him[256];
+ int himq[256];
+ int him_preferred[256];
+ int subnegotiation[256];
+ char subopt_ttype[32]; /* Set with suboption TTYPE */
+ char subopt_xdisploc[128]; /* Set with suboption XDISPLOC */
+ unsigned short subopt_wsx; /* Set with suboption NAWS */
+ unsigned short subopt_wsy; /* Set with suboption NAWS */
+ struct curl_slist *telnet_vars; /* Environment variables */
+
+ /* suboptions */
+ unsigned char subbuffer[SUBBUFSIZE];
+ unsigned char *subpointer, *subend; /* buffer for sub-options */
+
+ TelnetReceive telrcv_state;
+};
+
+
+/*
+ * TELNET protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_telnet = {
+ "TELNET", /* scheme */
+ ZERO_NULL, /* setup_connection */
+ telnet_do, /* do_it */
+ telnet_done, /* done */
+ ZERO_NULL, /* do_more */
+ ZERO_NULL, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_TELNET, /* defport */
- CURLPROTO_TELNET, /* protocol */
+ PORT_TELNET, /* defport */
+ CURLPROTO_TELNET, /* protocol */
CURLPROTO_TELNET, /* family */
- PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
-};
-
-
-static
-CURLcode init_telnet(struct connectdata *conn)
-{
- struct TELNET *tn;
-
- tn = calloc(1, sizeof(struct TELNET));
- if(!tn)
- return CURLE_OUT_OF_MEMORY;
-
+ PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
+};
+
+
+static
+CURLcode init_telnet(struct connectdata *conn)
+{
+ struct TELNET *tn;
+
+ tn = calloc(1, sizeof(struct TELNET));
+ if(!tn)
+ return CURLE_OUT_OF_MEMORY;
+
conn->data->req.p.telnet = tn; /* make us known */
-
- tn->telrcv_state = CURL_TS_DATA;
-
- /* Init suboptions */
- CURL_SB_CLEAR(tn);
-
- /* Set the options we want by default */
- tn->us_preferred[CURL_TELOPT_SGA] = CURL_YES;
- tn->him_preferred[CURL_TELOPT_SGA] = CURL_YES;
-
- /* To be compliant with previous releases of libcurl
- we enable this option by default. This behaviour
- can be changed thanks to the "BINARY" option in
- CURLOPT_TELNETOPTIONS
- */
- tn->us_preferred[CURL_TELOPT_BINARY] = CURL_YES;
- tn->him_preferred[CURL_TELOPT_BINARY] = CURL_YES;
-
- /* We must allow the server to echo what we sent
- but it is not necessary to request the server
- to do so (it might forces the server to close
- the connection). Hence, we ignore ECHO in the
- negotiate function
- */
- tn->him_preferred[CURL_TELOPT_ECHO] = CURL_YES;
-
- /* Set the subnegotiation fields to send information
- just after negotiation passed (do/will)
-
- Default values are (0,0) initialized by calloc.
- According to the RFC1013 it is valid:
- A value equal to zero is acceptable for the width (or height),
- and means that no character width (or height) is being sent.
- In this case, the width (or height) that will be assumed by the
- Telnet server is operating system specific (it will probably be
- based upon the terminal type information that may have been sent
- using the TERMINAL TYPE Telnet option). */
- tn->subnegotiation[CURL_TELOPT_NAWS] = CURL_YES;
- return CURLE_OK;
-}
-
-static void negotiate(struct connectdata *conn)
-{
- int i;
+
+ tn->telrcv_state = CURL_TS_DATA;
+
+ /* Init suboptions */
+ CURL_SB_CLEAR(tn);
+
+ /* Set the options we want by default */
+ tn->us_preferred[CURL_TELOPT_SGA] = CURL_YES;
+ tn->him_preferred[CURL_TELOPT_SGA] = CURL_YES;
+
+ /* To be compliant with previous releases of libcurl
+ we enable this option by default. This behaviour
+ can be changed thanks to the "BINARY" option in
+ CURLOPT_TELNETOPTIONS
+ */
+ tn->us_preferred[CURL_TELOPT_BINARY] = CURL_YES;
+ tn->him_preferred[CURL_TELOPT_BINARY] = CURL_YES;
+
+ /* We must allow the server to echo what we sent
+ but it is not necessary to request the server
+ to do so (it might forces the server to close
+ the connection). Hence, we ignore ECHO in the
+ negotiate function
+ */
+ tn->him_preferred[CURL_TELOPT_ECHO] = CURL_YES;
+
+ /* Set the subnegotiation fields to send information
+ just after negotiation passed (do/will)
+
+ Default values are (0,0) initialized by calloc.
+ According to the RFC1013 it is valid:
+ A value equal to zero is acceptable for the width (or height),
+ and means that no character width (or height) is being sent.
+ In this case, the width (or height) that will be assumed by the
+ Telnet server is operating system specific (it will probably be
+ based upon the terminal type information that may have been sent
+ using the TERMINAL TYPE Telnet option). */
+ tn->subnegotiation[CURL_TELOPT_NAWS] = CURL_YES;
+ return CURLE_OK;
+}
+
+static void negotiate(struct connectdata *conn)
+{
+ int i;
struct TELNET *tn = (struct TELNET *) conn->data->req.p.telnet;
-
+
for(i = 0; i < CURL_NTELOPTS; i++) {
if(i == CURL_TELOPT_ECHO)
- continue;
-
- if(tn->us_preferred[i] == CURL_YES)
- set_local_option(conn, i, CURL_YES);
-
- if(tn->him_preferred[i] == CURL_YES)
- set_remote_option(conn, i, CURL_YES);
- }
-}
-
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+ continue;
+
+ if(tn->us_preferred[i] == CURL_YES)
+ set_local_option(conn, i, CURL_YES);
+
+ if(tn->him_preferred[i] == CURL_YES)
+ set_remote_option(conn, i, CURL_YES);
+ }
+}
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
static void printoption(struct Curl_easy *data,
- const char *direction, int cmd, int option)
-{
- if(data->set.verbose) {
- if(cmd == CURL_IAC) {
- if(CURL_TELCMD_OK(option))
- infof(data, "%s IAC %s\n", direction, CURL_TELCMD(option));
- else
- infof(data, "%s IAC %d\n", direction, option);
- }
- else {
+ const char *direction, int cmd, int option)
+{
+ if(data->set.verbose) {
+ if(cmd == CURL_IAC) {
+ if(CURL_TELCMD_OK(option))
+ infof(data, "%s IAC %s\n", direction, CURL_TELCMD(option));
+ else
+ infof(data, "%s IAC %d\n", direction, option);
+ }
+ else {
const char *fmt = (cmd == CURL_WILL) ? "WILL" :
(cmd == CURL_WONT) ? "WONT" :
(cmd == CURL_DO) ? "DO" :
(cmd == CURL_DONT) ? "DONT" : 0;
- if(fmt) {
+ if(fmt) {
const char *opt;
- if(CURL_TELOPT_OK(option))
- opt = CURL_TELOPT(option);
- else if(option == CURL_TELOPT_EXOPL)
- opt = "EXOPL";
- else
- opt = NULL;
-
- if(opt)
- infof(data, "%s %s %s\n", direction, fmt, opt);
- else
- infof(data, "%s %s %d\n", direction, fmt, option);
- }
- else
- infof(data, "%s %d %d\n", direction, cmd, option);
- }
- }
-}
-#endif
-
-static void send_negotiation(struct connectdata *conn, int cmd, int option)
-{
- unsigned char buf[3];
- ssize_t bytes_written;
+ if(CURL_TELOPT_OK(option))
+ opt = CURL_TELOPT(option);
+ else if(option == CURL_TELOPT_EXOPL)
+ opt = "EXOPL";
+ else
+ opt = NULL;
+
+ if(opt)
+ infof(data, "%s %s %s\n", direction, fmt, opt);
+ else
+ infof(data, "%s %s %d\n", direction, fmt, option);
+ }
+ else
+ infof(data, "%s %d %d\n", direction, cmd, option);
+ }
+ }
+}
+#endif
+
+static void send_negotiation(struct connectdata *conn, int cmd, int option)
+{
+ unsigned char buf[3];
+ ssize_t bytes_written;
struct Curl_easy *data = conn->data;
-
- buf[0] = CURL_IAC;
- buf[1] = (unsigned char)cmd;
- buf[2] = (unsigned char)option;
-
- bytes_written = swrite(conn->sock[FIRSTSOCKET], buf, 3);
- if(bytes_written < 0) {
+
+ buf[0] = CURL_IAC;
+ buf[1] = (unsigned char)cmd;
+ buf[2] = (unsigned char)option;
+
+ bytes_written = swrite(conn->sock[FIRSTSOCKET], buf, 3);
+ if(bytes_written < 0) {
int err = SOCKERRNO;
- failf(data,"Sending data failed (%d)",err);
- }
-
- printoption(conn->data, "SENT", cmd, option);
-}
-
-static
-void set_remote_option(struct connectdata *conn, int option, int newstate)
-{
+ failf(data,"Sending data failed (%d)",err);
+ }
+
+ printoption(conn->data, "SENT", cmd, option);
+}
+
+static
+void set_remote_option(struct connectdata *conn, int option, int newstate)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- if(newstate == CURL_YES) {
- switch(tn->him[option]) {
- case CURL_NO:
- tn->him[option] = CURL_WANTYES;
- send_negotiation(conn, CURL_DO, option);
- break;
-
- case CURL_YES:
- /* Already enabled */
- break;
-
- case CURL_WANTNO:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- /* Already negotiating for CURL_YES, queue the request */
- tn->himq[option] = CURL_OPPOSITE;
- break;
- case CURL_OPPOSITE:
- /* Error: already queued an enable request */
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- /* Error: already negotiating for enable */
- break;
- case CURL_OPPOSITE:
- tn->himq[option] = CURL_EMPTY;
- break;
- }
- break;
- }
- }
- else { /* NO */
- switch(tn->him[option]) {
- case CURL_NO:
- /* Already disabled */
- break;
-
- case CURL_YES:
- tn->him[option] = CURL_WANTNO;
- send_negotiation(conn, CURL_DONT, option);
- break;
-
- case CURL_WANTNO:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- /* Already negotiating for NO */
- break;
- case CURL_OPPOSITE:
- tn->himq[option] = CURL_EMPTY;
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- tn->himq[option] = CURL_OPPOSITE;
- break;
- case CURL_OPPOSITE:
- break;
- }
- break;
- }
- }
-}
-
-static
-void rec_will(struct connectdata *conn, int option)
-{
+ if(newstate == CURL_YES) {
+ switch(tn->him[option]) {
+ case CURL_NO:
+ tn->him[option] = CURL_WANTYES;
+ send_negotiation(conn, CURL_DO, option);
+ break;
+
+ case CURL_YES:
+ /* Already enabled */
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ /* Already negotiating for CURL_YES, queue the request */
+ tn->himq[option] = CURL_OPPOSITE;
+ break;
+ case CURL_OPPOSITE:
+ /* Error: already queued an enable request */
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ /* Error: already negotiating for enable */
+ break;
+ case CURL_OPPOSITE:
+ tn->himq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+ }
+ }
+ else { /* NO */
+ switch(tn->him[option]) {
+ case CURL_NO:
+ /* Already disabled */
+ break;
+
+ case CURL_YES:
+ tn->him[option] = CURL_WANTNO;
+ send_negotiation(conn, CURL_DONT, option);
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ /* Already negotiating for NO */
+ break;
+ case CURL_OPPOSITE:
+ tn->himq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ tn->himq[option] = CURL_OPPOSITE;
+ break;
+ case CURL_OPPOSITE:
+ break;
+ }
+ break;
+ }
+ }
+}
+
+static
+void rec_will(struct connectdata *conn, int option)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- switch(tn->him[option]) {
- case CURL_NO:
- if(tn->him_preferred[option] == CURL_YES) {
- tn->him[option] = CURL_YES;
- send_negotiation(conn, CURL_DO, option);
- }
- else
- send_negotiation(conn, CURL_DONT, option);
-
- break;
-
- case CURL_YES:
- /* Already enabled */
- break;
-
- case CURL_WANTNO:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- /* Error: DONT answered by WILL */
- tn->him[option] = CURL_NO;
- break;
- case CURL_OPPOSITE:
- /* Error: DONT answered by WILL */
- tn->him[option] = CURL_YES;
- tn->himq[option] = CURL_EMPTY;
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- tn->him[option] = CURL_YES;
- break;
- case CURL_OPPOSITE:
- tn->him[option] = CURL_WANTNO;
- tn->himq[option] = CURL_EMPTY;
- send_negotiation(conn, CURL_DONT, option);
- break;
- }
- break;
- }
-}
-
-static
-void rec_wont(struct connectdata *conn, int option)
-{
+ switch(tn->him[option]) {
+ case CURL_NO:
+ if(tn->him_preferred[option] == CURL_YES) {
+ tn->him[option] = CURL_YES;
+ send_negotiation(conn, CURL_DO, option);
+ }
+ else
+ send_negotiation(conn, CURL_DONT, option);
+
+ break;
+
+ case CURL_YES:
+ /* Already enabled */
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ /* Error: DONT answered by WILL */
+ tn->him[option] = CURL_NO;
+ break;
+ case CURL_OPPOSITE:
+ /* Error: DONT answered by WILL */
+ tn->him[option] = CURL_YES;
+ tn->himq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ tn->him[option] = CURL_YES;
+ break;
+ case CURL_OPPOSITE:
+ tn->him[option] = CURL_WANTNO;
+ tn->himq[option] = CURL_EMPTY;
+ send_negotiation(conn, CURL_DONT, option);
+ break;
+ }
+ break;
+ }
+}
+
+static
+void rec_wont(struct connectdata *conn, int option)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- switch(tn->him[option]) {
- case CURL_NO:
- /* Already disabled */
- break;
-
- case CURL_YES:
- tn->him[option] = CURL_NO;
- send_negotiation(conn, CURL_DONT, option);
- break;
-
- case CURL_WANTNO:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- tn->him[option] = CURL_NO;
- break;
-
- case CURL_OPPOSITE:
- tn->him[option] = CURL_WANTYES;
- tn->himq[option] = CURL_EMPTY;
- send_negotiation(conn, CURL_DO, option);
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->himq[option]) {
- case CURL_EMPTY:
- tn->him[option] = CURL_NO;
- break;
- case CURL_OPPOSITE:
- tn->him[option] = CURL_NO;
- tn->himq[option] = CURL_EMPTY;
- break;
- }
- break;
- }
-}
-
-static void
-set_local_option(struct connectdata *conn, int option, int newstate)
-{
+ switch(tn->him[option]) {
+ case CURL_NO:
+ /* Already disabled */
+ break;
+
+ case CURL_YES:
+ tn->him[option] = CURL_NO;
+ send_negotiation(conn, CURL_DONT, option);
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ tn->him[option] = CURL_NO;
+ break;
+
+ case CURL_OPPOSITE:
+ tn->him[option] = CURL_WANTYES;
+ tn->himq[option] = CURL_EMPTY;
+ send_negotiation(conn, CURL_DO, option);
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->himq[option]) {
+ case CURL_EMPTY:
+ tn->him[option] = CURL_NO;
+ break;
+ case CURL_OPPOSITE:
+ tn->him[option] = CURL_NO;
+ tn->himq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+ }
+}
+
+static void
+set_local_option(struct connectdata *conn, int option, int newstate)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- if(newstate == CURL_YES) {
- switch(tn->us[option]) {
- case CURL_NO:
- tn->us[option] = CURL_WANTYES;
- send_negotiation(conn, CURL_WILL, option);
- break;
-
- case CURL_YES:
- /* Already enabled */
- break;
-
- case CURL_WANTNO:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- /* Already negotiating for CURL_YES, queue the request */
- tn->usq[option] = CURL_OPPOSITE;
- break;
- case CURL_OPPOSITE:
- /* Error: already queued an enable request */
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- /* Error: already negotiating for enable */
- break;
- case CURL_OPPOSITE:
- tn->usq[option] = CURL_EMPTY;
- break;
- }
- break;
- }
- }
- else { /* NO */
- switch(tn->us[option]) {
- case CURL_NO:
- /* Already disabled */
- break;
-
- case CURL_YES:
- tn->us[option] = CURL_WANTNO;
- send_negotiation(conn, CURL_WONT, option);
- break;
-
- case CURL_WANTNO:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- /* Already negotiating for NO */
- break;
- case CURL_OPPOSITE:
- tn->usq[option] = CURL_EMPTY;
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- tn->usq[option] = CURL_OPPOSITE;
- break;
- case CURL_OPPOSITE:
- break;
- }
- break;
- }
- }
-}
-
-static
-void rec_do(struct connectdata *conn, int option)
-{
+ if(newstate == CURL_YES) {
+ switch(tn->us[option]) {
+ case CURL_NO:
+ tn->us[option] = CURL_WANTYES;
+ send_negotiation(conn, CURL_WILL, option);
+ break;
+
+ case CURL_YES:
+ /* Already enabled */
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ /* Already negotiating for CURL_YES, queue the request */
+ tn->usq[option] = CURL_OPPOSITE;
+ break;
+ case CURL_OPPOSITE:
+ /* Error: already queued an enable request */
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ /* Error: already negotiating for enable */
+ break;
+ case CURL_OPPOSITE:
+ tn->usq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+ }
+ }
+ else { /* NO */
+ switch(tn->us[option]) {
+ case CURL_NO:
+ /* Already disabled */
+ break;
+
+ case CURL_YES:
+ tn->us[option] = CURL_WANTNO;
+ send_negotiation(conn, CURL_WONT, option);
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ /* Already negotiating for NO */
+ break;
+ case CURL_OPPOSITE:
+ tn->usq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ tn->usq[option] = CURL_OPPOSITE;
+ break;
+ case CURL_OPPOSITE:
+ break;
+ }
+ break;
+ }
+ }
+}
+
+static
+void rec_do(struct connectdata *conn, int option)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- switch(tn->us[option]) {
- case CURL_NO:
- if(tn->us_preferred[option] == CURL_YES) {
- tn->us[option] = CURL_YES;
- send_negotiation(conn, CURL_WILL, option);
- if(tn->subnegotiation[option] == CURL_YES)
- /* transmission of data option */
- sendsuboption(conn, option);
- }
- else if(tn->subnegotiation[option] == CURL_YES) {
- /* send information to achieve this option*/
- tn->us[option] = CURL_YES;
- send_negotiation(conn, CURL_WILL, option);
- sendsuboption(conn, option);
- }
- else
- send_negotiation(conn, CURL_WONT, option);
- break;
-
- case CURL_YES:
- /* Already enabled */
- break;
-
- case CURL_WANTNO:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- /* Error: DONT answered by WILL */
- tn->us[option] = CURL_NO;
- break;
- case CURL_OPPOSITE:
- /* Error: DONT answered by WILL */
- tn->us[option] = CURL_YES;
- tn->usq[option] = CURL_EMPTY;
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- tn->us[option] = CURL_YES;
- if(tn->subnegotiation[option] == CURL_YES) {
- /* transmission of data option */
- sendsuboption(conn, option);
- }
- break;
- case CURL_OPPOSITE:
- tn->us[option] = CURL_WANTNO;
- tn->himq[option] = CURL_EMPTY;
- send_negotiation(conn, CURL_WONT, option);
- break;
- }
- break;
- }
-}
-
-static
-void rec_dont(struct connectdata *conn, int option)
-{
+ switch(tn->us[option]) {
+ case CURL_NO:
+ if(tn->us_preferred[option] == CURL_YES) {
+ tn->us[option] = CURL_YES;
+ send_negotiation(conn, CURL_WILL, option);
+ if(tn->subnegotiation[option] == CURL_YES)
+ /* transmission of data option */
+ sendsuboption(conn, option);
+ }
+ else if(tn->subnegotiation[option] == CURL_YES) {
+ /* send information to achieve this option*/
+ tn->us[option] = CURL_YES;
+ send_negotiation(conn, CURL_WILL, option);
+ sendsuboption(conn, option);
+ }
+ else
+ send_negotiation(conn, CURL_WONT, option);
+ break;
+
+ case CURL_YES:
+ /* Already enabled */
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ /* Error: DONT answered by WILL */
+ tn->us[option] = CURL_NO;
+ break;
+ case CURL_OPPOSITE:
+ /* Error: DONT answered by WILL */
+ tn->us[option] = CURL_YES;
+ tn->usq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ tn->us[option] = CURL_YES;
+ if(tn->subnegotiation[option] == CURL_YES) {
+ /* transmission of data option */
+ sendsuboption(conn, option);
+ }
+ break;
+ case CURL_OPPOSITE:
+ tn->us[option] = CURL_WANTNO;
+ tn->himq[option] = CURL_EMPTY;
+ send_negotiation(conn, CURL_WONT, option);
+ break;
+ }
+ break;
+ }
+}
+
+static
+void rec_dont(struct connectdata *conn, int option)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- switch(tn->us[option]) {
- case CURL_NO:
- /* Already disabled */
- break;
-
- case CURL_YES:
- tn->us[option] = CURL_NO;
- send_negotiation(conn, CURL_WONT, option);
- break;
-
- case CURL_WANTNO:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- tn->us[option] = CURL_NO;
- break;
-
- case CURL_OPPOSITE:
- tn->us[option] = CURL_WANTYES;
- tn->usq[option] = CURL_EMPTY;
- send_negotiation(conn, CURL_WILL, option);
- break;
- }
- break;
-
- case CURL_WANTYES:
- switch(tn->usq[option]) {
- case CURL_EMPTY:
- tn->us[option] = CURL_NO;
- break;
- case CURL_OPPOSITE:
- tn->us[option] = CURL_NO;
- tn->usq[option] = CURL_EMPTY;
- break;
- }
- break;
- }
-}
-
-
+ switch(tn->us[option]) {
+ case CURL_NO:
+ /* Already disabled */
+ break;
+
+ case CURL_YES:
+ tn->us[option] = CURL_NO;
+ send_negotiation(conn, CURL_WONT, option);
+ break;
+
+ case CURL_WANTNO:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ tn->us[option] = CURL_NO;
+ break;
+
+ case CURL_OPPOSITE:
+ tn->us[option] = CURL_WANTYES;
+ tn->usq[option] = CURL_EMPTY;
+ send_negotiation(conn, CURL_WILL, option);
+ break;
+ }
+ break;
+
+ case CURL_WANTYES:
+ switch(tn->usq[option]) {
+ case CURL_EMPTY:
+ tn->us[option] = CURL_NO;
+ break;
+ case CURL_OPPOSITE:
+ tn->us[option] = CURL_NO;
+ tn->usq[option] = CURL_EMPTY;
+ break;
+ }
+ break;
+ }
+}
+
+
static void printsub(struct Curl_easy *data,
- int direction, /* '<' or '>' */
- unsigned char *pointer, /* where suboption data is */
- size_t length) /* length of suboption data */
-{
- if(data->set.verbose) {
+ int direction, /* '<' or '>' */
+ unsigned char *pointer, /* where suboption data is */
+ size_t length) /* length of suboption data */
+{
+ if(data->set.verbose) {
unsigned int i = 0;
- if(direction) {
- infof(data, "%s IAC SB ", (direction == '<')? "RCVD":"SENT");
- if(length >= 3) {
- int j;
-
- i = pointer[length-2];
- j = pointer[length-1];
-
- if(i != CURL_IAC || j != CURL_SE) {
- infof(data, "(terminated by ");
- if(CURL_TELOPT_OK(i))
- infof(data, "%s ", CURL_TELOPT(i));
- else if(CURL_TELCMD_OK(i))
- infof(data, "%s ", CURL_TELCMD(i));
- else
- infof(data, "%u ", i);
- if(CURL_TELOPT_OK(j))
- infof(data, "%s", CURL_TELOPT(j));
- else if(CURL_TELCMD_OK(j))
- infof(data, "%s", CURL_TELCMD(j));
- else
- infof(data, "%d", j);
- infof(data, ", not IAC SE!) ");
- }
- }
- length -= 2;
- }
- if(length < 1) {
- infof(data, "(Empty suboption?)");
- return;
- }
-
- if(CURL_TELOPT_OK(pointer[0])) {
- switch(pointer[0]) {
- case CURL_TELOPT_TTYPE:
- case CURL_TELOPT_XDISPLOC:
- case CURL_TELOPT_NEW_ENVIRON:
- case CURL_TELOPT_NAWS:
- infof(data, "%s", CURL_TELOPT(pointer[0]));
- break;
- default:
- infof(data, "%s (unsupported)", CURL_TELOPT(pointer[0]));
- break;
- }
- }
- else
- infof(data, "%d (unknown)", pointer[i]);
-
- switch(pointer[0]) {
- case CURL_TELOPT_NAWS:
+ if(direction) {
+ infof(data, "%s IAC SB ", (direction == '<')? "RCVD":"SENT");
+ if(length >= 3) {
+ int j;
+
+ i = pointer[length-2];
+ j = pointer[length-1];
+
+ if(i != CURL_IAC || j != CURL_SE) {
+ infof(data, "(terminated by ");
+ if(CURL_TELOPT_OK(i))
+ infof(data, "%s ", CURL_TELOPT(i));
+ else if(CURL_TELCMD_OK(i))
+ infof(data, "%s ", CURL_TELCMD(i));
+ else
+ infof(data, "%u ", i);
+ if(CURL_TELOPT_OK(j))
+ infof(data, "%s", CURL_TELOPT(j));
+ else if(CURL_TELCMD_OK(j))
+ infof(data, "%s", CURL_TELCMD(j));
+ else
+ infof(data, "%d", j);
+ infof(data, ", not IAC SE!) ");
+ }
+ }
+ length -= 2;
+ }
+ if(length < 1) {
+ infof(data, "(Empty suboption?)");
+ return;
+ }
+
+ if(CURL_TELOPT_OK(pointer[0])) {
+ switch(pointer[0]) {
+ case CURL_TELOPT_TTYPE:
+ case CURL_TELOPT_XDISPLOC:
+ case CURL_TELOPT_NEW_ENVIRON:
+ case CURL_TELOPT_NAWS:
+ infof(data, "%s", CURL_TELOPT(pointer[0]));
+ break;
+ default:
+ infof(data, "%s (unsupported)", CURL_TELOPT(pointer[0]));
+ break;
+ }
+ }
+ else
+ infof(data, "%d (unknown)", pointer[i]);
+
+ switch(pointer[0]) {
+ case CURL_TELOPT_NAWS:
if(length > 4)
infof(data, "Width: %d ; Height: %d", (pointer[1]<<8) | pointer[2],
(pointer[3]<<8) | pointer[4]);
- break;
- default:
- switch(pointer[1]) {
- case CURL_TELQUAL_IS:
- infof(data, " IS");
- break;
- case CURL_TELQUAL_SEND:
- infof(data, " SEND");
- break;
- case CURL_TELQUAL_INFO:
- infof(data, " INFO/REPLY");
- break;
- case CURL_TELQUAL_NAME:
- infof(data, " NAME");
- break;
- }
-
- switch(pointer[0]) {
- case CURL_TELOPT_TTYPE:
- case CURL_TELOPT_XDISPLOC:
- pointer[length] = 0;
- infof(data, " \"%s\"", &pointer[2]);
- break;
- case CURL_TELOPT_NEW_ENVIRON:
- if(pointer[1] == CURL_TELQUAL_IS) {
- infof(data, " ");
+ break;
+ default:
+ switch(pointer[1]) {
+ case CURL_TELQUAL_IS:
+ infof(data, " IS");
+ break;
+ case CURL_TELQUAL_SEND:
+ infof(data, " SEND");
+ break;
+ case CURL_TELQUAL_INFO:
+ infof(data, " INFO/REPLY");
+ break;
+ case CURL_TELQUAL_NAME:
+ infof(data, " NAME");
+ break;
+ }
+
+ switch(pointer[0]) {
+ case CURL_TELOPT_TTYPE:
+ case CURL_TELOPT_XDISPLOC:
+ pointer[length] = 0;
+ infof(data, " \"%s\"", &pointer[2]);
+ break;
+ case CURL_TELOPT_NEW_ENVIRON:
+ if(pointer[1] == CURL_TELQUAL_IS) {
+ infof(data, " ");
for(i = 3; i < length; i++) {
- switch(pointer[i]) {
- case CURL_NEW_ENV_VAR:
- infof(data, ", ");
- break;
- case CURL_NEW_ENV_VALUE:
- infof(data, " = ");
- break;
- default:
- infof(data, "%c", pointer[i]);
- break;
- }
- }
- }
- break;
- default:
- for(i = 2; i < length; i++)
- infof(data, " %.2x", pointer[i]);
- break;
- }
- }
- if(direction)
- infof(data, "\n");
- }
-}
-
-static CURLcode check_telnet_options(struct connectdata *conn)
-{
- struct curl_slist *head;
- struct curl_slist *beg;
+ switch(pointer[i]) {
+ case CURL_NEW_ENV_VAR:
+ infof(data, ", ");
+ break;
+ case CURL_NEW_ENV_VALUE:
+ infof(data, " = ");
+ break;
+ default:
+ infof(data, "%c", pointer[i]);
+ break;
+ }
+ }
+ }
+ break;
+ default:
+ for(i = 2; i < length; i++)
+ infof(data, " %.2x", pointer[i]);
+ break;
+ }
+ }
+ if(direction)
+ infof(data, "\n");
+ }
+}
+
+static CURLcode check_telnet_options(struct connectdata *conn)
+{
+ struct curl_slist *head;
+ struct curl_slist *beg;
char option_keyword[128] = "";
char option_arg[256] = "";
struct Curl_easy *data = conn->data;
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- CURLcode result = CURLE_OK;
- int binary_option;
-
- /* Add the user name as an environment variable if it
- was given on the command line */
- if(conn->bits.user_passwd) {
+ CURLcode result = CURLE_OK;
+ int binary_option;
+
+ /* Add the user name as an environment variable if it
+ was given on the command line */
+ if(conn->bits.user_passwd) {
msnprintf(option_arg, sizeof(option_arg), "USER,%s", conn->user);
- beg = curl_slist_append(tn->telnet_vars, option_arg);
- if(!beg) {
- curl_slist_free_all(tn->telnet_vars);
- tn->telnet_vars = NULL;
- return CURLE_OUT_OF_MEMORY;
- }
- tn->telnet_vars = beg;
- tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
- }
-
+ beg = curl_slist_append(tn->telnet_vars, option_arg);
+ if(!beg) {
+ curl_slist_free_all(tn->telnet_vars);
+ tn->telnet_vars = NULL;
+ return CURLE_OUT_OF_MEMORY;
+ }
+ tn->telnet_vars = beg;
+ tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
+ }
+
for(head = data->set.telnet_options; head; head = head->next) {
- if(sscanf(head->data, "%127[^= ]%*[ =]%255s",
- option_keyword, option_arg) == 2) {
-
- /* Terminal type */
+ if(sscanf(head->data, "%127[^= ]%*[ =]%255s",
+ option_keyword, option_arg) == 2) {
+
+ /* Terminal type */
if(strcasecompare(option_keyword, "TTYPE")) {
- strncpy(tn->subopt_ttype, option_arg, 31);
- tn->subopt_ttype[31] = 0; /* String termination */
- tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES;
- continue;
- }
-
- /* Display variable */
+ strncpy(tn->subopt_ttype, option_arg, 31);
+ tn->subopt_ttype[31] = 0; /* String termination */
+ tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES;
+ continue;
+ }
+
+ /* Display variable */
if(strcasecompare(option_keyword, "XDISPLOC")) {
- strncpy(tn->subopt_xdisploc, option_arg, 127);
- tn->subopt_xdisploc[127] = 0; /* String termination */
- tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES;
- continue;
- }
-
- /* Environment variable */
+ strncpy(tn->subopt_xdisploc, option_arg, 127);
+ tn->subopt_xdisploc[127] = 0; /* String termination */
+ tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES;
+ continue;
+ }
+
+ /* Environment variable */
if(strcasecompare(option_keyword, "NEW_ENV")) {
- beg = curl_slist_append(tn->telnet_vars, option_arg);
- if(!beg) {
- result = CURLE_OUT_OF_MEMORY;
- break;
- }
- tn->telnet_vars = beg;
- tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
- continue;
- }
-
+ beg = curl_slist_append(tn->telnet_vars, option_arg);
+ if(!beg) {
+ result = CURLE_OUT_OF_MEMORY;
+ break;
+ }
+ tn->telnet_vars = beg;
+ tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
+ continue;
+ }
+
/* Window Size */
if(strcasecompare(option_keyword, "WS")) {
- if(sscanf(option_arg, "%hu%*[xX]%hu",
- &tn->subopt_wsx, &tn->subopt_wsy) == 2)
- tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES;
- else {
- failf(data, "Syntax error in telnet option: %s", head->data);
- result = CURLE_TELNET_OPTION_SYNTAX;
- break;
- }
- continue;
- }
-
- /* To take care or not of the 8th bit in data exchange */
+ if(sscanf(option_arg, "%hu%*[xX]%hu",
+ &tn->subopt_wsx, &tn->subopt_wsy) == 2)
+ tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES;
+ else {
+ failf(data, "Syntax error in telnet option: %s", head->data);
+ result = CURLE_TELNET_OPTION_SYNTAX;
+ break;
+ }
+ continue;
+ }
+
+ /* To take care or not of the 8th bit in data exchange */
if(strcasecompare(option_keyword, "BINARY")) {
binary_option = atoi(option_arg);
if(binary_option != 1) {
- tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO;
- tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO;
- }
- continue;
- }
-
- failf(data, "Unknown telnet option %s", head->data);
+ tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO;
+ tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO;
+ }
+ continue;
+ }
+
+ failf(data, "Unknown telnet option %s", head->data);
result = CURLE_UNKNOWN_OPTION;
- break;
- }
+ break;
+ }
failf(data, "Syntax error in telnet option: %s", head->data);
result = CURLE_TELNET_OPTION_SYNTAX;
break;
- }
-
- if(result) {
- curl_slist_free_all(tn->telnet_vars);
- tn->telnet_vars = NULL;
- }
-
- return result;
-}
-
-/*
- * suboption()
- *
- * Look at the sub-option buffer, and try to be helpful to the other
- * side.
- */
-
-static void suboption(struct connectdata *conn)
-{
- struct curl_slist *v;
- unsigned char temp[2048];
- ssize_t bytes_written;
- size_t len;
- int err;
+ }
+
+ if(result) {
+ curl_slist_free_all(tn->telnet_vars);
+ tn->telnet_vars = NULL;
+ }
+
+ return result;
+}
+
+/*
+ * suboption()
+ *
+ * Look at the sub-option buffer, and try to be helpful to the other
+ * side.
+ */
+
+static void suboption(struct connectdata *conn)
+{
+ struct curl_slist *v;
+ unsigned char temp[2048];
+ ssize_t bytes_written;
+ size_t len;
+ int err;
char varname[128] = "";
char varval[128] = "";
struct Curl_easy *data = conn->data;
struct TELNET *tn = (struct TELNET *)data->req.p.telnet;
-
+
printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2);
switch(CURL_SB_GET(tn)) {
- case CURL_TELOPT_TTYPE:
- len = strlen(tn->subopt_ttype) + 4 + 2;
+ case CURL_TELOPT_TTYPE:
+ len = strlen(tn->subopt_ttype) + 4 + 2;
msnprintf((char *)temp, sizeof(temp),
"%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE,
CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE);
- bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
- if(bytes_written < 0) {
- err = SOCKERRNO;
- failf(data,"Sending data failed (%d)",err);
- }
- printsub(data, '>', &temp[2], len-2);
- break;
- case CURL_TELOPT_XDISPLOC:
- len = strlen(tn->subopt_xdisploc) + 4 + 2;
+ bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
+ if(bytes_written < 0) {
+ err = SOCKERRNO;
+ failf(data,"Sending data failed (%d)",err);
+ }
+ printsub(data, '>', &temp[2], len-2);
+ break;
+ case CURL_TELOPT_XDISPLOC:
+ len = strlen(tn->subopt_xdisploc) + 4 + 2;
msnprintf((char *)temp, sizeof(temp),
"%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC,
CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE);
- bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
- if(bytes_written < 0) {
- err = SOCKERRNO;
- failf(data,"Sending data failed (%d)",err);
- }
- printsub(data, '>', &temp[2], len-2);
- break;
- case CURL_TELOPT_NEW_ENVIRON:
+ bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
+ if(bytes_written < 0) {
+ err = SOCKERRNO;
+ failf(data,"Sending data failed (%d)",err);
+ }
+ printsub(data, '>', &temp[2], len-2);
+ break;
+ case CURL_TELOPT_NEW_ENVIRON:
msnprintf((char *)temp, sizeof(temp),
"%c%c%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON,
CURL_TELQUAL_IS);
- len = 4;
-
+ len = 4;
+
for(v = tn->telnet_vars; v; v = v->next) {
size_t tmplen = (strlen(v->data) + 1);
- /* Add the variable only if it fits */
- if(len + tmplen < (int)sizeof(temp)-6) {
+ /* Add the variable only if it fits */
+ if(len + tmplen < (int)sizeof(temp)-6) {
if(sscanf(v->data, "%127[^,],%127s", varname, varval)) {
msnprintf((char *)&temp[len], sizeof(temp) - len,
"%c%s%c%s", CURL_NEW_ENV_VAR, varname,
CURL_NEW_ENV_VALUE, varval);
len += tmplen;
}
- }
- }
+ }
+ }
msnprintf((char *)&temp[len], sizeof(temp) - len,
"%c%c", CURL_IAC, CURL_SE);
- len += 2;
- bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
- if(bytes_written < 0) {
- err = SOCKERRNO;
- failf(data,"Sending data failed (%d)",err);
- }
- printsub(data, '>', &temp[2], len-2);
- break;
- }
- return;
-}
-
-
-/*
- * sendsuboption()
- *
- * Send suboption information to the server side.
- */
-
-static void sendsuboption(struct connectdata *conn, int option)
-{
- ssize_t bytes_written;
- int err;
- unsigned short x, y;
+ len += 2;
+ bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
+ if(bytes_written < 0) {
+ err = SOCKERRNO;
+ failf(data,"Sending data failed (%d)",err);
+ }
+ printsub(data, '>', &temp[2], len-2);
+ break;
+ }
+ return;
+}
+
+
+/*
+ * sendsuboption()
+ *
+ * Send suboption information to the server side.
+ */
+
+static void sendsuboption(struct connectdata *conn, int option)
+{
+ ssize_t bytes_written;
+ int err;
+ unsigned short x, y;
unsigned char *uc1, *uc2;
-
+
struct Curl_easy *data = conn->data;
struct TELNET *tn = (struct TELNET *)data->req.p.telnet;
-
+
switch(option) {
- case CURL_TELOPT_NAWS:
- /* We prepare data to be sent */
- CURL_SB_CLEAR(tn);
- CURL_SB_ACCUM(tn, CURL_IAC);
- CURL_SB_ACCUM(tn, CURL_SB);
- CURL_SB_ACCUM(tn, CURL_TELOPT_NAWS);
+ case CURL_TELOPT_NAWS:
+ /* We prepare data to be sent */
+ CURL_SB_CLEAR(tn);
+ CURL_SB_ACCUM(tn, CURL_IAC);
+ CURL_SB_ACCUM(tn, CURL_SB);
+ CURL_SB_ACCUM(tn, CURL_TELOPT_NAWS);
/* We must deal either with little or big endian processors */
- /* Window size must be sent according to the 'network order' */
+ /* Window size must be sent according to the 'network order' */
x = htons(tn->subopt_wsx);
y = htons(tn->subopt_wsy);
uc1 = (unsigned char *)&x;
uc2 = (unsigned char *)&y;
- CURL_SB_ACCUM(tn, uc1[0]);
- CURL_SB_ACCUM(tn, uc1[1]);
- CURL_SB_ACCUM(tn, uc2[0]);
- CURL_SB_ACCUM(tn, uc2[1]);
-
- CURL_SB_ACCUM(tn, CURL_IAC);
- CURL_SB_ACCUM(tn, CURL_SE);
- CURL_SB_TERM(tn);
- /* data suboption is now ready */
-
+ CURL_SB_ACCUM(tn, uc1[0]);
+ CURL_SB_ACCUM(tn, uc1[1]);
+ CURL_SB_ACCUM(tn, uc2[0]);
+ CURL_SB_ACCUM(tn, uc2[1]);
+
+ CURL_SB_ACCUM(tn, CURL_IAC);
+ CURL_SB_ACCUM(tn, CURL_SE);
+ CURL_SB_TERM(tn);
+ /* data suboption is now ready */
+
printsub(data, '>', (unsigned char *)tn->subbuffer + 2,
- CURL_SB_LEN(tn)-2);
-
- /* we send the header of the suboption... */
- bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer, 3);
- if(bytes_written < 0) {
- err = SOCKERRNO;
- failf(data, "Sending data failed (%d)", err);
- }
- /* ... then the window size with the send_telnet_data() function
- to deal with 0xFF cases ... */
+ CURL_SB_LEN(tn)-2);
+
+ /* we send the header of the suboption... */
+ bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer, 3);
+ if(bytes_written < 0) {
+ err = SOCKERRNO;
+ failf(data, "Sending data failed (%d)", err);
+ }
+ /* ... then the window size with the send_telnet_data() function
+ to deal with 0xFF cases ... */
send_telnet_data(conn, (char *)tn->subbuffer + 3, 4);
- /* ... and the footer */
+ /* ... and the footer */
bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer + 7, 2);
- if(bytes_written < 0) {
- err = SOCKERRNO;
- failf(data, "Sending data failed (%d)", err);
- }
- break;
- }
-}
-
-
-static
-CURLcode telrcv(struct connectdata *conn,
- const unsigned char *inbuf, /* Data received from socket */
- ssize_t count) /* Number of bytes received */
-{
- unsigned char c;
- CURLcode result;
- int in = 0;
+ if(bytes_written < 0) {
+ err = SOCKERRNO;
+ failf(data, "Sending data failed (%d)", err);
+ }
+ break;
+ }
+}
+
+
+static
+CURLcode telrcv(struct connectdata *conn,
+ const unsigned char *inbuf, /* Data received from socket */
+ ssize_t count) /* Number of bytes received */
+{
+ unsigned char c;
+ CURLcode result;
+ int in = 0;
int startwrite = -1;
struct Curl_easy *data = conn->data;
struct TELNET *tn = (struct TELNET *)data->req.p.telnet;
-
-#define startskipping() \
- if(startwrite >= 0) { \
- result = Curl_client_write(conn, \
- CLIENTWRITE_BODY, \
- (char *)&inbuf[startwrite], \
- in-startwrite); \
+
+#define startskipping() \
+ if(startwrite >= 0) { \
+ result = Curl_client_write(conn, \
+ CLIENTWRITE_BODY, \
+ (char *)&inbuf[startwrite], \
+ in-startwrite); \
if(result) \
- return result; \
- } \
- startwrite = -1
-
-#define writebyte() \
- if(startwrite < 0) \
- startwrite = in
-
-#define bufferflush() startskipping()
-
- while(count--) {
- c = inbuf[in];
-
+ return result; \
+ } \
+ startwrite = -1
+
+#define writebyte() \
+ if(startwrite < 0) \
+ startwrite = in
+
+#define bufferflush() startskipping()
+
+ while(count--) {
+ c = inbuf[in];
+
switch(tn->telrcv_state) {
- case CURL_TS_CR:
- tn->telrcv_state = CURL_TS_DATA;
- if(c == '\0') {
- startskipping();
- break; /* Ignore \0 after CR */
- }
- writebyte();
- break;
-
- case CURL_TS_DATA:
- if(c == CURL_IAC) {
- tn->telrcv_state = CURL_TS_IAC;
- startskipping();
- break;
- }
- else if(c == '\r')
- tn->telrcv_state = CURL_TS_CR;
- writebyte();
- break;
-
- case CURL_TS_IAC:
- process_iac:
- DEBUGASSERT(startwrite < 0);
+ case CURL_TS_CR:
+ tn->telrcv_state = CURL_TS_DATA;
+ if(c == '\0') {
+ startskipping();
+ break; /* Ignore \0 after CR */
+ }
+ writebyte();
+ break;
+
+ case CURL_TS_DATA:
+ if(c == CURL_IAC) {
+ tn->telrcv_state = CURL_TS_IAC;
+ startskipping();
+ break;
+ }
+ else if(c == '\r')
+ tn->telrcv_state = CURL_TS_CR;
+ writebyte();
+ break;
+
+ case CURL_TS_IAC:
+ process_iac:
+ DEBUGASSERT(startwrite < 0);
switch(c) {
- case CURL_WILL:
- tn->telrcv_state = CURL_TS_WILL;
- break;
- case CURL_WONT:
- tn->telrcv_state = CURL_TS_WONT;
- break;
- case CURL_DO:
- tn->telrcv_state = CURL_TS_DO;
- break;
- case CURL_DONT:
- tn->telrcv_state = CURL_TS_DONT;
- break;
- case CURL_SB:
- CURL_SB_CLEAR(tn);
- tn->telrcv_state = CURL_TS_SB;
- break;
- case CURL_IAC:
- tn->telrcv_state = CURL_TS_DATA;
- writebyte();
- break;
- case CURL_DM:
- case CURL_NOP:
- case CURL_GA:
- default:
- tn->telrcv_state = CURL_TS_DATA;
- printoption(data, "RCVD", CURL_IAC, c);
- break;
- }
- break;
-
- case CURL_TS_WILL:
- printoption(data, "RCVD", CURL_WILL, c);
- tn->please_negotiate = 1;
- rec_will(conn, c);
- tn->telrcv_state = CURL_TS_DATA;
- break;
-
- case CURL_TS_WONT:
- printoption(data, "RCVD", CURL_WONT, c);
- tn->please_negotiate = 1;
- rec_wont(conn, c);
- tn->telrcv_state = CURL_TS_DATA;
- break;
-
- case CURL_TS_DO:
- printoption(data, "RCVD", CURL_DO, c);
- tn->please_negotiate = 1;
- rec_do(conn, c);
- tn->telrcv_state = CURL_TS_DATA;
- break;
-
- case CURL_TS_DONT:
- printoption(data, "RCVD", CURL_DONT, c);
- tn->please_negotiate = 1;
- rec_dont(conn, c);
- tn->telrcv_state = CURL_TS_DATA;
- break;
-
- case CURL_TS_SB:
- if(c == CURL_IAC)
- tn->telrcv_state = CURL_TS_SE;
- else
+ case CURL_WILL:
+ tn->telrcv_state = CURL_TS_WILL;
+ break;
+ case CURL_WONT:
+ tn->telrcv_state = CURL_TS_WONT;
+ break;
+ case CURL_DO:
+ tn->telrcv_state = CURL_TS_DO;
+ break;
+ case CURL_DONT:
+ tn->telrcv_state = CURL_TS_DONT;
+ break;
+ case CURL_SB:
+ CURL_SB_CLEAR(tn);
+ tn->telrcv_state = CURL_TS_SB;
+ break;
+ case CURL_IAC:
+ tn->telrcv_state = CURL_TS_DATA;
+ writebyte();
+ break;
+ case CURL_DM:
+ case CURL_NOP:
+ case CURL_GA:
+ default:
+ tn->telrcv_state = CURL_TS_DATA;
+ printoption(data, "RCVD", CURL_IAC, c);
+ break;
+ }
+ break;
+
+ case CURL_TS_WILL:
+ printoption(data, "RCVD", CURL_WILL, c);
+ tn->please_negotiate = 1;
+ rec_will(conn, c);
+ tn->telrcv_state = CURL_TS_DATA;
+ break;
+
+ case CURL_TS_WONT:
+ printoption(data, "RCVD", CURL_WONT, c);
+ tn->please_negotiate = 1;
+ rec_wont(conn, c);
+ tn->telrcv_state = CURL_TS_DATA;
+ break;
+
+ case CURL_TS_DO:
+ printoption(data, "RCVD", CURL_DO, c);
+ tn->please_negotiate = 1;
+ rec_do(conn, c);
+ tn->telrcv_state = CURL_TS_DATA;
+ break;
+
+ case CURL_TS_DONT:
+ printoption(data, "RCVD", CURL_DONT, c);
+ tn->please_negotiate = 1;
+ rec_dont(conn, c);
+ tn->telrcv_state = CURL_TS_DATA;
+ break;
+
+ case CURL_TS_SB:
+ if(c == CURL_IAC)
+ tn->telrcv_state = CURL_TS_SE;
+ else
CURL_SB_ACCUM(tn, c);
- break;
-
- case CURL_TS_SE:
- if(c != CURL_SE) {
- if(c != CURL_IAC) {
- /*
- * This is an error. We only expect to get "IAC IAC" or "IAC SE".
- * Several things may have happened. An IAC was not doubled, the
- * IAC SE was left off, or another option got inserted into the
- * suboption are all possibilities. If we assume that the IAC was
- * not doubled, and really the IAC SE was left off, we could get
+ break;
+
+ case CURL_TS_SE:
+ if(c != CURL_SE) {
+ if(c != CURL_IAC) {
+ /*
+ * This is an error. We only expect to get "IAC IAC" or "IAC SE".
+ * Several things may have happened. An IAC was not doubled, the
+ * IAC SE was left off, or another option got inserted into the
+ * suboption are all possibilities. If we assume that the IAC was
+ * not doubled, and really the IAC SE was left off, we could get
* into an infinite loop here. So, instead, we terminate the
- * suboption, and process the partial suboption if we can.
- */
- CURL_SB_ACCUM(tn, CURL_IAC);
- CURL_SB_ACCUM(tn, c);
- tn->subpointer -= 2;
- CURL_SB_TERM(tn);
-
- printoption(data, "In SUBOPTION processing, RCVD", CURL_IAC, c);
- suboption(conn); /* handle sub-option */
- tn->telrcv_state = CURL_TS_IAC;
- goto process_iac;
- }
+ * suboption, and process the partial suboption if we can.
+ */
+ CURL_SB_ACCUM(tn, CURL_IAC);
+ CURL_SB_ACCUM(tn, c);
+ tn->subpointer -= 2;
+ CURL_SB_TERM(tn);
+
+ printoption(data, "In SUBOPTION processing, RCVD", CURL_IAC, c);
+ suboption(conn); /* handle sub-option */
+ tn->telrcv_state = CURL_TS_IAC;
+ goto process_iac;
+ }
CURL_SB_ACCUM(tn, c);
- tn->telrcv_state = CURL_TS_SB;
- }
+ tn->telrcv_state = CURL_TS_SB;
+ }
else {
- CURL_SB_ACCUM(tn, CURL_IAC);
- CURL_SB_ACCUM(tn, CURL_SE);
- tn->subpointer -= 2;
- CURL_SB_TERM(tn);
- suboption(conn); /* handle sub-option */
- tn->telrcv_state = CURL_TS_DATA;
- }
- break;
- }
- ++in;
- }
- bufferflush();
- return CURLE_OK;
-}
-
-/* Escape and send a telnet data block */
-static CURLcode send_telnet_data(struct connectdata *conn,
- char *buffer, ssize_t nread)
-{
+ CURL_SB_ACCUM(tn, CURL_IAC);
+ CURL_SB_ACCUM(tn, CURL_SE);
+ tn->subpointer -= 2;
+ CURL_SB_TERM(tn);
+ suboption(conn); /* handle sub-option */
+ tn->telrcv_state = CURL_TS_DATA;
+ }
+ break;
+ }
+ ++in;
+ }
+ bufferflush();
+ return CURLE_OK;
+}
+
+/* Escape and send a telnet data block */
+static CURLcode send_telnet_data(struct connectdata *conn,
+ char *buffer, ssize_t nread)
+{
ssize_t escapes, i, outlen;
unsigned char *outbuf = NULL;
CURLcode result = CURLE_OK;
- ssize_t bytes_written, total_written;
-
+ ssize_t bytes_written, total_written;
+
/* Determine size of new buffer after escaping */
escapes = 0;
for(i = 0; i < nread; i++)
if((unsigned char)buffer[i] == CURL_IAC)
escapes++;
outlen = nread + escapes;
-
+
if(outlen == nread)
outbuf = (unsigned char *)buffer;
else {
@@ -1201,7 +1201,7 @@ static CURLcode send_telnet_data(struct connectdata *conn,
outbuf[j++] = CURL_IAC;
}
outbuf[j] = '\0';
- }
+ }
total_written = 0;
while(!result && total_written < outlen) {
@@ -1230,358 +1230,358 @@ static CURLcode send_telnet_data(struct connectdata *conn,
free(outbuf);
return result;
-}
-
-static CURLcode telnet_done(struct connectdata *conn,
- CURLcode status, bool premature)
-{
+}
+
+static CURLcode telnet_done(struct connectdata *conn,
+ CURLcode status, bool premature)
+{
struct TELNET *tn = (struct TELNET *)conn->data->req.p.telnet;
- (void)status; /* unused */
- (void)premature; /* not used */
-
- if(!tn)
- return CURLE_OK;
-
- curl_slist_free_all(tn->telnet_vars);
- tn->telnet_vars = NULL;
-
+ (void)status; /* unused */
+ (void)premature; /* not used */
+
+ if(!tn)
+ return CURLE_OK;
+
+ curl_slist_free_all(tn->telnet_vars);
+ tn->telnet_vars = NULL;
+
Curl_safefree(conn->data->req.p.telnet);
-
- return CURLE_OK;
-}
-
-static CURLcode telnet_do(struct connectdata *conn, bool *done)
-{
+
+ return CURLE_OK;
+}
+
+static CURLcode telnet_do(struct connectdata *conn, bool *done)
+{
CURLcode result;
struct Curl_easy *data = conn->data;
- curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
-#ifdef USE_WINSOCK
- WSAEVENT event_handle;
- WSANETWORKEVENTS events;
- HANDLE stdin_handle;
- HANDLE objs[2];
- DWORD obj_count;
- DWORD wait_timeout;
- DWORD readfile_read;
- int err;
-#else
+ curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
+#ifdef USE_WINSOCK
+ WSAEVENT event_handle;
+ WSANETWORKEVENTS events;
+ HANDLE stdin_handle;
+ HANDLE objs[2];
+ DWORD obj_count;
+ DWORD wait_timeout;
+ DWORD readfile_read;
+ int err;
+#else
timediff_t interval_ms;
- struct pollfd pfd[2];
- int poll_cnt;
- curl_off_t total_dl = 0;
- curl_off_t total_ul = 0;
-#endif
- ssize_t nread;
+ struct pollfd pfd[2];
+ int poll_cnt;
+ curl_off_t total_dl = 0;
+ curl_off_t total_ul = 0;
+#endif
+ ssize_t nread;
struct curltime now;
- bool keepon = TRUE;
- char *buf = data->state.buffer;
- struct TELNET *tn;
-
- *done = TRUE; /* unconditionally */
-
+ bool keepon = TRUE;
+ char *buf = data->state.buffer;
+ struct TELNET *tn;
+
+ *done = TRUE; /* unconditionally */
+
result = init_telnet(conn);
if(result)
return result;
-
+
tn = data->req.p.telnet;
-
+
result = check_telnet_options(conn);
if(result)
return result;
-
-#ifdef USE_WINSOCK
- /* We want to wait for both stdin and the socket. Since
- ** the select() function in winsock only works on sockets
- ** we have to use the WaitForMultipleObjects() call.
- */
-
- /* First, create a sockets event object */
+
+#ifdef USE_WINSOCK
+ /* We want to wait for both stdin and the socket. Since
+ ** the select() function in winsock only works on sockets
+ ** we have to use the WaitForMultipleObjects() call.
+ */
+
+ /* First, create a sockets event object */
event_handle = WSACreateEvent();
- if(event_handle == WSA_INVALID_EVENT) {
+ if(event_handle == WSA_INVALID_EVENT) {
failf(data, "WSACreateEvent failed (%d)", SOCKERRNO);
- return CURLE_FAILED_INIT;
- }
-
- /* Tell winsock what events we want to listen to */
+ return CURLE_FAILED_INIT;
+ }
+
+ /* Tell winsock what events we want to listen to */
if(WSAEventSelect(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) {
WSACloseEvent(event_handle);
- return CURLE_OK;
- }
-
- /* The get the Windows file handle for stdin */
- stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
-
- /* Create the list of objects to wait for */
- objs[0] = event_handle;
- objs[1] = stdin_handle;
-
- /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it,
- else use the old WaitForMultipleObjects() way */
- if(GetFileType(stdin_handle) == FILE_TYPE_PIPE ||
- data->set.is_fread_set) {
- /* Don't wait for stdin_handle, just wait for event_handle */
- obj_count = 1;
- /* Check stdin_handle per 100 milliseconds */
- wait_timeout = 100;
- }
- else {
- obj_count = 2;
- wait_timeout = 1000;
- }
-
- /* Keep on listening and act on events */
- while(keepon) {
+ return CURLE_OK;
+ }
+
+ /* The get the Windows file handle for stdin */
+ stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
+
+ /* Create the list of objects to wait for */
+ objs[0] = event_handle;
+ objs[1] = stdin_handle;
+
+ /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it,
+ else use the old WaitForMultipleObjects() way */
+ if(GetFileType(stdin_handle) == FILE_TYPE_PIPE ||
+ data->set.is_fread_set) {
+ /* Don't wait for stdin_handle, just wait for event_handle */
+ obj_count = 1;
+ /* Check stdin_handle per 100 milliseconds */
+ wait_timeout = 100;
+ }
+ else {
+ obj_count = 2;
+ wait_timeout = 1000;
+ }
+
+ /* Keep on listening and act on events */
+ while(keepon) {
const DWORD buf_size = (DWORD)data->set.buffer_size;
DWORD waitret = WaitForMultipleObjects(obj_count, objs,
FALSE, wait_timeout);
- switch(waitret) {
+ switch(waitret) {
- case WAIT_TIMEOUT:
- {
- for(;;) {
+ case WAIT_TIMEOUT:
+ {
+ for(;;) {
if(data->set.is_fread_set) {
size_t n;
- /* read from user-supplied method */
+ /* read from user-supplied method */
n = data->state.fread_func(buf, 1, buf_size, data->state.in);
if(n == CURL_READFUNC_ABORT) {
- keepon = FALSE;
+ keepon = FALSE;
result = CURLE_READ_ERROR;
- break;
- }
-
+ break;
+ }
+
if(n == CURL_READFUNC_PAUSE)
- break;
-
+ break;
+
if(n == 0) /* no bytes */
- break;
-
+ break;
+
/* fall through with number of bytes read */
readfile_read = (DWORD)n;
- }
- else {
- /* read from stdin */
- if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL,
- &readfile_read, NULL)) {
- keepon = FALSE;
+ }
+ else {
+ /* read from stdin */
+ if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL,
+ &readfile_read, NULL)) {
+ keepon = FALSE;
result = CURLE_READ_ERROR;
- break;
- }
-
- if(!readfile_read)
- break;
-
+ break;
+ }
+
+ if(!readfile_read)
+ break;
+
if(!ReadFile(stdin_handle, buf, buf_size,
- &readfile_read, NULL)) {
- keepon = FALSE;
+ &readfile_read, NULL)) {
+ keepon = FALSE;
result = CURLE_READ_ERROR;
- break;
- }
- }
-
+ break;
+ }
+ }
+
result = send_telnet_data(conn, buf, readfile_read);
if(result) {
- keepon = FALSE;
- break;
- }
- }
- }
- break;
-
- case WAIT_OBJECT_0 + 1:
- {
+ keepon = FALSE;
+ break;
+ }
+ }
+ }
+ break;
+
+ case WAIT_OBJECT_0 + 1:
+ {
if(!ReadFile(stdin_handle, buf, buf_size,
- &readfile_read, NULL)) {
- keepon = FALSE;
+ &readfile_read, NULL)) {
+ keepon = FALSE;
result = CURLE_READ_ERROR;
- break;
- }
-
+ break;
+ }
+
result = send_telnet_data(conn, buf, readfile_read);
if(result) {
- keepon = FALSE;
- break;
- }
- }
- break;
-
- case WAIT_OBJECT_0:
+ keepon = FALSE;
+ break;
+ }
+ }
+ break;
+
+ case WAIT_OBJECT_0:
{
events.lNetworkEvents = 0;
if(WSAEnumNetworkEvents(sockfd, event_handle, &events) == SOCKET_ERROR) {
err = SOCKERRNO;
if(err != EINPROGRESS) {
infof(data, "WSAEnumNetworkEvents failed (%d)", err);
- keepon = FALSE;
+ keepon = FALSE;
result = CURLE_READ_ERROR;
- }
- break;
- }
- if(events.lNetworkEvents & FD_READ) {
- /* read data from network */
+ }
+ break;
+ }
+ if(events.lNetworkEvents & FD_READ) {
+ /* read data from network */
result = Curl_read(conn, sockfd, buf, data->set.buffer_size, &nread);
- /* read would've blocked. Loop again */
+ /* read would've blocked. Loop again */
if(result == CURLE_AGAIN)
- break;
- /* returned not-zero, this an error */
+ break;
+ /* returned not-zero, this an error */
else if(result) {
- keepon = FALSE;
- break;
- }
- /* returned zero but actually received 0 or less here,
- the server closed the connection and we bail out */
- else if(nread <= 0) {
- keepon = FALSE;
- break;
- }
-
+ keepon = FALSE;
+ break;
+ }
+ /* returned zero but actually received 0 or less here,
+ the server closed the connection and we bail out */
+ else if(nread <= 0) {
+ keepon = FALSE;
+ break;
+ }
+
result = telrcv(conn, (unsigned char *) buf, nread);
if(result) {
- keepon = FALSE;
- break;
- }
-
- /* Negotiate if the peer has started negotiating,
- otherwise don't. We don't want to speak telnet with
- non-telnet servers, like POP or SMTP. */
- if(tn->please_negotiate && !tn->already_negotiated) {
- negotiate(conn);
- tn->already_negotiated = 1;
- }
- }
- if(events.lNetworkEvents & FD_CLOSE) {
- keepon = FALSE;
- }
+ keepon = FALSE;
+ break;
+ }
+
+ /* Negotiate if the peer has started negotiating,
+ otherwise don't. We don't want to speak telnet with
+ non-telnet servers, like POP or SMTP. */
+ if(tn->please_negotiate && !tn->already_negotiated) {
+ negotiate(conn);
+ tn->already_negotiated = 1;
+ }
+ }
+ if(events.lNetworkEvents & FD_CLOSE) {
+ keepon = FALSE;
+ }
}
break;
-
- }
-
- if(data->set.timeout) {
+
+ }
+
+ if(data->set.timeout) {
now = Curl_now();
if(Curl_timediff(now, conn->created) >= data->set.timeout) {
- failf(data, "Time-out");
+ failf(data, "Time-out");
result = CURLE_OPERATION_TIMEDOUT;
- keepon = FALSE;
- }
- }
- }
-
- /* We called WSACreateEvent, so call WSACloseEvent */
+ keepon = FALSE;
+ }
+ }
+ }
+
+ /* We called WSACreateEvent, so call WSACloseEvent */
if(!WSACloseEvent(event_handle)) {
infof(data, "WSACloseEvent failed (%d)", SOCKERRNO);
- }
-#else
- pfd[0].fd = sockfd;
- pfd[0].events = POLLIN;
-
+ }
+#else
+ pfd[0].fd = sockfd;
+ pfd[0].events = POLLIN;
+
if(data->set.is_fread_set) {
- poll_cnt = 1;
- interval_ms = 100; /* poll user-supplied read function */
- }
- else {
- /* really using fread, so infile is a FILE* */
+ poll_cnt = 1;
+ interval_ms = 100; /* poll user-supplied read function */
+ }
+ else {
+ /* really using fread, so infile is a FILE* */
pfd[1].fd = fileno((FILE *)data->state.in);
- pfd[1].events = POLLIN;
- poll_cnt = 2;
- interval_ms = 1 * 1000;
- }
-
- while(keepon) {
+ pfd[1].events = POLLIN;
+ poll_cnt = 2;
+ interval_ms = 1 * 1000;
+ }
+
+ while(keepon) {
switch(Curl_poll(pfd, poll_cnt, interval_ms)) {
- case -1: /* error, stop reading */
- keepon = FALSE;
- continue;
- case 0: /* timeout */
- pfd[0].revents = 0;
- pfd[1].revents = 0;
+ case -1: /* error, stop reading */
+ keepon = FALSE;
+ continue;
+ case 0: /* timeout */
+ pfd[0].revents = 0;
+ pfd[1].revents = 0;
/* FALLTHROUGH */
- default: /* read! */
- if(pfd[0].revents & POLLIN) {
- /* read data from network */
+ default: /* read! */
+ if(pfd[0].revents & POLLIN) {
+ /* read data from network */
result = Curl_read(conn, sockfd, buf, data->set.buffer_size, &nread);
- /* read would've blocked. Loop again */
+ /* read would've blocked. Loop again */
if(result == CURLE_AGAIN)
- break;
- /* returned not-zero, this an error */
+ break;
+ /* returned not-zero, this an error */
if(result) {
- keepon = FALSE;
- break;
- }
- /* returned zero but actually received 0 or less here,
- the server closed the connection and we bail out */
- else if(nread <= 0) {
- keepon = FALSE;
- break;
- }
-
- total_dl += nread;
- Curl_pgrsSetDownloadCounter(data, total_dl);
+ keepon = FALSE;
+ break;
+ }
+ /* returned zero but actually received 0 or less here,
+ the server closed the connection and we bail out */
+ else if(nread <= 0) {
+ keepon = FALSE;
+ break;
+ }
+
+ total_dl += nread;
+ Curl_pgrsSetDownloadCounter(data, total_dl);
result = telrcv(conn, (unsigned char *)buf, nread);
if(result) {
- keepon = FALSE;
- break;
- }
-
- /* Negotiate if the peer has started negotiating,
- otherwise don't. We don't want to speak telnet with
- non-telnet servers, like POP or SMTP. */
- if(tn->please_negotiate && !tn->already_negotiated) {
- negotiate(conn);
- tn->already_negotiated = 1;
- }
- }
-
- nread = 0;
- if(poll_cnt == 2) {
- if(pfd[1].revents & POLLIN) { /* read from in file */
+ keepon = FALSE;
+ break;
+ }
+
+ /* Negotiate if the peer has started negotiating,
+ otherwise don't. We don't want to speak telnet with
+ non-telnet servers, like POP or SMTP. */
+ if(tn->please_negotiate && !tn->already_negotiated) {
+ negotiate(conn);
+ tn->already_negotiated = 1;
+ }
+ }
+
+ nread = 0;
+ if(poll_cnt == 2) {
+ if(pfd[1].revents & POLLIN) { /* read from in file */
nread = read(pfd[1].fd, buf, data->set.buffer_size);
- }
- }
- else {
- /* read from user-supplied method */
+ }
+ }
+ else {
+ /* read from user-supplied method */
nread = (int)data->state.fread_func(buf, 1, data->set.buffer_size,
data->state.in);
- if(nread == CURL_READFUNC_ABORT) {
- keepon = FALSE;
- break;
- }
- if(nread == CURL_READFUNC_PAUSE)
- break;
- }
-
- if(nread > 0) {
+ if(nread == CURL_READFUNC_ABORT) {
+ keepon = FALSE;
+ break;
+ }
+ if(nread == CURL_READFUNC_PAUSE)
+ break;
+ }
+
+ if(nread > 0) {
result = send_telnet_data(conn, buf, nread);
if(result) {
- keepon = FALSE;
- break;
- }
- total_ul += nread;
- Curl_pgrsSetUploadCounter(data, total_ul);
- }
- else if(nread < 0)
- keepon = FALSE;
-
- break;
- } /* poll switch statement */
-
- if(data->set.timeout) {
+ keepon = FALSE;
+ break;
+ }
+ total_ul += nread;
+ Curl_pgrsSetUploadCounter(data, total_ul);
+ }
+ else if(nread < 0)
+ keepon = FALSE;
+
+ break;
+ } /* poll switch statement */
+
+ if(data->set.timeout) {
now = Curl_now();
if(Curl_timediff(now, conn->created) >= data->set.timeout) {
- failf(data, "Time-out");
+ failf(data, "Time-out");
result = CURLE_OPERATION_TIMEDOUT;
- keepon = FALSE;
- }
- }
-
- if(Curl_pgrsUpdate(conn)) {
+ keepon = FALSE;
+ }
+ }
+
+ if(Curl_pgrsUpdate(conn)) {
result = CURLE_ABORTED_BY_CALLBACK;
- break;
- }
- }
-#endif
- /* mark this as "no further transfer wanted" */
+ break;
+ }
+ }
+#endif
+ /* mark this as "no further transfer wanted" */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
-
+
return result;
-}
-#endif
+}
+#endif
diff --git a/contrib/libs/curl/lib/telnet.h b/contrib/libs/curl/lib/telnet.h
index 48b24300af..1427473a9f 100644
--- a/contrib/libs/curl/lib/telnet.h
+++ b/contrib/libs/curl/lib/telnet.h
@@ -1,28 +1,28 @@
-#ifndef HEADER_CURL_TELNET_H
-#define HEADER_CURL_TELNET_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_TELNET_H
+#define HEADER_CURL_TELNET_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifndef CURL_DISABLE_TELNET
-extern const struct Curl_handler Curl_handler_telnet;
-#endif
-
-#endif /* HEADER_CURL_TELNET_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifndef CURL_DISABLE_TELNET
+extern const struct Curl_handler Curl_handler_telnet;
+#endif
+
+#endif /* HEADER_CURL_TELNET_H */
diff --git a/contrib/libs/curl/lib/tftp.c b/contrib/libs/curl/lib/tftp.c
index c4eee0a41d..fba3f5e8c2 100644
--- a/contrib/libs/curl/lib/tftp.c
+++ b/contrib/libs/curl/lib/tftp.c
@@ -1,497 +1,497 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifndef CURL_DISABLE_TFTP
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "transfer.h"
-#include "sendf.h"
-#include "tftp.h"
-#include "progress.h"
-#include "connect.h"
-#include "strerror.h"
-#include "sockaddr.h" /* required for Curl_sockaddr_storage */
-#include "multiif.h"
-#include "url.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifndef CURL_DISABLE_TFTP
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "transfer.h"
+#include "sendf.h"
+#include "tftp.h"
+#include "progress.h"
+#include "connect.h"
+#include "strerror.h"
+#include "sockaddr.h" /* required for Curl_sockaddr_storage */
+#include "multiif.h"
+#include "url.h"
#include "strcase.h"
-#include "speedcheck.h"
+#include "speedcheck.h"
#include "select.h"
#include "escape.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* RFC2348 allows the block size to be negotiated */
-#define TFTP_BLKSIZE_DEFAULT 512
-#define TFTP_BLKSIZE_MIN 8
-#define TFTP_BLKSIZE_MAX 65464
-#define TFTP_OPTION_BLKSIZE "blksize"
-
-/* from RFC2349: */
-#define TFTP_OPTION_TSIZE "tsize"
-#define TFTP_OPTION_INTERVAL "timeout"
-
-typedef enum {
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* RFC2348 allows the block size to be negotiated */
+#define TFTP_BLKSIZE_DEFAULT 512
+#define TFTP_BLKSIZE_MIN 8
+#define TFTP_BLKSIZE_MAX 65464
+#define TFTP_OPTION_BLKSIZE "blksize"
+
+/* from RFC2349: */
+#define TFTP_OPTION_TSIZE "tsize"
+#define TFTP_OPTION_INTERVAL "timeout"
+
+typedef enum {
TFTP_MODE_NETASCII = 0,
- TFTP_MODE_OCTET
-} tftp_mode_t;
-
-typedef enum {
+ TFTP_MODE_OCTET
+} tftp_mode_t;
+
+typedef enum {
TFTP_STATE_START = 0,
- TFTP_STATE_RX,
- TFTP_STATE_TX,
- TFTP_STATE_FIN
-} tftp_state_t;
-
-typedef enum {
- TFTP_EVENT_NONE = -1,
- TFTP_EVENT_INIT = 0,
- TFTP_EVENT_RRQ = 1,
- TFTP_EVENT_WRQ = 2,
- TFTP_EVENT_DATA = 3,
- TFTP_EVENT_ACK = 4,
- TFTP_EVENT_ERROR = 5,
- TFTP_EVENT_OACK = 6,
- TFTP_EVENT_TIMEOUT
-} tftp_event_t;
-
-typedef enum {
+ TFTP_STATE_RX,
+ TFTP_STATE_TX,
+ TFTP_STATE_FIN
+} tftp_state_t;
+
+typedef enum {
+ TFTP_EVENT_NONE = -1,
+ TFTP_EVENT_INIT = 0,
+ TFTP_EVENT_RRQ = 1,
+ TFTP_EVENT_WRQ = 2,
+ TFTP_EVENT_DATA = 3,
+ TFTP_EVENT_ACK = 4,
+ TFTP_EVENT_ERROR = 5,
+ TFTP_EVENT_OACK = 6,
+ TFTP_EVENT_TIMEOUT
+} tftp_event_t;
+
+typedef enum {
TFTP_ERR_UNDEF = 0,
- TFTP_ERR_NOTFOUND,
- TFTP_ERR_PERM,
- TFTP_ERR_DISKFULL,
- TFTP_ERR_ILLEGAL,
- TFTP_ERR_UNKNOWNID,
- TFTP_ERR_EXISTS,
- TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
-
- /* The remaining error codes are internal to curl */
- TFTP_ERR_NONE = -100,
- TFTP_ERR_TIMEOUT,
- TFTP_ERR_NORESPONSE
-} tftp_error_t;
-
+ TFTP_ERR_NOTFOUND,
+ TFTP_ERR_PERM,
+ TFTP_ERR_DISKFULL,
+ TFTP_ERR_ILLEGAL,
+ TFTP_ERR_UNKNOWNID,
+ TFTP_ERR_EXISTS,
+ TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
+
+ /* The remaining error codes are internal to curl */
+ TFTP_ERR_NONE = -100,
+ TFTP_ERR_TIMEOUT,
+ TFTP_ERR_NORESPONSE
+} tftp_error_t;
+
struct tftp_packet {
- unsigned char *data;
+ unsigned char *data;
};
-
+
struct tftp_state_data {
- tftp_state_t state;
- tftp_mode_t mode;
- tftp_error_t error;
- tftp_event_t event;
- struct connectdata *conn;
- curl_socket_t sockfd;
- int retries;
- int retry_time;
- int retry_max;
- time_t start_time;
- time_t max_time;
- time_t rx_time;
- unsigned short block;
- struct Curl_sockaddr_storage local_addr;
- struct Curl_sockaddr_storage remote_addr;
- curl_socklen_t remote_addrlen;
- int rbytes;
- int sbytes;
- int blksize;
- int requested_blksize;
+ tftp_state_t state;
+ tftp_mode_t mode;
+ tftp_error_t error;
+ tftp_event_t event;
+ struct connectdata *conn;
+ curl_socket_t sockfd;
+ int retries;
+ int retry_time;
+ int retry_max;
+ time_t start_time;
+ time_t max_time;
+ time_t rx_time;
+ unsigned short block;
+ struct Curl_sockaddr_storage local_addr;
+ struct Curl_sockaddr_storage remote_addr;
+ curl_socklen_t remote_addrlen;
+ int rbytes;
+ int sbytes;
+ int blksize;
+ int requested_blksize;
struct tftp_packet rpacket;
struct tftp_packet spacket;
};
-
-
-/* Forward declarations */
+
+
+/* Forward declarations */
static CURLcode tftp_rx(struct tftp_state_data *state, tftp_event_t event);
static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event);
-static CURLcode tftp_connect(struct connectdata *conn, bool *done);
-static CURLcode tftp_disconnect(struct connectdata *conn,
- bool dead_connection);
-static CURLcode tftp_do(struct connectdata *conn, bool *done);
-static CURLcode tftp_done(struct connectdata *conn,
- CURLcode, bool premature);
+static CURLcode tftp_connect(struct connectdata *conn, bool *done);
+static CURLcode tftp_disconnect(struct connectdata *conn,
+ bool dead_connection);
+static CURLcode tftp_do(struct connectdata *conn, bool *done);
+static CURLcode tftp_done(struct connectdata *conn,
+ CURLcode, bool premature);
static CURLcode tftp_setup_connection(struct connectdata *conn);
-static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
-static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
+static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
+static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks);
-static CURLcode tftp_translate_code(tftp_error_t error);
-
-
-/*
- * TFTP protocol handler.
- */
-
-const struct Curl_handler Curl_handler_tftp = {
- "TFTP", /* scheme */
- tftp_setup_connection, /* setup_connection */
- tftp_do, /* do_it */
- tftp_done, /* done */
- ZERO_NULL, /* do_more */
- tftp_connect, /* connect_it */
- tftp_multi_statemach, /* connecting */
- tftp_doing, /* doing */
- tftp_getsock, /* proto_getsock */
- tftp_getsock, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- tftp_disconnect, /* disconnect */
- ZERO_NULL, /* readwrite */
+static CURLcode tftp_translate_code(tftp_error_t error);
+
+
+/*
+ * TFTP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_tftp = {
+ "TFTP", /* scheme */
+ tftp_setup_connection, /* setup_connection */
+ tftp_do, /* do_it */
+ tftp_done, /* done */
+ ZERO_NULL, /* do_more */
+ tftp_connect, /* connect_it */
+ tftp_multi_statemach, /* connecting */
+ tftp_doing, /* doing */
+ tftp_getsock, /* proto_getsock */
+ tftp_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ tftp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- PORT_TFTP, /* defport */
- CURLPROTO_TFTP, /* protocol */
+ PORT_TFTP, /* defport */
+ CURLPROTO_TFTP, /* protocol */
CURLPROTO_TFTP, /* family */
- PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
-};
-
-/**********************************************************
- *
- * tftp_set_timeouts -
- *
- * Set timeouts based on state machine state.
- * Use user provided connect timeouts until DATA or ACK
- * packet is received, then use user-provided transfer timeouts
- *
- *
- **********************************************************/
+ PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
+};
+
+/**********************************************************
+ *
+ * tftp_set_timeouts -
+ *
+ * Set timeouts based on state machine state.
+ * Use user provided connect timeouts until DATA or ACK
+ * packet is received, then use user-provided transfer timeouts
+ *
+ *
+ **********************************************************/
static CURLcode tftp_set_timeouts(struct tftp_state_data *state)
-{
- time_t maxtime, timeout;
+{
+ time_t maxtime, timeout;
timediff_t timeout_ms;
- bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
-
- time(&state->start_time);
-
- /* Compute drop-dead time */
- timeout_ms = Curl_timeleft(state->conn->data, NULL, start);
-
- if(timeout_ms < 0) {
- /* time-out, bail out, go home */
- failf(state->conn->data, "Connection time-out");
- return CURLE_OPERATION_TIMEDOUT;
- }
-
- if(start) {
-
- maxtime = (time_t)(timeout_ms + 500) / 1000;
+ bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
+
+ time(&state->start_time);
+
+ /* Compute drop-dead time */
+ timeout_ms = Curl_timeleft(state->conn->data, NULL, start);
+
+ if(timeout_ms < 0) {
+ /* time-out, bail out, go home */
+ failf(state->conn->data, "Connection time-out");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ if(start) {
+
+ maxtime = (time_t)(timeout_ms + 500) / 1000;
state->max_time = state->start_time + maxtime;
-
- /* Set per-block timeout to total */
+
+ /* Set per-block timeout to total */
timeout = maxtime;
-
- /* Average restart after 5 seconds */
- state->retry_max = (int)timeout/5;
-
- if(state->retry_max < 1)
- /* avoid division by zero below */
- state->retry_max = 1;
-
- /* Compute the re-start interval to suit the timeout */
- state->retry_time = (int)timeout/state->retry_max;
- if(state->retry_time<1)
+
+ /* Average restart after 5 seconds */
+ state->retry_max = (int)timeout/5;
+
+ if(state->retry_max < 1)
+ /* avoid division by zero below */
+ state->retry_max = 1;
+
+ /* Compute the re-start interval to suit the timeout */
+ state->retry_time = (int)timeout/state->retry_max;
+ if(state->retry_time<1)
state->retry_time = 1;
-
- }
- else {
- if(timeout_ms > 0)
- maxtime = (time_t)(timeout_ms + 500) / 1000;
- else
- maxtime = 3600;
-
+
+ }
+ else {
+ if(timeout_ms > 0)
+ maxtime = (time_t)(timeout_ms + 500) / 1000;
+ else
+ maxtime = 3600;
+
state->max_time = state->start_time + maxtime;
-
- /* Set per-block timeout to total */
- timeout = maxtime;
-
- /* Average reposting an ACK after 5 seconds */
- state->retry_max = (int)timeout/5;
- }
- /* But bound the total number */
- if(state->retry_max<3)
+
+ /* Set per-block timeout to total */
+ timeout = maxtime;
+
+ /* Average reposting an ACK after 5 seconds */
+ state->retry_max = (int)timeout/5;
+ }
+ /* But bound the total number */
+ if(state->retry_max<3)
state->retry_max = 3;
-
- if(state->retry_max>50)
+
+ if(state->retry_max>50)
state->retry_max = 50;
-
- /* Compute the re-ACK interval to suit the timeout */
- state->retry_time = (int)(timeout/state->retry_max);
- if(state->retry_time<1)
+
+ /* Compute the re-ACK interval to suit the timeout */
+ state->retry_time = (int)(timeout/state->retry_max);
+ if(state->retry_time<1)
state->retry_time = 1;
-
- infof(state->conn->data,
- "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
- (int)state->state, (long)(state->max_time-state->start_time),
- state->retry_time, state->retry_max);
-
- /* init RX time */
- time(&state->rx_time);
-
- return CURLE_OK;
-}
-
-/**********************************************************
- *
- * tftp_set_send_first
- *
- * Event handler for the START state
- *
- **********************************************************/
-
+
+ infof(state->conn->data,
+ "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
+ (int)state->state, (long)(state->max_time-state->start_time),
+ state->retry_time, state->retry_max);
+
+ /* init RX time */
+ time(&state->rx_time);
+
+ return CURLE_OK;
+}
+
+/**********************************************************
+ *
+ * tftp_set_send_first
+ *
+ * Event handler for the START state
+ *
+ **********************************************************/
+
static void setpacketevent(struct tftp_packet *packet, unsigned short num)
-{
- packet->data[0] = (unsigned char)(num >> 8);
- packet->data[1] = (unsigned char)(num & 0xff);
-}
-
-
+{
+ packet->data[0] = (unsigned char)(num >> 8);
+ packet->data[1] = (unsigned char)(num & 0xff);
+}
+
+
static void setpacketblock(struct tftp_packet *packet, unsigned short num)
-{
- packet->data[2] = (unsigned char)(num >> 8);
- packet->data[3] = (unsigned char)(num & 0xff);
-}
-
+{
+ packet->data[2] = (unsigned char)(num >> 8);
+ packet->data[3] = (unsigned char)(num & 0xff);
+}
+
static unsigned short getrpacketevent(const struct tftp_packet *packet)
-{
- return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
-}
-
+{
+ return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
+}
+
static unsigned short getrpacketblock(const struct tftp_packet *packet)
-{
- return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
-}
-
-static size_t Curl_strnlen(const char *string, size_t maxlen)
-{
+{
+ return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
+}
+
+static size_t Curl_strnlen(const char *string, size_t maxlen)
+{
const char *end = memchr(string, '\0', maxlen);
- return end ? (size_t) (end - string) : maxlen;
-}
-
-static const char *tftp_option_get(const char *buf, size_t len,
- const char **option, const char **value)
-{
- size_t loc;
-
+ return end ? (size_t) (end - string) : maxlen;
+}
+
+static const char *tftp_option_get(const char *buf, size_t len,
+ const char **option, const char **value)
+{
+ size_t loc;
+
loc = Curl_strnlen(buf, len);
- loc++; /* NULL term */
-
- if(loc >= len)
- return NULL;
- *option = buf;
-
+ loc++; /* NULL term */
+
+ if(loc >= len)
+ return NULL;
+ *option = buf;
+
loc += Curl_strnlen(buf + loc, len-loc);
- loc++; /* NULL term */
-
- if(loc > len)
- return NULL;
- *value = &buf[strlen(*option) + 1];
-
- return &buf[loc];
-}
-
+ loc++; /* NULL term */
+
+ if(loc > len)
+ return NULL;
+ *value = &buf[strlen(*option) + 1];
+
+ return &buf[loc];
+}
+
static CURLcode tftp_parse_option_ack(struct tftp_state_data *state,
- const char *ptr, int len)
-{
- const char *tmp = ptr;
+ const char *ptr, int len)
+{
+ const char *tmp = ptr;
struct Curl_easy *data = state->conn->data;
-
- /* if OACK doesn't contain blksize option, the default (512) must be used */
- state->blksize = TFTP_BLKSIZE_DEFAULT;
-
- while(tmp < ptr + len) {
- const char *option, *value;
-
- tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
- if(tmp == NULL) {
- failf(data, "Malformed ACK packet, rejecting");
- return CURLE_TFTP_ILLEGAL;
- }
-
- infof(data, "got option=(%s) value=(%s)\n", option, value);
-
- if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
- long blksize;
-
+
+ /* if OACK doesn't contain blksize option, the default (512) must be used */
+ state->blksize = TFTP_BLKSIZE_DEFAULT;
+
+ while(tmp < ptr + len) {
+ const char *option, *value;
+
+ tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
+ if(tmp == NULL) {
+ failf(data, "Malformed ACK packet, rejecting");
+ return CURLE_TFTP_ILLEGAL;
+ }
+
+ infof(data, "got option=(%s) value=(%s)\n", option, value);
+
+ if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
+ long blksize;
+
blksize = strtol(value, NULL, 10);
-
- if(!blksize) {
- failf(data, "invalid blocksize value in OACK packet");
- return CURLE_TFTP_ILLEGAL;
- }
+
+ if(!blksize) {
+ failf(data, "invalid blocksize value in OACK packet");
+ return CURLE_TFTP_ILLEGAL;
+ }
if(blksize > TFTP_BLKSIZE_MAX) {
- failf(data, "%s (%d)", "blksize is larger than max supported",
- TFTP_BLKSIZE_MAX);
- return CURLE_TFTP_ILLEGAL;
- }
- else if(blksize < TFTP_BLKSIZE_MIN) {
- failf(data, "%s (%d)", "blksize is smaller than min supported",
- TFTP_BLKSIZE_MIN);
- return CURLE_TFTP_ILLEGAL;
- }
- else if(blksize > state->requested_blksize) {
- /* could realloc pkt buffers here, but the spec doesn't call out
- * support for the server requesting a bigger blksize than the client
- * requests */
- failf(data, "%s (%ld)",
- "server requested blksize larger than allocated", blksize);
- return CURLE_TFTP_ILLEGAL;
- }
-
- state->blksize = (int)blksize;
- infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
- state->blksize, "requested", state->requested_blksize);
- }
- else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
- long tsize = 0;
-
+ failf(data, "%s (%d)", "blksize is larger than max supported",
+ TFTP_BLKSIZE_MAX);
+ return CURLE_TFTP_ILLEGAL;
+ }
+ else if(blksize < TFTP_BLKSIZE_MIN) {
+ failf(data, "%s (%d)", "blksize is smaller than min supported",
+ TFTP_BLKSIZE_MIN);
+ return CURLE_TFTP_ILLEGAL;
+ }
+ else if(blksize > state->requested_blksize) {
+ /* could realloc pkt buffers here, but the spec doesn't call out
+ * support for the server requesting a bigger blksize than the client
+ * requests */
+ failf(data, "%s (%ld)",
+ "server requested blksize larger than allocated", blksize);
+ return CURLE_TFTP_ILLEGAL;
+ }
+
+ state->blksize = (int)blksize;
+ infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
+ state->blksize, "requested", state->requested_blksize);
+ }
+ else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
+ long tsize = 0;
+
tsize = strtol(value, NULL, 10);
- infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
-
- /* tsize should be ignored on upload: Who cares about the size of the
- remote file? */
- if(!data->set.upload) {
- if(!tsize) {
- failf(data, "invalid tsize -:%s:- value in OACK packet", value);
- return CURLE_TFTP_ILLEGAL;
- }
- Curl_pgrsSetDownloadSize(data, tsize);
- }
- }
- }
-
- return CURLE_OK;
-}
-
+ infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
+
+ /* tsize should be ignored on upload: Who cares about the size of the
+ remote file? */
+ if(!data->set.upload) {
+ if(!tsize) {
+ failf(data, "invalid tsize -:%s:- value in OACK packet", value);
+ return CURLE_TFTP_ILLEGAL;
+ }
+ Curl_pgrsSetDownloadSize(data, tsize);
+ }
+ }
+ }
+
+ return CURLE_OK;
+}
+
static CURLcode tftp_option_add(struct tftp_state_data *state, size_t *csize,
char *buf, const char *option)
-{
+{
if(( strlen(option) + *csize + 1) > (size_t)state->blksize)
return CURLE_TFTP_ILLEGAL;
- strcpy(buf, option);
+ strcpy(buf, option);
*csize += strlen(option) + 1;
return CURLE_OK;
-}
-
+}
+
static CURLcode tftp_connect_for_tx(struct tftp_state_data *state,
- tftp_event_t event)
-{
+ tftp_event_t event)
+{
CURLcode result;
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
struct Curl_easy *data = state->conn->data;
-
- infof(data, "%s\n", "Connected for transmit");
-#endif
- state->state = TFTP_STATE_TX;
+
+ infof(data, "%s\n", "Connected for transmit");
+#endif
+ state->state = TFTP_STATE_TX;
result = tftp_set_timeouts(state);
if(result)
return result;
- return tftp_tx(state, event);
-}
-
+ return tftp_tx(state, event);
+}
+
static CURLcode tftp_connect_for_rx(struct tftp_state_data *state,
- tftp_event_t event)
-{
+ tftp_event_t event)
+{
CURLcode result;
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
struct Curl_easy *data = state->conn->data;
-
- infof(data, "%s\n", "Connected for receive");
-#endif
- state->state = TFTP_STATE_RX;
+
+ infof(data, "%s\n", "Connected for receive");
+#endif
+ state->state = TFTP_STATE_RX;
result = tftp_set_timeouts(state);
if(result)
return result;
- return tftp_rx(state, event);
-}
-
+ return tftp_rx(state, event);
+}
+
static CURLcode tftp_send_first(struct tftp_state_data *state,
tftp_event_t event)
-{
- size_t sbytes;
- ssize_t senddata;
- const char *mode = "octet";
- char *filename;
+{
+ size_t sbytes;
+ ssize_t senddata;
+ const char *mode = "octet";
+ char *filename;
struct Curl_easy *data = state->conn->data;
CURLcode result = CURLE_OK;
-
- /* Set ascii mode if -B flag was used */
- if(data->set.prefer_ascii)
- mode = "netascii";
-
- switch(event) {
-
- case TFTP_EVENT_INIT: /* Send the first packet out */
- case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
- /* Increment the retry counter, quit if over the limit */
- state->retries++;
- if(state->retries>state->retry_max) {
- state->error = TFTP_ERR_NORESPONSE;
- state->state = TFTP_STATE_FIN;
+
+ /* Set ascii mode if -B flag was used */
+ if(data->set.prefer_ascii)
+ mode = "netascii";
+
+ switch(event) {
+
+ case TFTP_EVENT_INIT: /* Send the first packet out */
+ case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
+ /* Increment the retry counter, quit if over the limit */
+ state->retries++;
+ if(state->retries>state->retry_max) {
+ state->error = TFTP_ERR_NORESPONSE;
+ state->state = TFTP_STATE_FIN;
return result;
- }
-
- if(data->set.upload) {
- /* If we are uploading, send an WRQ */
- setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
- state->conn->data->req.upload_fromhere =
+ }
+
+ if(data->set.upload) {
+ /* If we are uploading, send an WRQ */
+ setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
+ state->conn->data->req.upload_fromhere =
(char *)state->spacket.data + 4;
if(data->state.infilesize != -1)
Curl_pgrsSetUploadSize(data, data->state.infilesize);
- }
- else {
- /* If we are downloading, send an RRQ */
- setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
- }
- /* As RFC3617 describes the separator slash is not actually part of the
- file name so we skip the always-present first letter of the path
- string. */
+ }
+ else {
+ /* If we are downloading, send an RRQ */
+ setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
+ }
+ /* As RFC3617 describes the separator slash is not actually part of the
+ file name so we skip the always-present first letter of the path
+ string. */
result = Curl_urldecode(data, &state->conn->data->state.up.path[1], 0,
&filename, NULL, REJECT_ZERO);
if(result)
return result;
-
+
if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
failf(data, "TFTP file name too long\n");
free(filename);
@@ -501,8 +501,8 @@ static CURLcode tftp_send_first(struct tftp_state_data *state,
msnprintf((char *)state->spacket.data + 2,
state->blksize,
"%s%c%s%c", filename, '\0', mode, '\0');
- sbytes = 4 + strlen(filename) + strlen(mode);
-
+ sbytes = 4 + strlen(filename) + strlen(mode);
+
/* optional addition of TFTP options */
if(!data->set.tftp_no_options) {
char buf[64];
@@ -512,7 +512,7 @@ static CURLcode tftp_send_first(struct tftp_state_data *state,
data->state.infilesize);
else
strcpy(buf, "0"); /* the destination is large enough */
-
+
result = tftp_option_add(state, &sbytes,
(char *)state->spacket.data + sbytes,
TFTP_OPTION_TSIZE);
@@ -529,7 +529,7 @@ static CURLcode tftp_send_first(struct tftp_state_data *state,
if(result == CURLE_OK)
result = tftp_option_add(state, &sbytes,
(char *)state->spacket.data + sbytes, buf);
-
+
/* add timeout option */
msnprintf(buf, sizeof(buf), "%d", state->retry_time);
if(result == CURLE_OK)
@@ -546,248 +546,248 @@ static CURLcode tftp_send_first(struct tftp_state_data *state,
return CURLE_TFTP_ILLEGAL;
}
}
-
- /* the typecase for the 3rd argument is mostly for systems that do
- not have a size_t argument, like older unixes that want an 'int' */
- senddata = sendto(state->sockfd, (void *)state->spacket.data,
- (SEND_TYPE_ARG3)sbytes, 0,
- state->conn->ip_addr->ai_addr,
- state->conn->ip_addr->ai_addrlen);
- if(senddata != (ssize_t)sbytes) {
+
+ /* the typecase for the 3rd argument is mostly for systems that do
+ not have a size_t argument, like older unixes that want an 'int' */
+ senddata = sendto(state->sockfd, (void *)state->spacket.data,
+ (SEND_TYPE_ARG3)sbytes, 0,
+ state->conn->ip_addr->ai_addr,
+ state->conn->ip_addr->ai_addrlen);
+ if(senddata != (ssize_t)sbytes) {
char buffer[STRERROR_LEN];
failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- }
+ }
free(filename);
- break;
-
- case TFTP_EVENT_OACK:
- if(data->set.upload) {
+ break;
+
+ case TFTP_EVENT_OACK:
+ if(data->set.upload) {
result = tftp_connect_for_tx(state, event);
- }
- else {
+ }
+ else {
result = tftp_connect_for_rx(state, event);
- }
- break;
-
- case TFTP_EVENT_ACK: /* Connected for transmit */
+ }
+ break;
+
+ case TFTP_EVENT_ACK: /* Connected for transmit */
result = tftp_connect_for_tx(state, event);
- break;
-
- case TFTP_EVENT_DATA: /* Connected for receive */
+ break;
+
+ case TFTP_EVENT_DATA: /* Connected for receive */
result = tftp_connect_for_rx(state, event);
- break;
-
- case TFTP_EVENT_ERROR:
- state->state = TFTP_STATE_FIN;
- break;
-
- default:
- failf(state->conn->data, "tftp_send_first: internal error");
- break;
- }
+ break;
+
+ case TFTP_EVENT_ERROR:
+ state->state = TFTP_STATE_FIN;
+ break;
+
+ default:
+ failf(state->conn->data, "tftp_send_first: internal error");
+ break;
+ }
return result;
-}
-
-/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
- boundary */
+}
+
+/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
+ boundary */
#define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
-
-/**********************************************************
- *
- * tftp_rx
- *
- * Event handler for the RX state
- *
- **********************************************************/
+
+/**********************************************************
+ *
+ * tftp_rx
+ *
+ * Event handler for the RX state
+ *
+ **********************************************************/
static CURLcode tftp_rx(struct tftp_state_data *state,
tftp_event_t event)
-{
- ssize_t sbytes;
- int rblock;
+{
+ ssize_t sbytes;
+ int rblock;
struct Curl_easy *data = state->conn->data;
char buffer[STRERROR_LEN];
-
- switch(event) {
-
- case TFTP_EVENT_DATA:
- /* Is this the block we expect? */
- rblock = getrpacketblock(&state->rpacket);
- if(NEXT_BLOCKNUM(state->block) == rblock) {
- /* This is the expected block. Reset counters and ACK it. */
- state->retries = 0;
- }
- else if(state->block == rblock) {
- /* This is the last recently received block again. Log it and ACK it
- again. */
- infof(data, "Received last DATA packet block %d again.\n", rblock);
- }
- else {
- /* totally unexpected, just log it */
- infof(data,
- "Received unexpected DATA packet block %d, expecting block %d\n",
- rblock, NEXT_BLOCKNUM(state->block));
- break;
- }
-
- /* ACK this block. */
- state->block = (unsigned short)rblock;
- setpacketevent(&state->spacket, TFTP_EVENT_ACK);
- setpacketblock(&state->spacket, state->block);
- sbytes = sendto(state->sockfd, (void *)state->spacket.data,
- 4, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- if(sbytes < 0) {
+
+ switch(event) {
+
+ case TFTP_EVENT_DATA:
+ /* Is this the block we expect? */
+ rblock = getrpacketblock(&state->rpacket);
+ if(NEXT_BLOCKNUM(state->block) == rblock) {
+ /* This is the expected block. Reset counters and ACK it. */
+ state->retries = 0;
+ }
+ else if(state->block == rblock) {
+ /* This is the last recently received block again. Log it and ACK it
+ again. */
+ infof(data, "Received last DATA packet block %d again.\n", rblock);
+ }
+ else {
+ /* totally unexpected, just log it */
+ infof(data,
+ "Received unexpected DATA packet block %d, expecting block %d\n",
+ rblock, NEXT_BLOCKNUM(state->block));
+ break;
+ }
+
+ /* ACK this block. */
+ state->block = (unsigned short)rblock;
+ setpacketevent(&state->spacket, TFTP_EVENT_ACK);
+ setpacketblock(&state->spacket, state->block);
+ sbytes = sendto(state->sockfd, (void *)state->spacket.data,
+ 4, SEND_4TH_ARG,
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ if(sbytes < 0) {
failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- return CURLE_SEND_ERROR;
- }
-
- /* Check if completed (That is, a less than full packet is received) */
+ return CURLE_SEND_ERROR;
+ }
+
+ /* Check if completed (That is, a less than full packet is received) */
if(state->rbytes < (ssize_t)state->blksize + 4) {
- state->state = TFTP_STATE_FIN;
- }
- else {
- state->state = TFTP_STATE_RX;
- }
- time(&state->rx_time);
- break;
-
- case TFTP_EVENT_OACK:
- /* ACK option acknowledgement so we can move on to data */
- state->block = 0;
- state->retries = 0;
- setpacketevent(&state->spacket, TFTP_EVENT_ACK);
- setpacketblock(&state->spacket, state->block);
- sbytes = sendto(state->sockfd, (void *)state->spacket.data,
- 4, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- if(sbytes < 0) {
+ state->state = TFTP_STATE_FIN;
+ }
+ else {
+ state->state = TFTP_STATE_RX;
+ }
+ time(&state->rx_time);
+ break;
+
+ case TFTP_EVENT_OACK:
+ /* ACK option acknowledgement so we can move on to data */
+ state->block = 0;
+ state->retries = 0;
+ setpacketevent(&state->spacket, TFTP_EVENT_ACK);
+ setpacketblock(&state->spacket, state->block);
+ sbytes = sendto(state->sockfd, (void *)state->spacket.data,
+ 4, SEND_4TH_ARG,
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ if(sbytes < 0) {
failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- return CURLE_SEND_ERROR;
- }
-
- /* we're ready to RX data */
- state->state = TFTP_STATE_RX;
- time(&state->rx_time);
- break;
-
- case TFTP_EVENT_TIMEOUT:
- /* Increment the retry count and fail if over the limit */
- state->retries++;
- infof(data,
- "Timeout waiting for block %d ACK. Retries = %d\n",
- NEXT_BLOCKNUM(state->block), state->retries);
- if(state->retries > state->retry_max) {
- state->error = TFTP_ERR_TIMEOUT;
- state->state = TFTP_STATE_FIN;
- }
- else {
- /* Resend the previous ACK */
- sbytes = sendto(state->sockfd, (void *)state->spacket.data,
- 4, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- if(sbytes<0) {
+ return CURLE_SEND_ERROR;
+ }
+
+ /* we're ready to RX data */
+ state->state = TFTP_STATE_RX;
+ time(&state->rx_time);
+ break;
+
+ case TFTP_EVENT_TIMEOUT:
+ /* Increment the retry count and fail if over the limit */
+ state->retries++;
+ infof(data,
+ "Timeout waiting for block %d ACK. Retries = %d\n",
+ NEXT_BLOCKNUM(state->block), state->retries);
+ if(state->retries > state->retry_max) {
+ state->error = TFTP_ERR_TIMEOUT;
+ state->state = TFTP_STATE_FIN;
+ }
+ else {
+ /* Resend the previous ACK */
+ sbytes = sendto(state->sockfd, (void *)state->spacket.data,
+ 4, SEND_4TH_ARG,
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ if(sbytes<0) {
failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- return CURLE_SEND_ERROR;
- }
- }
- break;
-
- case TFTP_EVENT_ERROR:
- setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
- setpacketblock(&state->spacket, state->block);
- (void)sendto(state->sockfd, (void *)state->spacket.data,
- 4, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- /* don't bother with the return code, but if the socket is still up we
- * should be a good TFTP client and let the server know we're done */
- state->state = TFTP_STATE_FIN;
- break;
-
- default:
- failf(data, "%s", "tftp_rx: internal error");
- return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
- this */
- }
- return CURLE_OK;
-}
-
-/**********************************************************
- *
- * tftp_tx
- *
- * Event handler for the TX state
- *
- **********************************************************/
+ return CURLE_SEND_ERROR;
+ }
+ }
+ break;
+
+ case TFTP_EVENT_ERROR:
+ setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
+ setpacketblock(&state->spacket, state->block);
+ (void)sendto(state->sockfd, (void *)state->spacket.data,
+ 4, SEND_4TH_ARG,
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ /* don't bother with the return code, but if the socket is still up we
+ * should be a good TFTP client and let the server know we're done */
+ state->state = TFTP_STATE_FIN;
+ break;
+
+ default:
+ failf(data, "%s", "tftp_rx: internal error");
+ return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
+ this */
+ }
+ return CURLE_OK;
+}
+
+/**********************************************************
+ *
+ * tftp_tx
+ *
+ * Event handler for the TX state
+ *
+ **********************************************************/
static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event)
-{
+{
struct Curl_easy *data = state->conn->data;
- ssize_t sbytes;
+ ssize_t sbytes;
CURLcode result = CURLE_OK;
- struct SingleRequest *k = &data->req;
+ struct SingleRequest *k = &data->req;
size_t cb; /* Bytes currently read */
char buffer[STRERROR_LEN];
-
- switch(event) {
-
- case TFTP_EVENT_ACK:
- case TFTP_EVENT_OACK:
- if(event == TFTP_EVENT_ACK) {
- /* Ack the packet */
+
+ switch(event) {
+
+ case TFTP_EVENT_ACK:
+ case TFTP_EVENT_OACK:
+ if(event == TFTP_EVENT_ACK) {
+ /* Ack the packet */
int rblock = getrpacketblock(&state->rpacket);
-
- if(rblock != state->block &&
- /* There's a bug in tftpd-hpa that causes it to send us an ack for
- * 65535 when the block number wraps to 0. So when we're expecting
- * 0, also accept 65535. See
- * http://syslinux.zytor.com/archives/2010-September/015253.html
- * */
- !(state->block == 0 && rblock == 65535)) {
- /* This isn't the expected block. Log it and up the retry counter */
- infof(data, "Received ACK for block %d, expecting %d\n",
- rblock, state->block);
- state->retries++;
- /* Bail out if over the maximum */
- if(state->retries>state->retry_max) {
- failf(data, "tftp_tx: giving up waiting for block %d ack",
- state->block);
+
+ if(rblock != state->block &&
+ /* There's a bug in tftpd-hpa that causes it to send us an ack for
+ * 65535 when the block number wraps to 0. So when we're expecting
+ * 0, also accept 65535. See
+ * http://syslinux.zytor.com/archives/2010-September/015253.html
+ * */
+ !(state->block == 0 && rblock == 65535)) {
+ /* This isn't the expected block. Log it and up the retry counter */
+ infof(data, "Received ACK for block %d, expecting %d\n",
+ rblock, state->block);
+ state->retries++;
+ /* Bail out if over the maximum */
+ if(state->retries>state->retry_max) {
+ failf(data, "tftp_tx: giving up waiting for block %d ack",
+ state->block);
result = CURLE_SEND_ERROR;
- }
- else {
- /* Re-send the data packet */
- sbytes = sendto(state->sockfd, (void *)state->spacket.data,
+ }
+ else {
+ /* Re-send the data packet */
+ sbytes = sendto(state->sockfd, (void *)state->spacket.data,
4 + state->sbytes, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- /* Check all sbytes were sent */
- if(sbytes<0) {
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ /* Check all sbytes were sent */
+ if(sbytes<0) {
failf(data, "%s", Curl_strerror(SOCKERRNO,
buffer, sizeof(buffer)));
result = CURLE_SEND_ERROR;
- }
- }
+ }
+ }
return result;
- }
- /* This is the expected packet. Reset the counters and send the next
- block */
- time(&state->rx_time);
- state->block++;
- }
- else
- state->block = 1; /* first data block is 1 when using OACK */
-
- state->retries = 0;
- setpacketevent(&state->spacket, TFTP_EVENT_DATA);
- setpacketblock(&state->spacket, state->block);
+ }
+ /* This is the expected packet. Reset the counters and send the next
+ block */
+ time(&state->rx_time);
+ state->block++;
+ }
+ else
+ state->block = 1; /* first data block is 1 when using OACK */
+
+ state->retries = 0;
+ setpacketevent(&state->spacket, TFTP_EVENT_DATA);
+ setpacketblock(&state->spacket, state->block);
if(state->block > 1 && state->sbytes < state->blksize) {
- state->state = TFTP_STATE_FIN;
- return CURLE_OK;
- }
+ state->state = TFTP_STATE_FIN;
+ return CURLE_OK;
+ }
/* TFTP considers data block size < 512 bytes as an end of session. So
* in some cases we must wait for additional data to build full (512 bytes)
@@ -806,366 +806,366 @@ static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event)
sbytes = sendto(state->sockfd, (void *) state->spacket.data,
4 + state->sbytes, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- /* Check all sbytes were sent */
- if(sbytes<0) {
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ /* Check all sbytes were sent */
+ if(sbytes<0) {
failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- return CURLE_SEND_ERROR;
- }
- /* Update the progress meter */
- k->writebytecount += state->sbytes;
- Curl_pgrsSetUploadCounter(data, k->writebytecount);
- break;
-
- case TFTP_EVENT_TIMEOUT:
- /* Increment the retry counter and log the timeout */
- state->retries++;
- infof(data, "Timeout waiting for block %d ACK. "
- " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
- /* Decide if we've had enough */
- if(state->retries > state->retry_max) {
- state->error = TFTP_ERR_TIMEOUT;
- state->state = TFTP_STATE_FIN;
- }
- else {
- /* Re-send the data packet */
- sbytes = sendto(state->sockfd, (void *)state->spacket.data,
+ return CURLE_SEND_ERROR;
+ }
+ /* Update the progress meter */
+ k->writebytecount += state->sbytes;
+ Curl_pgrsSetUploadCounter(data, k->writebytecount);
+ break;
+
+ case TFTP_EVENT_TIMEOUT:
+ /* Increment the retry counter and log the timeout */
+ state->retries++;
+ infof(data, "Timeout waiting for block %d ACK. "
+ " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
+ /* Decide if we've had enough */
+ if(state->retries > state->retry_max) {
+ state->error = TFTP_ERR_TIMEOUT;
+ state->state = TFTP_STATE_FIN;
+ }
+ else {
+ /* Re-send the data packet */
+ sbytes = sendto(state->sockfd, (void *)state->spacket.data,
4 + state->sbytes, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- /* Check all sbytes were sent */
- if(sbytes<0) {
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ /* Check all sbytes were sent */
+ if(sbytes<0) {
failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- return CURLE_SEND_ERROR;
- }
- /* since this was a re-send, we remain at the still byte position */
- Curl_pgrsSetUploadCounter(data, k->writebytecount);
- }
- break;
-
- case TFTP_EVENT_ERROR:
- state->state = TFTP_STATE_FIN;
- setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
- setpacketblock(&state->spacket, state->block);
- (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
- (struct sockaddr *)&state->remote_addr,
- state->remote_addrlen);
- /* don't bother with the return code, but if the socket is still up we
- * should be a good TFTP client and let the server know we're done */
- state->state = TFTP_STATE_FIN;
- break;
-
- default:
- failf(data, "tftp_tx: internal error, event: %i", (int)(event));
- break;
- }
-
+ return CURLE_SEND_ERROR;
+ }
+ /* since this was a re-send, we remain at the still byte position */
+ Curl_pgrsSetUploadCounter(data, k->writebytecount);
+ }
+ break;
+
+ case TFTP_EVENT_ERROR:
+ state->state = TFTP_STATE_FIN;
+ setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
+ setpacketblock(&state->spacket, state->block);
+ (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
+ (struct sockaddr *)&state->remote_addr,
+ state->remote_addrlen);
+ /* don't bother with the return code, but if the socket is still up we
+ * should be a good TFTP client and let the server know we're done */
+ state->state = TFTP_STATE_FIN;
+ break;
+
+ default:
+ failf(data, "tftp_tx: internal error, event: %i", (int)(event));
+ break;
+ }
+
return result;
-}
-
-/**********************************************************
- *
- * tftp_translate_code
- *
- * Translate internal error codes to CURL error codes
- *
- **********************************************************/
-static CURLcode tftp_translate_code(tftp_error_t error)
-{
+}
+
+/**********************************************************
+ *
+ * tftp_translate_code
+ *
+ * Translate internal error codes to CURL error codes
+ *
+ **********************************************************/
+static CURLcode tftp_translate_code(tftp_error_t error)
+{
CURLcode result = CURLE_OK;
-
- if(error != TFTP_ERR_NONE) {
- switch(error) {
- case TFTP_ERR_NOTFOUND:
+
+ if(error != TFTP_ERR_NONE) {
+ switch(error) {
+ case TFTP_ERR_NOTFOUND:
result = CURLE_TFTP_NOTFOUND;
- break;
- case TFTP_ERR_PERM:
+ break;
+ case TFTP_ERR_PERM:
result = CURLE_TFTP_PERM;
- break;
- case TFTP_ERR_DISKFULL:
+ break;
+ case TFTP_ERR_DISKFULL:
result = CURLE_REMOTE_DISK_FULL;
- break;
- case TFTP_ERR_UNDEF:
- case TFTP_ERR_ILLEGAL:
+ break;
+ case TFTP_ERR_UNDEF:
+ case TFTP_ERR_ILLEGAL:
result = CURLE_TFTP_ILLEGAL;
- break;
- case TFTP_ERR_UNKNOWNID:
+ break;
+ case TFTP_ERR_UNKNOWNID:
result = CURLE_TFTP_UNKNOWNID;
- break;
- case TFTP_ERR_EXISTS:
+ break;
+ case TFTP_ERR_EXISTS:
result = CURLE_REMOTE_FILE_EXISTS;
- break;
- case TFTP_ERR_NOSUCHUSER:
+ break;
+ case TFTP_ERR_NOSUCHUSER:
result = CURLE_TFTP_NOSUCHUSER;
- break;
- case TFTP_ERR_TIMEOUT:
+ break;
+ case TFTP_ERR_TIMEOUT:
result = CURLE_OPERATION_TIMEDOUT;
- break;
- case TFTP_ERR_NORESPONSE:
+ break;
+ case TFTP_ERR_NORESPONSE:
result = CURLE_COULDNT_CONNECT;
- break;
- default:
+ break;
+ default:
result = CURLE_ABORTED_BY_CALLBACK;
- break;
- }
- }
+ break;
+ }
+ }
else
result = CURLE_OK;
-
+
return result;
-}
-
-/**********************************************************
- *
- * tftp_state_machine
- *
- * The tftp state machine event dispatcher
- *
- **********************************************************/
+}
+
+/**********************************************************
+ *
+ * tftp_state_machine
+ *
+ * The tftp state machine event dispatcher
+ *
+ **********************************************************/
static CURLcode tftp_state_machine(struct tftp_state_data *state,
- tftp_event_t event)
-{
+ tftp_event_t event)
+{
CURLcode result = CURLE_OK;
struct Curl_easy *data = state->conn->data;
- switch(state->state) {
- case TFTP_STATE_START:
- DEBUGF(infof(data, "TFTP_STATE_START\n"));
+ switch(state->state) {
+ case TFTP_STATE_START:
+ DEBUGF(infof(data, "TFTP_STATE_START\n"));
result = tftp_send_first(state, event);
- break;
- case TFTP_STATE_RX:
- DEBUGF(infof(data, "TFTP_STATE_RX\n"));
+ break;
+ case TFTP_STATE_RX:
+ DEBUGF(infof(data, "TFTP_STATE_RX\n"));
result = tftp_rx(state, event);
- break;
- case TFTP_STATE_TX:
- DEBUGF(infof(data, "TFTP_STATE_TX\n"));
+ break;
+ case TFTP_STATE_TX:
+ DEBUGF(infof(data, "TFTP_STATE_TX\n"));
result = tftp_tx(state, event);
- break;
- case TFTP_STATE_FIN:
- infof(data, "%s\n", "TFTP finished");
- break;
- default:
- DEBUGF(infof(data, "STATE: %d\n", state->state));
- failf(data, "%s", "Internal state machine error");
+ break;
+ case TFTP_STATE_FIN:
+ infof(data, "%s\n", "TFTP finished");
+ break;
+ default:
+ DEBUGF(infof(data, "STATE: %d\n", state->state));
+ failf(data, "%s", "Internal state machine error");
result = CURLE_TFTP_ILLEGAL;
- break;
- }
+ break;
+ }
return result;
-}
-
-/**********************************************************
- *
- * tftp_disconnect
- *
- * The disconnect callback
- *
- **********************************************************/
-static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
-{
+}
+
+/**********************************************************
+ *
+ * tftp_disconnect
+ *
+ * The disconnect callback
+ *
+ **********************************************************/
+static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
+{
struct tftp_state_data *state = conn->proto.tftpc;
- (void) dead_connection;
-
- /* done, free dynamically allocated pkt buffers */
- if(state) {
- Curl_safefree(state->rpacket.data);
- Curl_safefree(state->spacket.data);
- free(state);
- }
-
- return CURLE_OK;
-}
-
-/**********************************************************
- *
- * tftp_connect
- *
- * The connect callback
- *
- **********************************************************/
-static CURLcode tftp_connect(struct connectdata *conn, bool *done)
-{
+ (void) dead_connection;
+
+ /* done, free dynamically allocated pkt buffers */
+ if(state) {
+ Curl_safefree(state->rpacket.data);
+ Curl_safefree(state->spacket.data);
+ free(state);
+ }
+
+ return CURLE_OK;
+}
+
+/**********************************************************
+ *
+ * tftp_connect
+ *
+ * The connect callback
+ *
+ **********************************************************/
+static CURLcode tftp_connect(struct connectdata *conn, bool *done)
+{
struct tftp_state_data *state;
int blksize;
int need_blksize;
-
- blksize = TFTP_BLKSIZE_DEFAULT;
-
+
+ blksize = TFTP_BLKSIZE_DEFAULT;
+
state = conn->proto.tftpc = calloc(1, sizeof(struct tftp_state_data));
- if(!state)
- return CURLE_OUT_OF_MEMORY;
-
- /* alloc pkt buffers based on specified blksize */
- if(conn->data->set.tftp_blksize) {
- blksize = (int)conn->data->set.tftp_blksize;
+ if(!state)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* alloc pkt buffers based on specified blksize */
+ if(conn->data->set.tftp_blksize) {
+ blksize = (int)conn->data->set.tftp_blksize;
if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN)
- return CURLE_TFTP_ILLEGAL;
- }
-
+ return CURLE_TFTP_ILLEGAL;
+ }
+
need_blksize = blksize;
/* default size is the fallback when no OACK is received */
if(need_blksize < TFTP_BLKSIZE_DEFAULT)
need_blksize = TFTP_BLKSIZE_DEFAULT;
- if(!state->rpacket.data) {
+ if(!state->rpacket.data) {
state->rpacket.data = calloc(1, need_blksize + 2 + 2);
-
- if(!state->rpacket.data)
- return CURLE_OUT_OF_MEMORY;
- }
-
- if(!state->spacket.data) {
+
+ if(!state->rpacket.data)
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ if(!state->spacket.data) {
state->spacket.data = calloc(1, need_blksize + 2 + 2);
-
- if(!state->spacket.data)
- return CURLE_OUT_OF_MEMORY;
- }
-
+
+ if(!state->spacket.data)
+ return CURLE_OUT_OF_MEMORY;
+ }
+
/* we don't keep TFTP connections up basically because there's none or very
* little gain for UDP */
connclose(conn, "TFTP");
-
- state->conn = conn;
- state->sockfd = state->conn->sock[FIRSTSOCKET];
- state->state = TFTP_STATE_START;
- state->error = TFTP_ERR_NONE;
+
+ state->conn = conn;
+ state->sockfd = state->conn->sock[FIRSTSOCKET];
+ state->state = TFTP_STATE_START;
+ state->error = TFTP_ERR_NONE;
state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */
- state->requested_blksize = blksize;
-
- ((struct sockaddr *)&state->local_addr)->sa_family =
+ state->requested_blksize = blksize;
+
+ ((struct sockaddr *)&state->local_addr)->sa_family =
(CURL_SA_FAMILY_T)(conn->ip_addr->ai_family);
-
- tftp_set_timeouts(state);
-
- if(!conn->bits.bound) {
- /* If not already bound, bind to any interface, random UDP port. If it is
- * reused or a custom local port was desired, this has already been done!
- *
- * We once used the size of the local_addr struct as the third argument
- * for bind() to better work with IPv6 or whatever size the struct could
- * have, but we learned that at least Tru64, AIX and IRIX *requires* the
- * size of that argument to match the exact size of a 'sockaddr_in' struct
- * when running IPv4-only.
- *
- * Therefore we use the size from the address we connected to, which we
- * assume uses the same IP version and thus hopefully this works for both
- * IPv4 and IPv6...
- */
+
+ tftp_set_timeouts(state);
+
+ if(!conn->bits.bound) {
+ /* If not already bound, bind to any interface, random UDP port. If it is
+ * reused or a custom local port was desired, this has already been done!
+ *
+ * We once used the size of the local_addr struct as the third argument
+ * for bind() to better work with IPv6 or whatever size the struct could
+ * have, but we learned that at least Tru64, AIX and IRIX *requires* the
+ * size of that argument to match the exact size of a 'sockaddr_in' struct
+ * when running IPv4-only.
+ *
+ * Therefore we use the size from the address we connected to, which we
+ * assume uses the same IP version and thus hopefully this works for both
+ * IPv4 and IPv6...
+ */
int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
conn->ip_addr->ai_addrlen);
- if(rc) {
+ if(rc) {
char buffer[STRERROR_LEN];
- failf(conn->data, "bind() failed; %s",
+ failf(conn->data, "bind() failed; %s",
Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
- return CURLE_COULDNT_CONNECT;
- }
- conn->bits.bound = TRUE;
- }
-
- Curl_pgrsStartNow(conn->data);
-
- *done = TRUE;
+ return CURLE_COULDNT_CONNECT;
+ }
+ conn->bits.bound = TRUE;
+ }
+
+ Curl_pgrsStartNow(conn->data);
+
+ *done = TRUE;
return CURLE_OK;
-}
-
-/**********************************************************
- *
- * tftp_done
- *
- * The done callback
- *
- **********************************************************/
-static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
- bool premature)
-{
+}
+
+/**********************************************************
+ *
+ * tftp_done
+ *
+ * The done callback
+ *
+ **********************************************************/
+static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
CURLcode result = CURLE_OK;
struct tftp_state_data *state = conn->proto.tftpc;
-
- (void)status; /* unused */
- (void)premature; /* not used */
-
- if(Curl_pgrsDone(conn))
- return CURLE_ABORTED_BY_CALLBACK;
-
- /* If we have encountered an error */
+
+ (void)status; /* unused */
+ (void)premature; /* not used */
+
+ if(Curl_pgrsDone(conn))
+ return CURLE_ABORTED_BY_CALLBACK;
+
+ /* If we have encountered an error */
if(state)
result = tftp_translate_code(state->error);
-
+
return result;
-}
-
-/**********************************************************
- *
- * tftp_getsock
- *
- * The getsock callback
- *
- **********************************************************/
+}
+
+/**********************************************************
+ *
+ * tftp_getsock
+ *
+ * The getsock callback
+ *
+ **********************************************************/
static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks)
-{
- socks[0] = conn->sock[FIRSTSOCKET];
- return GETSOCK_READSOCK(0);
-}
-
-/**********************************************************
- *
- * tftp_receive_packet
- *
- * Called once select fires and data is ready on the socket
- *
- **********************************************************/
-static CURLcode tftp_receive_packet(struct connectdata *conn)
-{
- struct Curl_sockaddr_storage fromaddr;
- curl_socklen_t fromlen;
- CURLcode result = CURLE_OK;
+{
+ socks[0] = conn->sock[FIRSTSOCKET];
+ return GETSOCK_READSOCK(0);
+}
+
+/**********************************************************
+ *
+ * tftp_receive_packet
+ *
+ * Called once select fires and data is ready on the socket
+ *
+ **********************************************************/
+static CURLcode tftp_receive_packet(struct connectdata *conn)
+{
+ struct Curl_sockaddr_storage fromaddr;
+ curl_socklen_t fromlen;
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct tftp_state_data *state = conn->proto.tftpc;
- struct SingleRequest *k = &data->req;
-
- /* Receive the packet */
- fromlen = sizeof(fromaddr);
- state->rbytes = (int)recvfrom(state->sockfd,
- (void *)state->rpacket.data,
+ struct SingleRequest *k = &data->req;
+
+ /* Receive the packet */
+ fromlen = sizeof(fromaddr);
+ state->rbytes = (int)recvfrom(state->sockfd,
+ (void *)state->rpacket.data,
state->blksize + 4,
- 0,
- (struct sockaddr *)&fromaddr,
- &fromlen);
+ 0,
+ (struct sockaddr *)&fromaddr,
+ &fromlen);
if(state->remote_addrlen == 0) {
- memcpy(&state->remote_addr, &fromaddr, fromlen);
- state->remote_addrlen = fromlen;
- }
-
- /* Sanity check packet length */
- if(state->rbytes < 4) {
- failf(data, "Received too short packet");
- /* Not a timeout, but how best to handle it? */
- state->event = TFTP_EVENT_TIMEOUT;
- }
- else {
- /* The event is given by the TFTP packet time */
+ memcpy(&state->remote_addr, &fromaddr, fromlen);
+ state->remote_addrlen = fromlen;
+ }
+
+ /* Sanity check packet length */
+ if(state->rbytes < 4) {
+ failf(data, "Received too short packet");
+ /* Not a timeout, but how best to handle it? */
+ state->event = TFTP_EVENT_TIMEOUT;
+ }
+ else {
+ /* The event is given by the TFTP packet time */
unsigned short event = getrpacketevent(&state->rpacket);
state->event = (tftp_event_t)event;
-
- switch(state->event) {
- case TFTP_EVENT_DATA:
- /* Don't pass to the client empty or retransmitted packets */
- if(state->rbytes > 4 &&
- (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
- result = Curl_client_write(conn, CLIENTWRITE_BODY,
+
+ switch(state->event) {
+ case TFTP_EVENT_DATA:
+ /* Don't pass to the client empty or retransmitted packets */
+ if(state->rbytes > 4 &&
+ (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
+ result = Curl_client_write(conn, CLIENTWRITE_BODY,
(char *)state->rpacket.data + 4,
- state->rbytes-4);
- if(result) {
- tftp_state_machine(state, TFTP_EVENT_ERROR);
- return result;
- }
- k->bytecount += state->rbytes-4;
- Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
- }
- break;
- case TFTP_EVENT_ERROR:
+ state->rbytes-4);
+ if(result) {
+ tftp_state_machine(state, TFTP_EVENT_ERROR);
+ return result;
+ }
+ k->bytecount += state->rbytes-4;
+ Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
+ }
+ break;
+ case TFTP_EVENT_ERROR:
{
unsigned short error = getrpacketblock(&state->rpacket);
char *str = (char *)state->rpacket.data + 4;
@@ -1173,254 +1173,254 @@ static CURLcode tftp_receive_packet(struct connectdata *conn)
state->error = (tftp_error_t)error;
if(Curl_strnlen(str, strn) < strn)
infof(data, "TFTP error: %s\n", str);
- break;
+ break;
}
- case TFTP_EVENT_ACK:
- break;
- case TFTP_EVENT_OACK:
- result = tftp_parse_option_ack(state,
+ case TFTP_EVENT_ACK:
+ break;
+ case TFTP_EVENT_OACK:
+ result = tftp_parse_option_ack(state,
(const char *)state->rpacket.data + 2,
- state->rbytes-2);
- if(result)
- return result;
- break;
- case TFTP_EVENT_RRQ:
- case TFTP_EVENT_WRQ:
- default:
- failf(data, "%s", "Internal error: Unexpected packet");
- break;
- }
-
- /* Update the progress meter */
- if(Curl_pgrsUpdate(conn)) {
- tftp_state_machine(state, TFTP_EVENT_ERROR);
- return CURLE_ABORTED_BY_CALLBACK;
- }
- }
- return result;
-}
-
-/**********************************************************
- *
- * tftp_state_timeout
- *
- * Check if timeouts have been reached
- *
- **********************************************************/
-static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
-{
+ state->rbytes-2);
+ if(result)
+ return result;
+ break;
+ case TFTP_EVENT_RRQ:
+ case TFTP_EVENT_WRQ:
+ default:
+ failf(data, "%s", "Internal error: Unexpected packet");
+ break;
+ }
+
+ /* Update the progress meter */
+ if(Curl_pgrsUpdate(conn)) {
+ tftp_state_machine(state, TFTP_EVENT_ERROR);
+ return CURLE_ABORTED_BY_CALLBACK;
+ }
+ }
+ return result;
+}
+
+/**********************************************************
+ *
+ * tftp_state_timeout
+ *
+ * Check if timeouts have been reached
+ *
+ **********************************************************/
+static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
+{
time_t current;
struct tftp_state_data *state = conn->proto.tftpc;
-
- if(event)
- *event = TFTP_EVENT_NONE;
-
- time(&current);
- if(current > state->max_time) {
- DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
- (long)current, (long)state->max_time));
- state->error = TFTP_ERR_TIMEOUT;
- state->state = TFTP_STATE_FIN;
- return 0;
- }
+
+ if(event)
+ *event = TFTP_EVENT_NONE;
+
+ time(&current);
+ if(current > state->max_time) {
+ DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
+ (long)current, (long)state->max_time));
+ state->error = TFTP_ERR_TIMEOUT;
+ state->state = TFTP_STATE_FIN;
+ return 0;
+ }
if(current > state->rx_time + state->retry_time) {
- if(event)
- *event = TFTP_EVENT_TIMEOUT;
- time(&state->rx_time); /* update even though we received nothing */
- }
-
- /* there's a typecast below here since 'time_t' may in fact be larger than
- 'long', but we estimate that a 'long' will still be able to hold number
- of seconds even if "only" 32 bit */
- return (long)(state->max_time - current);
-}
-
-/**********************************************************
- *
- * tftp_multi_statemach
- *
- * Handle single RX socket event and return
- *
- **********************************************************/
-static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
-{
- tftp_event_t event;
- CURLcode result = CURLE_OK;
+ if(event)
+ *event = TFTP_EVENT_TIMEOUT;
+ time(&state->rx_time); /* update even though we received nothing */
+ }
+
+ /* there's a typecast below here since 'time_t' may in fact be larger than
+ 'long', but we estimate that a 'long' will still be able to hold number
+ of seconds even if "only" 32 bit */
+ return (long)(state->max_time - current);
+}
+
+/**********************************************************
+ *
+ * tftp_multi_statemach
+ *
+ * Handle single RX socket event and return
+ *
+ **********************************************************/
+static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
+{
+ tftp_event_t event;
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct tftp_state_data *state = conn->proto.tftpc;
- long timeout_ms = tftp_state_timeout(conn, &event);
-
- *done = FALSE;
-
- if(timeout_ms <= 0) {
- failf(data, "TFTP response timeout");
- return CURLE_OPERATION_TIMEDOUT;
- }
+ long timeout_ms = tftp_state_timeout(conn, &event);
+
+ *done = FALSE;
+
+ if(timeout_ms <= 0) {
+ failf(data, "TFTP response timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
if(event != TFTP_EVENT_NONE) {
- result = tftp_state_machine(state, event);
+ result = tftp_state_machine(state, event);
if(result)
return result;
- *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
- if(*done)
- /* Tell curl we're done */
+ *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
+ if(*done)
+ /* Tell curl we're done */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
- }
- else {
- /* no timeouts to handle, check our socket */
+ }
+ else {
+ /* no timeouts to handle, check our socket */
int rc = SOCKET_READABLE(state->sockfd, 0);
-
- if(rc == -1) {
- /* bail out */
- int error = SOCKERRNO;
+
+ if(rc == -1) {
+ /* bail out */
+ int error = SOCKERRNO;
char buffer[STRERROR_LEN];
failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer)));
- state->event = TFTP_EVENT_ERROR;
- }
- else if(rc != 0) {
- result = tftp_receive_packet(conn);
+ state->event = TFTP_EVENT_ERROR;
+ }
+ else if(rc != 0) {
+ result = tftp_receive_packet(conn);
if(result)
return result;
- result = tftp_state_machine(state, state->event);
+ result = tftp_state_machine(state, state->event);
if(result)
return result;
- *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
- if(*done)
- /* Tell curl we're done */
+ *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
+ if(*done)
+ /* Tell curl we're done */
Curl_setup_transfer(data, -1, -1, FALSE, -1);
- }
- /* if rc == 0, then select() timed out */
- }
-
- return result;
-}
-
-/**********************************************************
- *
- * tftp_doing
- *
- * Called from multi.c while DOing
- *
- **********************************************************/
-static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
-{
- CURLcode result;
- result = tftp_multi_statemach(conn, dophase_done);
-
- if(*dophase_done) {
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
- }
+ }
+ /* if rc == 0, then select() timed out */
+ }
+
+ return result;
+}
+
+/**********************************************************
+ *
+ * tftp_doing
+ *
+ * Called from multi.c while DOing
+ *
+ **********************************************************/
+static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
+{
+ CURLcode result;
+ result = tftp_multi_statemach(conn, dophase_done);
+
+ if(*dophase_done) {
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
else if(!result) {
- /* The multi code doesn't have this logic for the DOING state so we
- provide it for TFTP since it may do the entire transfer in this
- state. */
- if(Curl_pgrsUpdate(conn))
- result = CURLE_ABORTED_BY_CALLBACK;
- else
+ /* The multi code doesn't have this logic for the DOING state so we
+ provide it for TFTP since it may do the entire transfer in this
+ state. */
+ if(Curl_pgrsUpdate(conn))
+ result = CURLE_ABORTED_BY_CALLBACK;
+ else
result = Curl_speedcheck(conn->data, Curl_now());
- }
- return result;
-}
-
-/**********************************************************
- *
- * tftp_peform
- *
- * Entry point for transfer from tftp_do, sarts state mach
- *
- **********************************************************/
-static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
-{
- CURLcode result = CURLE_OK;
+ }
+ return result;
+}
+
+/**********************************************************
+ *
+ * tftp_peform
+ *
+ * Entry point for transfer from tftp_do, sarts state mach
+ *
+ **********************************************************/
+static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
+{
+ CURLcode result = CURLE_OK;
struct tftp_state_data *state = conn->proto.tftpc;
-
- *dophase_done = FALSE;
-
- result = tftp_state_machine(state, TFTP_EVENT_INIT);
-
+
+ *dophase_done = FALSE;
+
+ result = tftp_state_machine(state, TFTP_EVENT_INIT);
+
if((state->state == TFTP_STATE_FIN) || result)
return result;
-
- tftp_multi_statemach(conn, dophase_done);
-
- if(*dophase_done)
- DEBUGF(infof(conn->data, "DO phase is complete\n"));
-
- return result;
-}
-
-
-/**********************************************************
- *
- * tftp_do
- *
- * The do callback
- *
- * This callback initiates the TFTP transfer
- *
- **********************************************************/
-
-static CURLcode tftp_do(struct connectdata *conn, bool *done)
-{
+
+ tftp_multi_statemach(conn, dophase_done);
+
+ if(*dophase_done)
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+
+ return result;
+}
+
+
+/**********************************************************
+ *
+ * tftp_do
+ *
+ * The do callback
+ *
+ * This callback initiates the TFTP transfer
+ *
+ **********************************************************/
+
+static CURLcode tftp_do(struct connectdata *conn, bool *done)
+{
struct tftp_state_data *state;
CURLcode result;
-
- *done = FALSE;
-
- if(!conn->proto.tftpc) {
+
+ *done = FALSE;
+
+ if(!conn->proto.tftpc) {
result = tftp_connect(conn, done);
if(result)
return result;
- }
+ }
state = conn->proto.tftpc;
if(!state)
return CURLE_TFTP_ILLEGAL;
-
+
result = tftp_perform(conn, done);
-
- /* If tftp_perform() returned an error, use that for return code. If it
- was OK, see if tftp_translate_code() has an error. */
+
+ /* If tftp_perform() returned an error, use that for return code. If it
+ was OK, see if tftp_translate_code() has an error. */
if(!result)
- /* If we have encountered an internal tftp error, translate it. */
+ /* If we have encountered an internal tftp error, translate it. */
result = tftp_translate_code(state->error);
-
+
return result;
-}
-
+}
+
static CURLcode tftp_setup_connection(struct connectdata *conn)
-{
+{
struct Curl_easy *data = conn->data;
char *type;
-
+
conn->transport = TRNSPRT_UDP;
-
- /* TFTP URLs support an extension like ";mode=<typecode>" that
- * we'll try to get now! */
+
+ /* TFTP URLs support an extension like ";mode=<typecode>" that
+ * we'll try to get now! */
type = strstr(data->state.up.path, ";mode=");
-
- if(!type)
- type = strstr(conn->host.rawalloc, ";mode=");
-
- if(type) {
+
+ if(!type)
+ type = strstr(conn->host.rawalloc, ";mode=");
+
+ if(type) {
char command;
- *type = 0; /* it was in the middle of the hostname */
- command = Curl_raw_toupper(type[6]);
-
+ *type = 0; /* it was in the middle of the hostname */
+ command = Curl_raw_toupper(type[6]);
+
switch(command) {
- case 'A': /* ASCII mode */
- case 'N': /* NETASCII mode */
- data->set.prefer_ascii = TRUE;
- break;
-
- case 'O': /* octet mode */
- case 'I': /* binary mode */
- default:
- /* switch off ASCII */
- data->set.prefer_ascii = FALSE;
- break;
- }
- }
-
- return CURLE_OK;
-}
-#endif
+ case 'A': /* ASCII mode */
+ case 'N': /* NETASCII mode */
+ data->set.prefer_ascii = TRUE;
+ break;
+
+ case 'O': /* octet mode */
+ case 'I': /* binary mode */
+ default:
+ /* switch off ASCII */
+ data->set.prefer_ascii = FALSE;
+ break;
+ }
+ }
+
+ return CURLE_OK;
+}
+#endif
diff --git a/contrib/libs/curl/lib/tftp.h b/contrib/libs/curl/lib/tftp.h
index 7eff2400e7..4b5bea2757 100644
--- a/contrib/libs/curl/lib/tftp.h
+++ b/contrib/libs/curl/lib/tftp.h
@@ -1,28 +1,28 @@
-#ifndef HEADER_CURL_TFTP_H
-#define HEADER_CURL_TFTP_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_TFTP_H
+#define HEADER_CURL_TFTP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#ifndef CURL_DISABLE_TFTP
-extern const struct Curl_handler Curl_handler_tftp;
-#endif
-
-#endif /* HEADER_CURL_TFTP_H */
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifndef CURL_DISABLE_TFTP
+extern const struct Curl_handler Curl_handler_tftp;
+#endif
+
+#endif /* HEADER_CURL_TFTP_H */
diff --git a/contrib/libs/curl/lib/timeval.c b/contrib/libs/curl/lib/timeval.c
index 6be8d14786..8523dad400 100644
--- a/contrib/libs/curl/lib/timeval.c
+++ b/contrib/libs/curl/lib/timeval.c
@@ -1,36 +1,36 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "timeval.h"
-
-#if defined(WIN32) && !defined(MSDOS)
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "timeval.h"
+
+#if defined(WIN32) && !defined(MSDOS)
+
/* set in win32_init() */
extern LARGE_INTEGER Curl_freq;
extern bool Curl_isVistaOrGreater;
/* In case of bug fix this function has a counterpart in tool_util.c */
struct curltime Curl_now(void)
-{
+{
struct curltime now;
if(Curl_isVistaOrGreater) { /* QPC timer might have issues pre-Vista */
LARGE_INTEGER count;
@@ -53,25 +53,25 @@ struct curltime Curl_now(void)
now.tv_sec = milliseconds / 1000;
now.tv_usec = (milliseconds % 1000) * 1000;
}
- return now;
-}
-
-#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
-
+ return now;
+}
+
+#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
+
struct curltime Curl_now(void)
-{
- /*
- ** clock_gettime() is granted to be increased monotonically when the
- ** monotonic clock is queried. Time starting point is unspecified, it
- ** could be the system start-up time, the Epoch, or something else,
- ** in any case the time starting point does not change once that the
- ** system has started up.
- */
+{
+ /*
+ ** clock_gettime() is granted to be increased monotonically when the
+ ** monotonic clock is queried. Time starting point is unspecified, it
+ ** could be the system start-up time, the Epoch, or something else,
+ ** in any case the time starting point does not change once that the
+ ** system has started up.
+ */
#ifdef HAVE_GETTIMEOFDAY
- struct timeval now;
+ struct timeval now;
#endif
struct curltime cnow;
- struct timespec tsnow;
+ struct timespec tsnow;
/*
** clock_gettime() may be defined by Apple's SDK as weak symbol thus
@@ -91,27 +91,27 @@ struct curltime Curl_now(void)
(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow))) {
cnow.tv_sec = tsnow.tv_sec;
cnow.tv_usec = (unsigned int)(tsnow.tv_nsec / 1000);
- }
- /*
- ** Even when the configure process has truly detected monotonic clock
- ** availability, it might happen that it is not actually available at
- ** run-time. When this occurs simply fallback to other time source.
- */
-#ifdef HAVE_GETTIMEOFDAY
+ }
+ /*
+ ** Even when the configure process has truly detected monotonic clock
+ ** availability, it might happen that it is not actually available at
+ ** run-time. When this occurs simply fallback to other time source.
+ */
+#ifdef HAVE_GETTIMEOFDAY
else {
- (void)gettimeofday(&now, NULL);
+ (void)gettimeofday(&now, NULL);
cnow.tv_sec = now.tv_sec;
cnow.tv_usec = (unsigned int)now.tv_usec;
}
-#else
- else {
+#else
+ else {
cnow.tv_sec = time(NULL);
cnow.tv_usec = 0;
- }
-#endif
+ }
+#endif
return cnow;
-}
-
+}
+
#elif defined(HAVE_MACH_ABSOLUTE_TIME)
#include <stdint.h>
@@ -143,64 +143,64 @@ struct curltime Curl_now(void)
return cnow;
}
-#elif defined(HAVE_GETTIMEOFDAY)
-
+#elif defined(HAVE_GETTIMEOFDAY)
+
struct curltime Curl_now(void)
-{
- /*
- ** gettimeofday() is not granted to be increased monotonically, due to
- ** clock drifting and external source time synchronization it can jump
- ** forward or backward in time.
- */
- struct timeval now;
+{
+ /*
+ ** gettimeofday() is not granted to be increased monotonically, due to
+ ** clock drifting and external source time synchronization it can jump
+ ** forward or backward in time.
+ */
+ struct timeval now;
struct curltime ret;
- (void)gettimeofday(&now, NULL);
+ (void)gettimeofday(&now, NULL);
ret.tv_sec = now.tv_sec;
ret.tv_usec = (int)now.tv_usec;
return ret;
-}
-
-#else
-
+}
+
+#else
+
struct curltime Curl_now(void)
-{
- /*
- ** time() returns the value of time in seconds since the Epoch.
- */
+{
+ /*
+ ** time() returns the value of time in seconds since the Epoch.
+ */
struct curltime now;
now.tv_sec = time(NULL);
- now.tv_usec = 0;
- return now;
-}
-
-#endif
-
-/*
+ now.tv_usec = 0;
+ return now;
+}
+
+#endif
+
+/*
* Returns: time difference in number of milliseconds. For too large diffs it
* returns max value.
- *
+ *
* @unittest: 1323
- */
+ */
timediff_t Curl_timediff(struct curltime newer, struct curltime older)
-{
+{
timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec;
if(diff >= (TIMEDIFF_T_MAX/1000))
return TIMEDIFF_T_MAX;
else if(diff <= (TIMEDIFF_T_MIN/1000))
return TIMEDIFF_T_MIN;
return diff * 1000 + (newer.tv_usec-older.tv_usec)/1000;
-}
-
-/*
+}
+
+/*
* Returns: time difference in number of microseconds. For too large diffs it
* returns max value.
- */
+ */
timediff_t Curl_timediff_us(struct curltime newer, struct curltime older)
-{
+{
timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec;
if(diff >= (TIMEDIFF_T_MAX/1000000))
return TIMEDIFF_T_MAX;
else if(diff <= (TIMEDIFF_T_MIN/1000000))
return TIMEDIFF_T_MIN;
return diff * 1000000 + newer.tv_usec-older.tv_usec;
-}
+}
diff --git a/contrib/libs/curl/lib/timeval.h b/contrib/libs/curl/lib/timeval.h
index 96a2e1610d..685e72961d 100644
--- a/contrib/libs/curl/lib/timeval.h
+++ b/contrib/libs/curl/lib/timeval.h
@@ -1,34 +1,34 @@
-#ifndef HEADER_CURL_TIMEVAL_H
-#define HEADER_CURL_TIMEVAL_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_TIMEVAL_H
+#define HEADER_CURL_TIMEVAL_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
/* Use a larger type even for 32 bit time_t systems so that we can keep
microsecond accuracy in it */
typedef curl_off_t timediff_t;
#define CURL_FORMAT_TIMEDIFF_T CURL_FORMAT_CURL_OFF_T
-
+
#define TIMEDIFF_T_MAX CURL_OFF_T_MAX
#define TIMEDIFF_T_MIN CURL_OFF_T_MIN
@@ -39,20 +39,20 @@ struct curltime {
struct curltime Curl_now(void);
-/*
- * Make sure that the first argument (t1) is the more recent time and t2 is
- * the older time, as otherwise you get a weird negative time-diff back...
- *
- * Returns: the time difference in number of milliseconds.
- */
+/*
+ * Make sure that the first argument (t1) is the more recent time and t2 is
+ * the older time, as otherwise you get a weird negative time-diff back...
+ *
+ * Returns: the time difference in number of milliseconds.
+ */
timediff_t Curl_timediff(struct curltime t1, struct curltime t2);
-
-/*
+
+/*
* Make sure that the first argument (t1) is the more recent time and t2 is
* the older time, as otherwise you get a weird negative time-diff back...
- *
+ *
* Returns: the time difference in number of microseconds.
- */
+ */
timediff_t Curl_timediff_us(struct curltime newer, struct curltime older);
-
-#endif /* HEADER_CURL_TIMEVAL_H */
+
+#endif /* HEADER_CURL_TIMEVAL_H */
diff --git a/contrib/libs/curl/lib/transfer.c b/contrib/libs/curl/lib/transfer.c
index 47d08822df..bfd0218fef 100644
--- a/contrib/libs/curl/lib/transfer.c
+++ b/contrib/libs/curl/lib/transfer.c
@@ -1,90 +1,90 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-#include "strtoofft.h"
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-#ifdef HAVE_SIGNAL_H
-#include <signal.h>
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+#include "strtoofft.h"
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
#elif defined(HAVE_UNISTD_H)
#include <unistd.h>
-#endif
-
-#ifndef HAVE_SOCKET
-#error "We can't compile without socket() support!"
-#endif
-
-#include "urldata.h"
-#include <curl/curl.h>
-#include "netrc.h"
-
-#include "content_encoding.h"
-#include "hostip.h"
-#include "transfer.h"
-#include "sendf.h"
-#include "speedcheck.h"
-#include "progress.h"
-#include "http.h"
-#include "url.h"
-#include "getinfo.h"
+#endif
+
+#ifndef HAVE_SOCKET
+#error "We can't compile without socket() support!"
+#endif
+
+#include "urldata.h"
+#include <curl/curl.h>
+#include "netrc.h"
+
+#include "content_encoding.h"
+#include "hostip.h"
+#include "transfer.h"
+#include "sendf.h"
+#include "speedcheck.h"
+#include "progress.h"
+#include "http.h"
+#include "url.h"
+#include "getinfo.h"
#include "vtls/vtls.h"
-#include "select.h"
-#include "multiif.h"
-#include "connect.h"
-#include "non-ascii.h"
+#include "select.h"
+#include "multiif.h"
+#include "connect.h"
+#include "non-ascii.h"
#include "http2.h"
#include "mime.h"
#include "strcase.h"
#include "urlapi-int.h"
#include "hsts.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "memdebug.h"
+
#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
!defined(CURL_DISABLE_IMAP)
/*
@@ -99,7 +99,7 @@ char *Curl_checkheaders(const struct connectdata *conn,
struct curl_slist *head;
size_t thislen = strlen(thisheader);
struct Curl_easy *data = conn->data;
-
+
for(head = data->set.headers; head; head = head->next) {
if(strncasecompare(head->data, thisheader, thislen) &&
Curl_headersep(head->data[thislen]) )
@@ -121,7 +121,7 @@ CURLcode Curl_get_upload_buffer(struct Curl_easy *data)
}
#ifndef CURL_DISABLE_HTTP
-/*
+/*
* This function will be called to loop through the trailers buffer
* until no more data is available for sending.
*/
@@ -151,12 +151,12 @@ static size_t Curl_trailers_left(void *raw)
#endif
/*
- * This function will call the read callback to fill our buffer with data
- * to upload.
- */
+ * This function will call the read callback to fill our buffer with data
+ * to upload.
+ */
CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
size_t *nreadp)
-{
+{
struct Curl_easy *data = conn->data;
size_t buffersize = bytes;
size_t nread;
@@ -164,19 +164,19 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
curl_read_callback readfunc = NULL;
void *extra_data = NULL;
-#ifdef CURL_DOES_CONVERSIONS
- bool sending_http_headers = FALSE;
-
+#ifdef CURL_DOES_CONVERSIONS
+ bool sending_http_headers = FALSE;
+
if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
const struct HTTP *http = data->req.p.http;
-
- if(http->sending == HTTPSEND_REQUEST)
- /* We're sending the HTTP request headers, not the data.
- Remember that so we don't re-translate them into garbage. */
- sending_http_headers = TRUE;
- }
-#endif
-
+
+ if(http->sending == HTTPSEND_REQUEST)
+ /* We're sending the HTTP request headers, not the data.
+ Remember that so we don't re-translate them into garbage. */
+ sending_http_headers = TRUE;
+ }
+#endif
+
#ifndef CURL_DISABLE_HTTP
if(data->state.trailers_state == TRAILERS_INITIALIZED) {
struct curl_slist *trailers = NULL;
@@ -218,11 +218,11 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
a chunk size so we skip this */
if(data->req.upload_chunky &&
data->state.trailers_state == TRAILERS_NONE) {
- /* if chunked Transfer-Encoding */
- buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
- data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
- }
-
+ /* if chunked Transfer-Encoding */
+ buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
+ data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
+ }
+
#ifndef CURL_DISABLE_HTTP
if(data->state.trailers_state == TRAILERS_SENDING) {
/* if we're here then that means that we already sent the last empty chunk
@@ -245,14 +245,14 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
nread = readfunc(data->req.upload_fromhere, 1,
buffersize, extra_data);
Curl_set_in_callback(data, false);
-
- if(nread == CURL_READFUNC_ABORT) {
- failf(data, "operation aborted by callback");
- *nreadp = 0;
- return CURLE_ABORTED_BY_CALLBACK;
- }
+
+ if(nread == CURL_READFUNC_ABORT) {
+ failf(data, "operation aborted by callback");
+ *nreadp = 0;
+ return CURLE_ABORTED_BY_CALLBACK;
+ }
if(nread == CURL_READFUNC_PAUSE) {
- struct SingleRequest *k = &data->req;
+ struct SingleRequest *k = &data->req;
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* protocols that work without network cannot be paused. This is
@@ -262,71 +262,71 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
return CURLE_READ_ERROR;
}
- /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
- k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
- if(data->req.upload_chunky) {
+ /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
+ k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
+ if(data->req.upload_chunky) {
/* Back out the preallocation done above */
- data->req.upload_fromhere -= (8 + 2);
- }
- *nreadp = 0;
+ data->req.upload_fromhere -= (8 + 2);
+ }
+ *nreadp = 0;
- return CURLE_OK; /* nothing was read */
- }
+ return CURLE_OK; /* nothing was read */
+ }
else if(nread > buffersize) {
- /* the read function returned a too large value */
- *nreadp = 0;
- failf(data, "read function returned funny value");
- return CURLE_READ_ERROR;
- }
-
- if(!data->req.forbidchunk && data->req.upload_chunky) {
- /* if chunked Transfer-Encoding
- * build chunk:
- *
- * <HEX SIZE> CRLF
- * <DATA> CRLF
- */
- /* On non-ASCII platforms the <DATA> may or may not be
- translated based on set.prefer_ascii while the protocol
- portion must always be translated to the network encoding.
- To further complicate matters, line end conversion might be
- done later on, so we need to prevent CRLFs from becoming
- CRCRLFs if that's the case. To do this we use bare LFs
- here, knowing they'll become CRLFs later on.
- */
-
+ /* the read function returned a too large value */
+ *nreadp = 0;
+ failf(data, "read function returned funny value");
+ return CURLE_READ_ERROR;
+ }
+
+ if(!data->req.forbidchunk && data->req.upload_chunky) {
+ /* if chunked Transfer-Encoding
+ * build chunk:
+ *
+ * <HEX SIZE> CRLF
+ * <DATA> CRLF
+ */
+ /* On non-ASCII platforms the <DATA> may or may not be
+ translated based on set.prefer_ascii while the protocol
+ portion must always be translated to the network encoding.
+ To further complicate matters, line end conversion might be
+ done later on, so we need to prevent CRLFs from becoming
+ CRCRLFs if that's the case. To do this we use bare LFs
+ here, knowing they'll become CRLFs later on.
+ */
+
bool added_crlf = FALSE;
int hexlen = 0;
- const char *endofline_native;
- const char *endofline_network;
-
- if(
-#ifdef CURL_DO_LINEEND_CONV
- (data->set.prefer_ascii) ||
-#endif
- (data->set.crlf)) {
- /* \n will become \r\n later on */
- endofline_native = "\n";
- endofline_network = "\x0a";
- }
- else {
- endofline_native = "\r\n";
- endofline_network = "\x0d\x0a";
- }
-
+ const char *endofline_native;
+ const char *endofline_network;
+
+ if(
+#ifdef CURL_DO_LINEEND_CONV
+ (data->set.prefer_ascii) ||
+#endif
+ (data->set.crlf)) {
+ /* \n will become \r\n later on */
+ endofline_native = "\n";
+ endofline_network = "\x0a";
+ }
+ else {
+ endofline_native = "\r\n";
+ endofline_network = "\x0d\x0a";
+ }
+
/* if we're not handling trailing data, proceed as usual */
if(data->state.trailers_state != TRAILERS_SENDING) {
char hexbuffer[11] = "";
hexlen = msnprintf(hexbuffer, sizeof(hexbuffer),
"%zx%s", nread, endofline_native);
-
+
/* move buffer pointer */
data->req.upload_fromhere -= hexlen;
nread += hexlen;
-
+
/* copy the prefix to the buffer, leaving out the NUL */
memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
-
+
/* always append ASCII CRLF to the data unless
we have a valid trailer callback */
#ifndef CURL_DISABLE_HTTP
@@ -345,7 +345,7 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
}
}
-#ifdef CURL_DOES_CONVERSIONS
+#ifdef CURL_DOES_CONVERSIONS
{
CURLcode result;
size_t length;
@@ -362,9 +362,9 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
if(result)
return result;
}
- }
-#endif /* CURL_DOES_CONVERSIONS */
-
+ }
+#endif /* CURL_DOES_CONVERSIONS */
+
#ifndef CURL_DISABLE_HTTP
if(data->state.trailers_state == TRAILERS_SENDING &&
!Curl_trailers_left(data)) {
@@ -373,7 +373,7 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
data->set.trailer_data = NULL;
data->set.trailer_callback = NULL;
/* mark the transfer as done */
- data->req.upload_done = TRUE;
+ data->req.upload_done = TRUE;
infof(data, "Signaling end of chunked upload after trailers.\n");
}
else
@@ -385,47 +385,47 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
infof(data,
"Signaling end of chunked upload via terminating chunk.\n");
}
-
+
if(added_crlf)
nread += strlen(endofline_network); /* for the added end of line */
- }
-#ifdef CURL_DOES_CONVERSIONS
- else if((data->set.prefer_ascii) && (!sending_http_headers)) {
+ }
+#ifdef CURL_DOES_CONVERSIONS
+ else if((data->set.prefer_ascii) && (!sending_http_headers)) {
CURLcode result;
result = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
- /* Curl_convert_to_network calls failf if unsuccessful */
+ /* Curl_convert_to_network calls failf if unsuccessful */
if(result)
return result;
- }
-#endif /* CURL_DOES_CONVERSIONS */
-
- *nreadp = nread;
-
- return CURLE_OK;
-}
-
-
-/*
- * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
- * POST/PUT with multi-pass authentication when a sending was denied and a
- * resend is necessary.
- */
-CURLcode Curl_readrewind(struct connectdata *conn)
-{
+ }
+#endif /* CURL_DOES_CONVERSIONS */
+
+ *nreadp = nread;
+
+ return CURLE_OK;
+}
+
+
+/*
+ * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
+ * POST/PUT with multi-pass authentication when a sending was denied and a
+ * resend is necessary.
+ */
+CURLcode Curl_readrewind(struct connectdata *conn)
+{
struct Curl_easy *data = conn->data;
curl_mimepart *mimepart = &data->set.mimepost;
-
- conn->bits.rewindaftersend = FALSE; /* we rewind now */
-
- /* explicitly switch off sending data on this connection now since we are
- about to restart a new transfer and thus we want to avoid inadvertently
- sending more data on the existing connection until the next transfer
- starts */
- data->req.keepon &= ~KEEP_SEND;
-
- /* We have sent away data. If not using CURLOPT_POSTFIELDS or
- CURLOPT_HTTPPOST, call app to rewind
- */
+
+ conn->bits.rewindaftersend = FALSE; /* we rewind now */
+
+ /* explicitly switch off sending data on this connection now since we are
+ about to restart a new transfer and thus we want to avoid inadvertently
+ sending more data on the existing connection until the next transfer
+ starts */
+ data->req.keepon &= ~KEEP_SEND;
+
+ /* We have sent away data. If not using CURLOPT_POSTFIELDS or
+ CURLOPT_HTTPPOST, call app to rewind
+ */
if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
struct HTTP *http = data->req.p.http;
@@ -433,7 +433,7 @@ CURLcode Curl_readrewind(struct connectdata *conn)
mimepart = http->sendit;
}
if(data->set.postfields)
- ; /* do nothing */
+ ; /* do nothing */
else if(data->state.httpreq == HTTPREQ_POST_MIME ||
data->state.httpreq == HTTPREQ_POST_FORM) {
if(Curl_mime_rewind(mimepart)) {
@@ -441,52 +441,52 @@ CURLcode Curl_readrewind(struct connectdata *conn)
return CURLE_SEND_FAIL_REWIND;
}
}
- else {
- if(data->set.seek_func) {
- int err;
-
+ else {
+ if(data->set.seek_func) {
+ int err;
+
Curl_set_in_callback(data, true);
- err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
+ err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
Curl_set_in_callback(data, false);
- if(err) {
- failf(data, "seek callback returned error %d", (int)err);
- return CURLE_SEND_FAIL_REWIND;
- }
- }
- else if(data->set.ioctl_func) {
- curlioerr err;
-
+ if(err) {
+ failf(data, "seek callback returned error %d", (int)err);
+ return CURLE_SEND_FAIL_REWIND;
+ }
+ }
+ else if(data->set.ioctl_func) {
+ curlioerr err;
+
Curl_set_in_callback(data, true);
- err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
- data->set.ioctl_client);
+ err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
+ data->set.ioctl_client);
Curl_set_in_callback(data, false);
- infof(data, "the ioctl callback returned %d\n", (int)err);
-
- if(err) {
- failf(data, "ioctl callback returned error %d", (int)err);
- return CURLE_SEND_FAIL_REWIND;
- }
- }
- else {
- /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
- given FILE * stream and we can actually attempt to rewind that
- ourselves with fseek() */
+ infof(data, "the ioctl callback returned %d\n", (int)err);
+
+ if(err) {
+ failf(data, "ioctl callback returned error %d", (int)err);
+ return CURLE_SEND_FAIL_REWIND;
+ }
+ }
+ else {
+ /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
+ given FILE * stream and we can actually attempt to rewind that
+ ourselves with fseek() */
if(data->state.fread_func == (curl_read_callback)fread) {
if(-1 != fseek(data->state.in, 0, SEEK_SET))
- /* successful rewind */
- return CURLE_OK;
- }
-
- /* no callback set or failure above, makes us fail at once */
- failf(data, "necessary data rewind wasn't possible");
- return CURLE_SEND_FAIL_REWIND;
- }
- }
- return CURLE_OK;
-}
-
+ /* successful rewind */
+ return CURLE_OK;
+ }
+
+ /* no callback set or failure above, makes us fail at once */
+ failf(data, "necessary data rewind wasn't possible");
+ return CURLE_SEND_FAIL_REWIND;
+ }
+ }
+ return CURLE_OK;
+}
+
static int data_pending(const struct Curl_easy *data)
-{
+{
struct connectdata *conn = data->conn;
#ifdef ENABLE_QUIC
@@ -494,9 +494,9 @@ static int data_pending(const struct Curl_easy *data)
return Curl_quic_data_pending(data);
#endif
- /* in the case of libssh2, we can never be really sure that we have emptied
- its internal buffers so we MUST always try until we get EAGAIN back */
- return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
+ /* in the case of libssh2, we can never be really sure that we have emptied
+ its internal buffers so we MUST always try until we get EAGAIN back */
+ return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
#if defined(USE_NGHTTP2)
Curl_ssl_data_pending(conn, FIRSTSOCKET) ||
/* For HTTP/2, we may read up everything including response body
@@ -508,78 +508,78 @@ static int data_pending(const struct Curl_easy *data)
a workaround, we return nonzero here to call http2_recv. */
((conn->handler->protocol&PROTO_FAMILY_HTTP) && conn->httpversion >= 20);
#else
- Curl_ssl_data_pending(conn, FIRSTSOCKET);
+ Curl_ssl_data_pending(conn, FIRSTSOCKET);
#endif
-}
-
-/*
- * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
- * remote document with the time provided by CURLOPT_TIMEVAL
- */
+}
+
+/*
+ * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
+ * remote document with the time provided by CURLOPT_TIMEVAL
+ */
bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
-{
- if((timeofdoc == 0) || (data->set.timevalue == 0))
- return TRUE;
-
- switch(data->set.timecondition) {
- case CURL_TIMECOND_IFMODSINCE:
- default:
- if(timeofdoc <= data->set.timevalue) {
- infof(data,
- "The requested document is not new enough\n");
- data->info.timecond = TRUE;
- return FALSE;
- }
- break;
- case CURL_TIMECOND_IFUNMODSINCE:
- if(timeofdoc >= data->set.timevalue) {
- infof(data,
- "The requested document is not old enough\n");
- data->info.timecond = TRUE;
- return FALSE;
- }
- break;
- }
-
- return TRUE;
-}
-
-/*
- * Go ahead and do a read if we have a readable socket or if
- * the stream was rewound (in which case we have data in a
- * buffer)
+{
+ if((timeofdoc == 0) || (data->set.timevalue == 0))
+ return TRUE;
+
+ switch(data->set.timecondition) {
+ case CURL_TIMECOND_IFMODSINCE:
+ default:
+ if(timeofdoc <= data->set.timevalue) {
+ infof(data,
+ "The requested document is not new enough\n");
+ data->info.timecond = TRUE;
+ return FALSE;
+ }
+ break;
+ case CURL_TIMECOND_IFUNMODSINCE:
+ if(timeofdoc >= data->set.timevalue) {
+ infof(data,
+ "The requested document is not old enough\n");
+ data->info.timecond = TRUE;
+ return FALSE;
+ }
+ break;
+ }
+
+ return TRUE;
+}
+
+/*
+ * Go ahead and do a read if we have a readable socket or if
+ * the stream was rewound (in which case we have data in a
+ * buffer)
*
* return '*comeback' TRUE if we didn't properly drain the socket so this
* function should get called again without select() or similar in between!
- */
+ */
static CURLcode readwrite_data(struct Curl_easy *data,
- struct connectdata *conn,
- struct SingleRequest *k,
+ struct connectdata *conn,
+ struct SingleRequest *k,
int *didwhat, bool *done,
bool *comeback)
-{
- CURLcode result = CURLE_OK;
- ssize_t nread; /* number of bytes read */
- size_t excess = 0; /* excess bytes read */
- bool readmore = FALSE; /* used by RTP to signal for more data */
+{
+ CURLcode result = CURLE_OK;
+ ssize_t nread; /* number of bytes read */
+ size_t excess = 0; /* excess bytes read */
+ bool readmore = FALSE; /* used by RTP to signal for more data */
int maxloops = 100;
char *buf = data->state.buffer;
DEBUGASSERT(buf);
-
- *done = FALSE;
+
+ *done = FALSE;
*comeback = FALSE;
-
- /* This is where we loop until we have read everything there is to
- read or we get a CURLE_AGAIN */
- do {
+
+ /* This is where we loop until we have read everything there is to
+ read or we get a CURLE_AGAIN */
+ do {
bool is_empty_data = FALSE;
size_t buffersize = data->set.buffer_size;
- size_t bytestoread = buffersize;
+ size_t bytestoread = buffersize;
#ifdef USE_NGHTTP2
bool is_http2 = ((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
(conn->httpversion == 20));
#endif
-
+
if(
#ifdef USE_NGHTTP2
/* For HTTP/2, read data without caring about the content
@@ -592,43 +592,43 @@ static CURLcode readwrite_data(struct Curl_easy *data,
#endif
k->size != -1 && !k->header) {
/* make sure we don't read too much */
- curl_off_t totalleft = k->size - k->bytecount;
- if(totalleft < (curl_off_t)bytestoread)
- bytestoread = (size_t)totalleft;
- }
-
- if(bytestoread) {
- /* receive data from the network! */
+ curl_off_t totalleft = k->size - k->bytecount;
+ if(totalleft < (curl_off_t)bytestoread)
+ bytestoread = (size_t)totalleft;
+ }
+
+ if(bytestoread) {
+ /* receive data from the network! */
result = Curl_read(conn, conn->sockfd, buf, bytestoread, &nread);
-
- /* read would've blocked */
- if(CURLE_AGAIN == result)
- break; /* get out of loop */
-
- if(result>0)
- return result;
- }
- else {
- /* read nothing but since we wanted nothing we consider this an OK
- situation to proceed from */
+
+ /* read would've blocked */
+ if(CURLE_AGAIN == result)
+ break; /* get out of loop */
+
+ if(result>0)
+ return result;
+ }
+ else {
+ /* read nothing but since we wanted nothing we consider this an OK
+ situation to proceed from */
DEBUGF(infof(data, "readwrite_data: we're done!\n"));
- nread = 0;
- }
-
+ nread = 0;
+ }
+
if(!k->bytecount) {
- Curl_pgrsTime(data, TIMER_STARTTRANSFER);
- if(k->exp100 > EXP100_SEND_DATA)
- /* set time stamp to compare with when waiting for the 100 */
+ Curl_pgrsTime(data, TIMER_STARTTRANSFER);
+ if(k->exp100 > EXP100_SEND_DATA)
+ /* set time stamp to compare with when waiting for the 100 */
k->start100 = Curl_now();
- }
-
- *didwhat |= KEEP_RECV;
- /* indicates data of zero size, i.e. empty file */
- is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
-
- if(0 < nread || is_empty_data) {
+ }
+
+ *didwhat |= KEEP_RECV;
+ /* indicates data of zero size, i.e. empty file */
+ is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
+
+ if(0 < nread || is_empty_data) {
buf[nread] = 0;
- }
+ }
else {
/* if we receive 0 or less here, either the http2 stream is closed or the
server closed the connection and we bail out from this! */
@@ -638,63 +638,63 @@ static CURLcode readwrite_data(struct Curl_easy *data,
else
#endif
DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
- k->keepon &= ~KEEP_RECV;
- break;
- }
-
- /* Default buffer to use when we write the buffer, it may be changed
- in the flow below before the actual storing is done. */
+ k->keepon &= ~KEEP_RECV;
+ break;
+ }
+
+ /* Default buffer to use when we write the buffer, it may be changed
+ in the flow below before the actual storing is done. */
k->str = buf;
-
- if(conn->handler->readwrite) {
- result = conn->handler->readwrite(data, conn, &nread, &readmore);
- if(result)
- return result;
- if(readmore)
- break;
- }
-
-#ifndef CURL_DISABLE_HTTP
- /* Since this is a two-state thing, we check if we are parsing
- headers at the moment or not. */
- if(k->header) {
- /* we are in parse-the-header-mode */
- bool stop_reading = FALSE;
- result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
- if(result)
- return result;
-
- if(conn->handler->readwrite &&
- (k->maxdownload <= 0 && nread > 0)) {
- result = conn->handler->readwrite(data, conn, &nread, &readmore);
- if(result)
- return result;
- if(readmore)
- break;
- }
-
- if(stop_reading) {
- /* We've stopped dealing with input, get out of the do-while loop */
-
- if(nread > 0) {
+
+ if(conn->handler->readwrite) {
+ result = conn->handler->readwrite(data, conn, &nread, &readmore);
+ if(result)
+ return result;
+ if(readmore)
+ break;
+ }
+
+#ifndef CURL_DISABLE_HTTP
+ /* Since this is a two-state thing, we check if we are parsing
+ headers at the moment or not. */
+ if(k->header) {
+ /* we are in parse-the-header-mode */
+ bool stop_reading = FALSE;
+ result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
+ if(result)
+ return result;
+
+ if(conn->handler->readwrite &&
+ (k->maxdownload <= 0 && nread > 0)) {
+ result = conn->handler->readwrite(data, conn, &nread, &readmore);
+ if(result)
+ return result;
+ if(readmore)
+ break;
+ }
+
+ if(stop_reading) {
+ /* We've stopped dealing with input, get out of the do-while loop */
+
+ if(nread > 0) {
infof(data,
"Excess found:"
" excess = %zd"
" url = %s (zero-length body)\n",
nread, data->state.up.path);
- }
-
- break;
- }
- }
-#endif /* CURL_DISABLE_HTTP */
-
-
- /* This is not an 'else if' since it may be a rest from the header
- parsing, where the beginning of the buffer is headers and the end
- is non-headers. */
+ }
+
+ break;
+ }
+ }
+#endif /* CURL_DISABLE_HTTP */
+
+
+ /* This is not an 'else if' since it may be a rest from the header
+ parsing, where the beginning of the buffer is headers and the end
+ is non-headers. */
if(!k->header && (nread > 0 || is_empty_data)) {
-
+
if(data->set.opt_no_body) {
/* data arrives although we want none, bail out */
streamclose(conn, "ignoring body");
@@ -702,30 +702,30 @@ static CURLcode readwrite_data(struct Curl_easy *data,
return CURLE_WEIRD_SERVER_REPLY;
}
-#ifndef CURL_DISABLE_HTTP
- if(0 == k->bodywrites && !is_empty_data) {
- /* These checks are only made the first time we are about to
- write a piece of the body */
+#ifndef CURL_DISABLE_HTTP
+ if(0 == k->bodywrites && !is_empty_data) {
+ /* These checks are only made the first time we are about to
+ write a piece of the body */
if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
- /* HTTP-only checks */
-
- if(data->req.newurl) {
- if(conn->bits.close) {
- /* Abort after the headers if "follow Location" is set
- and we're set to close anyway. */
- k->keepon &= ~KEEP_RECV;
- *done = TRUE;
- return CURLE_OK;
- }
- /* We have a new url to load, but since we want to be able
- to re-use this connection properly, we read the full
- response in "ignore more" */
- k->ignorebody = TRUE;
- infof(data, "Ignoring the response-body\n");
- }
- if(data->state.resume_from && !k->content_range &&
+ /* HTTP-only checks */
+
+ if(data->req.newurl) {
+ if(conn->bits.close) {
+ /* Abort after the headers if "follow Location" is set
+ and we're set to close anyway. */
+ k->keepon &= ~KEEP_RECV;
+ *done = TRUE;
+ return CURLE_OK;
+ }
+ /* We have a new url to load, but since we want to be able
+ to re-use this connection properly, we read the full
+ response in "ignore more" */
+ k->ignorebody = TRUE;
+ infof(data, "Ignoring the response-body\n");
+ }
+ if(data->state.resume_from && !k->content_range &&
(data->state.httpreq == HTTPREQ_GET) &&
- !k->ignorebody) {
+ !k->ignorebody) {
if(k->size == data->state.resume_from) {
/* The resume point is at the end of file, consider this fine
@@ -738,105 +738,105 @@ static CURLcode readwrite_data(struct Curl_easy *data,
return CURLE_OK;
}
- /* we wanted to resume a download, although the server doesn't
- * seem to support this and we did this with a GET (if it
- * wasn't a GET we did a POST or PUT resume) */
- failf(data, "HTTP server doesn't seem to support "
- "byte ranges. Cannot resume.");
- return CURLE_RANGE_ERROR;
- }
-
- if(data->set.timecondition && !data->state.range) {
- /* A time condition has been set AND no ranges have been
- requested. This seems to be what chapter 13.3.4 of
- RFC 2616 defines to be the correct action for a
- HTTP/1.1 client */
-
- if(!Curl_meets_timecondition(data, k->timeofdoc)) {
- *done = TRUE;
- /* We're simulating a http 304 from server so we return
- what should have been returned from the server */
- data->info.httpcode = 304;
- infof(data, "Simulate a HTTP 304 response!\n");
- /* we abort the transfer before it is completed == we ruin the
- re-use ability. Close the connection */
+ /* we wanted to resume a download, although the server doesn't
+ * seem to support this and we did this with a GET (if it
+ * wasn't a GET we did a POST or PUT resume) */
+ failf(data, "HTTP server doesn't seem to support "
+ "byte ranges. Cannot resume.");
+ return CURLE_RANGE_ERROR;
+ }
+
+ if(data->set.timecondition && !data->state.range) {
+ /* A time condition has been set AND no ranges have been
+ requested. This seems to be what chapter 13.3.4 of
+ RFC 2616 defines to be the correct action for a
+ HTTP/1.1 client */
+
+ if(!Curl_meets_timecondition(data, k->timeofdoc)) {
+ *done = TRUE;
+ /* We're simulating a http 304 from server so we return
+ what should have been returned from the server */
+ data->info.httpcode = 304;
+ infof(data, "Simulate a HTTP 304 response!\n");
+ /* we abort the transfer before it is completed == we ruin the
+ re-use ability. Close the connection */
connclose(conn, "Simulated 304 handling");
- return CURLE_OK;
- }
- } /* we have a time condition */
-
- } /* this is HTTP or RTSP */
- } /* this is the first time we write a body part */
-#endif /* CURL_DISABLE_HTTP */
-
- k->bodywrites++;
-
- /* pass data to the debug function before it gets "dechunked" */
- if(data->set.verbose) {
- if(k->badheader) {
+ return CURLE_OK;
+ }
+ } /* we have a time condition */
+
+ } /* this is HTTP or RTSP */
+ } /* this is the first time we write a body part */
+#endif /* CURL_DISABLE_HTTP */
+
+ k->bodywrites++;
+
+ /* pass data to the debug function before it gets "dechunked" */
+ if(data->set.verbose) {
+ if(k->badheader) {
Curl_debug(data, CURLINFO_DATA_IN,
Curl_dyn_ptr(&data->state.headerb),
Curl_dyn_len(&data->state.headerb));
- if(k->badheader == HEADER_PARTHEADER)
- Curl_debug(data, CURLINFO_DATA_IN,
+ if(k->badheader == HEADER_PARTHEADER)
+ Curl_debug(data, CURLINFO_DATA_IN,
k->str, (size_t)nread);
- }
- else
- Curl_debug(data, CURLINFO_DATA_IN,
+ }
+ else
+ Curl_debug(data, CURLINFO_DATA_IN,
k->str, (size_t)nread);
- }
-
-#ifndef CURL_DISABLE_HTTP
- if(k->chunk) {
- /*
- * Here comes a chunked transfer flying and we need to decode this
- * properly. While the name says read, this function both reads
- * and writes away the data. The returned 'nread' holds the number
- * of actual data it wrote to the client.
- */
+ }
+
+#ifndef CURL_DISABLE_HTTP
+ if(k->chunk) {
+ /*
+ * Here comes a chunked transfer flying and we need to decode this
+ * properly. While the name says read, this function both reads
+ * and writes away the data. The returned 'nread' holds the number
+ * of actual data it wrote to the client.
+ */
CURLcode extra;
- CHUNKcode res =
+ CHUNKcode res =
Curl_httpchunk_read(conn, k->str, nread, &nread, &extra);
-
- if(CHUNKE_OK < res) {
+
+ if(CHUNKE_OK < res) {
if(CHUNKE_PASSTHRU_ERROR == res) {
failf(data, "Failed reading the chunked-encoded stream");
return extra;
- }
+ }
failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res));
- return CURLE_RECV_ERROR;
- }
+ return CURLE_RECV_ERROR;
+ }
if(CHUNKE_STOP == res) {
- size_t dataleft;
- /* we're done reading chunks! */
- k->keepon &= ~KEEP_RECV; /* read no more */
-
- /* There are now possibly N number of bytes at the end of the
- str buffer that weren't written to the client.
- Push it back to be read on the next pass. */
-
- dataleft = conn->chunk.dataleft;
- if(dataleft != 0) {
- infof(conn->data, "Leftovers after chunking: %zu bytes\n",
- dataleft);
- }
- }
- /* If it returned OK, we just keep going */
- }
-#endif /* CURL_DISABLE_HTTP */
-
- /* Account for body content stored in the header buffer */
+ size_t dataleft;
+ /* we're done reading chunks! */
+ k->keepon &= ~KEEP_RECV; /* read no more */
+
+ /* There are now possibly N number of bytes at the end of the
+ str buffer that weren't written to the client.
+ Push it back to be read on the next pass. */
+
+ dataleft = conn->chunk.dataleft;
+ if(dataleft != 0) {
+ infof(conn->data, "Leftovers after chunking: %zu bytes\n",
+ dataleft);
+ }
+ }
+ /* If it returned OK, we just keep going */
+ }
+#endif /* CURL_DISABLE_HTTP */
+
+ /* Account for body content stored in the header buffer */
if((k->badheader == HEADER_PARTHEADER) && !k->ignorebody) {
size_t headlen = Curl_dyn_len(&data->state.headerb);
DEBUGF(infof(data, "Increasing bytecount by %zu\n", headlen));
k->bytecount += headlen;
- }
-
- if((-1 != k->maxdownload) &&
- (k->bytecount + nread >= k->maxdownload)) {
-
- excess = (size_t)(k->bytecount + nread - k->maxdownload);
- if(excess > 0 && !k->ignorebody) {
+ }
+
+ if((-1 != k->maxdownload) &&
+ (k->bytecount + nread >= k->maxdownload)) {
+
+ excess = (size_t)(k->bytecount + nread - k->maxdownload);
+ if(excess > 0 && !k->ignorebody) {
infof(data,
"Excess found in a read:"
" excess = %zu"
@@ -845,99 +845,99 @@ static CURLcode readwrite_data(struct Curl_easy *data,
", bytecount = %" CURL_FORMAT_CURL_OFF_T "\n",
excess, k->size, k->maxdownload, k->bytecount);
connclose(conn, "excess found in a read");
- }
-
- nread = (ssize_t) (k->maxdownload - k->bytecount);
+ }
+
+ nread = (ssize_t) (k->maxdownload - k->bytecount);
if(nread < 0) /* this should be unusual */
- nread = 0;
-
- k->keepon &= ~KEEP_RECV; /* we're done reading */
- }
-
- k->bytecount += nread;
-
- Curl_pgrsSetDownloadCounter(data, k->bytecount);
-
- if(!k->chunk && (nread || k->badheader || is_empty_data)) {
- /* If this is chunky transfer, it was already written */
-
- if(k->badheader && !k->ignorebody) {
- /* we parsed a piece of data wrongly assuming it was a header
- and now we output it as body instead */
+ nread = 0;
+
+ k->keepon &= ~KEEP_RECV; /* we're done reading */
+ }
+
+ k->bytecount += nread;
+
+ Curl_pgrsSetDownloadCounter(data, k->bytecount);
+
+ if(!k->chunk && (nread || k->badheader || is_empty_data)) {
+ /* If this is chunky transfer, it was already written */
+
+ if(k->badheader && !k->ignorebody) {
+ /* we parsed a piece of data wrongly assuming it was a header
+ and now we output it as body instead */
size_t headlen = Curl_dyn_len(&data->state.headerb);
-
- /* Don't let excess data pollute body writes */
+
+ /* Don't let excess data pollute body writes */
if(k->maxdownload == -1 || (curl_off_t)headlen <= k->maxdownload)
- result = Curl_client_write(conn, CLIENTWRITE_BODY,
+ result = Curl_client_write(conn, CLIENTWRITE_BODY,
Curl_dyn_ptr(&data->state.headerb),
headlen);
- else
- result = Curl_client_write(conn, CLIENTWRITE_BODY,
+ else
+ result = Curl_client_write(conn, CLIENTWRITE_BODY,
Curl_dyn_ptr(&data->state.headerb),
- (size_t)k->maxdownload);
-
- if(result)
- return result;
- }
- if(k->badheader < HEADER_ALLBAD) {
- /* This switch handles various content encodings. If there's an
- error here, be sure to check over the almost identical code
- in http_chunks.c.
- Make sure that ALL_CONTENT_ENCODINGS contains all the
- encodings handled here. */
+ (size_t)k->maxdownload);
+
+ if(result)
+ return result;
+ }
+ if(k->badheader < HEADER_ALLBAD) {
+ /* This switch handles various content encodings. If there's an
+ error here, be sure to check over the almost identical code
+ in http_chunks.c.
+ Make sure that ALL_CONTENT_ENCODINGS contains all the
+ encodings handled here. */
if(conn->data->set.http_ce_skip || !k->writer_stack) {
- if(!k->ignorebody) {
-#ifndef CURL_DISABLE_POP3
+ if(!k->ignorebody) {
+#ifndef CURL_DISABLE_POP3
if(conn->handler->protocol & PROTO_FAMILY_POP3)
- result = Curl_pop3_write(conn, k->str, nread);
- else
-#endif /* CURL_DISABLE_POP3 */
- result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
- nread);
- }
- }
+ result = Curl_pop3_write(conn, k->str, nread);
+ else
+#endif /* CURL_DISABLE_POP3 */
+ result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
+ nread);
+ }
+ }
else if(!k->ignorebody)
result = Curl_unencode_write(conn, k->writer_stack, k->str, nread);
- }
- k->badheader = HEADER_NORMAL; /* taken care of now */
-
- if(result)
- return result;
- }
-
+ }
+ k->badheader = HEADER_NORMAL; /* taken care of now */
+
+ if(result)
+ return result;
+ }
+
} /* if(!header and data to read) */
-
+
if(conn->handler->readwrite && excess) {
- /* Parse the excess data */
- k->str += nread;
+ /* Parse the excess data */
+ k->str += nread;
if(&k->str[excess] > &buf[data->set.buffer_size]) {
/* the excess amount was too excessive(!), make sure
it doesn't read out of buffer */
excess = &buf[data->set.buffer_size] - k->str;
}
- nread = (ssize_t)excess;
-
- result = conn->handler->readwrite(data, conn, &nread, &readmore);
- if(result)
- return result;
-
- if(readmore)
- k->keepon |= KEEP_RECV; /* we're not done reading */
- break;
- }
-
- if(is_empty_data) {
- /* if we received nothing, the server closed the connection and we
- are done */
- k->keepon &= ~KEEP_RECV;
- }
-
+ nread = (ssize_t)excess;
+
+ result = conn->handler->readwrite(data, conn, &nread, &readmore);
+ if(result)
+ return result;
+
+ if(readmore)
+ k->keepon |= KEEP_RECV; /* we're not done reading */
+ break;
+ }
+
+ if(is_empty_data) {
+ /* if we received nothing, the server closed the connection and we
+ are done */
+ k->keepon &= ~KEEP_RECV;
+ }
+
if(k->keepon & KEEP_RECV_PAUSE) {
/* this is a paused transfer */
break;
}
-
+
} while(data_pending(data) && maxloops--);
if(maxloops <= 0) {
@@ -946,18 +946,18 @@ static CURLcode readwrite_data(struct Curl_easy *data,
*comeback = TRUE;
}
- if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
+ if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
conn->bits.close) {
- /* When we've read the entire thing and the close bit is set, the server
- may now close the connection. If there's now any kind of sending going
- on from our side, we need to stop that immediately. */
- infof(data, "we are done reading and this is set to close, stop send\n");
- k->keepon &= ~KEEP_SEND; /* no writing anymore either */
- }
-
- return CURLE_OK;
-}
-
+ /* When we've read the entire thing and the close bit is set, the server
+ may now close the connection. If there's now any kind of sending going
+ on from our side, we need to stop that immediately. */
+ infof(data, "we are done reading and this is set to close, stop send\n");
+ k->keepon &= ~KEEP_SEND; /* no writing anymore either */
+ }
+
+ return CURLE_OK;
+}
+
CURLcode Curl_done_sending(struct connectdata *conn,
struct SingleRequest *k)
{
@@ -996,95 +996,95 @@ static void win_update_buffer_size(curl_socket_t sockfd)
#define win_update_buffer_size(x)
#endif
-/*
- * Send data to upload to the server, when the socket is writable.
- */
+/*
+ * Send data to upload to the server, when the socket is writable.
+ */
static CURLcode readwrite_upload(struct Curl_easy *data,
- struct connectdata *conn,
- int *didwhat)
-{
- ssize_t i, si;
- ssize_t bytes_written;
- CURLcode result;
- ssize_t nread; /* number of bytes read */
- bool sending_http_headers = FALSE;
+ struct connectdata *conn,
+ int *didwhat)
+{
+ ssize_t i, si;
+ ssize_t bytes_written;
+ CURLcode result;
+ ssize_t nread; /* number of bytes read */
+ bool sending_http_headers = FALSE;
struct SingleRequest *k = &data->req;
-
- if((k->bytecount == 0) && (k->writebytecount == 0))
- Curl_pgrsTime(data, TIMER_STARTTRANSFER);
-
- *didwhat |= KEEP_SEND;
-
- do {
- /* only read more data if there's no upload data already
- present in the upload buffer */
+
+ if((k->bytecount == 0) && (k->writebytecount == 0))
+ Curl_pgrsTime(data, TIMER_STARTTRANSFER);
+
+ *didwhat |= KEEP_SEND;
+
+ do {
+ /* only read more data if there's no upload data already
+ present in the upload buffer */
if(0 == k->upload_present) {
result = Curl_get_upload_buffer(data);
if(result)
return result;
- /* init the "upload from here" pointer */
+ /* init the "upload from here" pointer */
k->upload_fromhere = data->state.ulbuf;
-
- if(!k->upload_done) {
- /* HTTP pollution, this should be written nicer to become more
- protocol agnostic. */
+
+ if(!k->upload_done) {
+ /* HTTP pollution, this should be written nicer to become more
+ protocol agnostic. */
size_t fillcount;
struct HTTP *http = k->p.http;
-
- if((k->exp100 == EXP100_SENDING_REQUEST) &&
- (http->sending == HTTPSEND_BODY)) {
- /* If this call is to send body data, we must take some action:
- We have sent off the full HTTP 1.1 request, and we shall now
- go into the Expect: 100 state and await such a header */
- k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
- k->keepon &= ~KEEP_SEND; /* disable writing */
+
+ if((k->exp100 == EXP100_SENDING_REQUEST) &&
+ (http->sending == HTTPSEND_BODY)) {
+ /* If this call is to send body data, we must take some action:
+ We have sent off the full HTTP 1.1 request, and we shall now
+ go into the Expect: 100 state and await such a header */
+ k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
+ k->keepon &= ~KEEP_SEND; /* disable writing */
k->start100 = Curl_now(); /* timeout count starts now */
- *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
- /* set a timeout for the multi interface */
+ *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
+ /* set a timeout for the multi interface */
Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
- break;
- }
-
+ break;
+ }
+
if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
- if(http->sending == HTTPSEND_REQUEST)
- /* We're sending the HTTP request headers, not the data.
- Remember that so we don't change the line endings. */
- sending_http_headers = TRUE;
- else
- sending_http_headers = FALSE;
- }
-
+ if(http->sending == HTTPSEND_REQUEST)
+ /* We're sending the HTTP request headers, not the data.
+ Remember that so we don't change the line endings. */
+ sending_http_headers = TRUE;
+ else
+ sending_http_headers = FALSE;
+ }
+
result = Curl_fillreadbuffer(conn, data->set.upload_buffer_size,
&fillcount);
- if(result)
- return result;
-
+ if(result)
+ return result;
+
nread = fillcount;
- }
- else
- nread = 0; /* we're done uploading/reading */
-
- if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
- /* this is a paused transfer */
- break;
- }
+ }
+ else
+ nread = 0; /* we're done uploading/reading */
+
+ if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
+ /* this is a paused transfer */
+ break;
+ }
if(nread <= 0) {
result = Curl_done_sending(conn, k);
if(result)
return result;
- break;
- }
-
- /* store number of bytes available for upload */
+ break;
+ }
+
+ /* store number of bytes available for upload */
k->upload_present = nread;
-
- /* convert LF to CRLF if so asked */
- if((!sending_http_headers) && (
-#ifdef CURL_DO_LINEEND_CONV
- /* always convert if we're FTPing in ASCII mode */
- (data->set.prefer_ascii) ||
-#endif
- (data->set.crlf))) {
+
+ /* convert LF to CRLF if so asked */
+ if((!sending_http_headers) && (
+#ifdef CURL_DO_LINEEND_CONV
+ /* always convert if we're FTPing in ASCII mode */
+ (data->set.prefer_ascii) ||
+#endif
+ (data->set.crlf))) {
/* Do we need to allocate a scratch buffer? */
if(!data->state.scratch) {
data->state.scratch = malloc(2 * data->set.upload_buffer_size);
@@ -1093,41 +1093,41 @@ static CURLcode readwrite_upload(struct Curl_easy *data,
return CURLE_OUT_OF_MEMORY;
}
- }
-
- /*
- * ASCII/EBCDIC Note: This is presumably a text (not binary)
- * transfer so the data should already be in ASCII.
- * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
- * must be used instead of the escape sequences \r & \n.
- */
- for(i = 0, si = 0; i < nread; i++, si++) {
+ }
+
+ /*
+ * ASCII/EBCDIC Note: This is presumably a text (not binary)
+ * transfer so the data should already be in ASCII.
+ * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
+ * must be used instead of the escape sequences \r & \n.
+ */
+ for(i = 0, si = 0; i < nread; i++, si++) {
if(k->upload_fromhere[i] == 0x0a) {
- data->state.scratch[si++] = 0x0d;
- data->state.scratch[si] = 0x0a;
- if(!data->set.crlf) {
- /* we're here only because FTP is in ASCII mode...
- bump infilesize for the LF we just added */
+ data->state.scratch[si++] = 0x0d;
+ data->state.scratch[si] = 0x0a;
+ if(!data->set.crlf) {
+ /* we're here only because FTP is in ASCII mode...
+ bump infilesize for the LF we just added */
if(data->state.infilesize != -1)
data->state.infilesize++;
- }
- }
- else
+ }
+ }
+ else
data->state.scratch[si] = k->upload_fromhere[i];
- }
-
- if(si != nread) {
- /* only perform the special operation if we really did replace
- anything */
- nread = si;
-
- /* upload from the new (replaced) buffer instead */
+ }
+
+ if(si != nread) {
+ /* only perform the special operation if we really did replace
+ anything */
+ nread = si;
+
+ /* upload from the new (replaced) buffer instead */
k->upload_fromhere = data->state.scratch;
-
- /* set the new amount too */
+
+ /* set the new amount too */
k->upload_present = nread;
- }
- }
+ }
+ }
#ifndef CURL_DISABLE_SMTP
if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
@@ -1137,305 +1137,305 @@ static CURLcode readwrite_upload(struct Curl_easy *data,
}
#endif /* CURL_DISABLE_SMTP */
} /* if 0 == k->upload_present */
- else {
- /* We have a partial buffer left from a previous "round". Use
- that instead of reading more data */
- }
-
- /* write to socket (send away data) */
- result = Curl_write(conn,
+ else {
+ /* We have a partial buffer left from a previous "round". Use
+ that instead of reading more data */
+ }
+
+ /* write to socket (send away data) */
+ result = Curl_write(conn,
conn->writesockfd, /* socket to send to */
k->upload_fromhere, /* buffer pointer */
k->upload_present, /* buffer size */
&bytes_written); /* actually sent */
- if(result)
- return result;
-
+ if(result)
+ return result;
+
win_update_buffer_size(conn->writesockfd);
/* show the data before we change the pointer upload_fromhere */
Curl_debug(data, CURLINFO_DATA_OUT, k->upload_fromhere,
(size_t)bytes_written);
-
- k->writebytecount += bytes_written;
+
+ k->writebytecount += bytes_written;
Curl_pgrsSetUploadCounter(data, k->writebytecount);
-
+
if((!k->upload_chunky || k->forbidchunk) &&
(k->writebytecount == data->state.infilesize)) {
- /* we have sent all data we were supposed to */
- k->upload_done = TRUE;
- infof(data, "We are completely uploaded and fine\n");
- }
-
+ /* we have sent all data we were supposed to */
+ k->upload_done = TRUE;
+ infof(data, "We are completely uploaded and fine\n");
+ }
+
if(k->upload_present != bytes_written) {
- /* we only wrote a part of the buffer (if anything), deal with it! */
-
- /* store the amount of bytes left in the buffer to write */
+ /* we only wrote a part of the buffer (if anything), deal with it! */
+
+ /* store the amount of bytes left in the buffer to write */
k->upload_present -= bytes_written;
-
- /* advance the pointer where to find the buffer when the next send
- is to happen */
+
+ /* advance the pointer where to find the buffer when the next send
+ is to happen */
k->upload_fromhere += bytes_written;
- }
- else {
- /* we've uploaded that buffer now */
+ }
+ else {
+ /* we've uploaded that buffer now */
result = Curl_get_upload_buffer(data);
if(result)
return result;
k->upload_fromhere = data->state.ulbuf;
k->upload_present = 0; /* no more bytes left */
-
- if(k->upload_done) {
+
+ if(k->upload_done) {
result = Curl_done_sending(conn, k);
if(result)
return result;
- }
- }
-
-
+ }
+ }
+
+
} while(0); /* just to break out from! */
-
- return CURLE_OK;
-}
-
-/*
- * Curl_readwrite() is the low-level function to be called when data is to
- * be read and written to/from the connection.
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_readwrite() is the low-level function to be called when data is to
+ * be read and written to/from the connection.
*
* return '*comeback' TRUE if we didn't properly drain the socket so this
* function should get called again without select() or similar in between!
- */
-CURLcode Curl_readwrite(struct connectdata *conn,
+ */
+CURLcode Curl_readwrite(struct connectdata *conn,
struct Curl_easy *data,
bool *done,
bool *comeback)
-{
- struct SingleRequest *k = &data->req;
- CURLcode result;
+{
+ struct SingleRequest *k = &data->req;
+ CURLcode result;
int didwhat = 0;
-
- curl_socket_t fd_read;
- curl_socket_t fd_write;
- int select_res = conn->cselect_bits;
-
- conn->cselect_bits = 0;
-
- /* only use the proper socket if the *_HOLD bit is not set simultaneously as
- then we are in rate limiting state in that transfer direction */
-
- if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
- fd_read = conn->sockfd;
- else
- fd_read = CURL_SOCKET_BAD;
-
- if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
- fd_write = conn->writesockfd;
- else
- fd_write = CURL_SOCKET_BAD;
-
+
+ curl_socket_t fd_read;
+ curl_socket_t fd_write;
+ int select_res = conn->cselect_bits;
+
+ conn->cselect_bits = 0;
+
+ /* only use the proper socket if the *_HOLD bit is not set simultaneously as
+ then we are in rate limiting state in that transfer direction */
+
+ if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
+ fd_read = conn->sockfd;
+ else
+ fd_read = CURL_SOCKET_BAD;
+
+ if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
+ fd_write = conn->writesockfd;
+ else
+ fd_write = CURL_SOCKET_BAD;
+
if(conn->data->state.drain) {
select_res |= CURL_CSELECT_IN;
DEBUGF(infof(data, "Curl_readwrite: forcibly told to drain data\n"));
}
- if(!select_res) /* Call for select()/poll() only, if read/write/error
- status is not known. */
+ if(!select_res) /* Call for select()/poll() only, if read/write/error
+ status is not known. */
select_res = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0);
-
- if(select_res == CURL_CSELECT_ERR) {
- failf(data, "select/poll returned error");
- return CURLE_SEND_ERROR;
- }
-
- /* We go ahead and do a read if we have a readable socket or if
- the stream was rewound (in which case we have data in a
- buffer) */
+
+ if(select_res == CURL_CSELECT_ERR) {
+ failf(data, "select/poll returned error");
+ return CURLE_SEND_ERROR;
+ }
+
+ /* We go ahead and do a read if we have a readable socket or if
+ the stream was rewound (in which case we have data in a
+ buffer) */
if((k->keepon & KEEP_RECV) && (select_res & CURL_CSELECT_IN)) {
result = readwrite_data(data, conn, k, &didwhat, done, comeback);
- if(result || *done)
- return result;
- }
-
- /* If we still have writing to do, we check if we have a writable socket. */
- if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
- /* write */
-
+ if(result || *done)
+ return result;
+ }
+
+ /* If we still have writing to do, we check if we have a writable socket. */
+ if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
+ /* write */
+
result = readwrite_upload(data, conn, &didwhat);
- if(result)
- return result;
- }
-
+ if(result)
+ return result;
+ }
+
k->now = Curl_now();
- if(didwhat) {
+ if(didwhat) {
;
- }
- else {
- /* no read no write, this is a timeout? */
- if(k->exp100 == EXP100_AWAITING_CONTINUE) {
- /* This should allow some time for the header to arrive, but only a
- very short time as otherwise it'll be too much wasted time too
- often. */
-
- /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
-
- Therefore, when a client sends this header field to an origin server
- (possibly via a proxy) from which it has never seen a 100 (Continue)
- status, the client SHOULD NOT wait for an indefinite period before
- sending the request body.
-
- */
-
+ }
+ else {
+ /* no read no write, this is a timeout? */
+ if(k->exp100 == EXP100_AWAITING_CONTINUE) {
+ /* This should allow some time for the header to arrive, but only a
+ very short time as otherwise it'll be too much wasted time too
+ often. */
+
+ /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
+
+ Therefore, when a client sends this header field to an origin server
+ (possibly via a proxy) from which it has never seen a 100 (Continue)
+ status, the client SHOULD NOT wait for an indefinite period before
+ sending the request body.
+
+ */
+
timediff_t ms = Curl_timediff(k->now, k->start100);
if(ms >= data->set.expect_100_timeout) {
- /* we've waited long enough, continue anyway */
- k->exp100 = EXP100_SEND_DATA;
- k->keepon |= KEEP_SEND;
+ /* we've waited long enough, continue anyway */
+ k->exp100 = EXP100_SEND_DATA;
+ k->keepon |= KEEP_SEND;
Curl_expire_done(data, EXPIRE_100_TIMEOUT);
- infof(data, "Done waiting for 100-continue\n");
- }
- }
- }
-
- if(Curl_pgrsUpdate(conn))
- result = CURLE_ABORTED_BY_CALLBACK;
- else
- result = Curl_speedcheck(data, k->now);
- if(result)
- return result;
-
- if(k->keepon) {
- if(0 > Curl_timeleft(data, &k->now, FALSE)) {
- if(k->size != -1) {
+ infof(data, "Done waiting for 100-continue\n");
+ }
+ }
+ }
+
+ if(Curl_pgrsUpdate(conn))
+ result = CURLE_ABORTED_BY_CALLBACK;
+ else
+ result = Curl_speedcheck(data, k->now);
+ if(result)
+ return result;
+
+ if(k->keepon) {
+ if(0 > Curl_timeleft(data, &k->now, FALSE)) {
+ if(k->size != -1) {
failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
" milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
CURL_FORMAT_CURL_OFF_T " bytes received",
Curl_timediff(k->now, data->progress.t_startsingle),
k->bytecount, k->size);
- }
- else {
+ }
+ else {
failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
" milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received",
Curl_timediff(k->now, data->progress.t_startsingle),
k->bytecount);
- }
- return CURLE_OPERATION_TIMEDOUT;
- }
- }
- else {
- /*
- * The transfer has been performed. Just make some general checks before
- * returning.
- */
-
- if(!(data->set.opt_no_body) && (k->size != -1) &&
- (k->bytecount != k->size) &&
-#ifdef CURL_DO_LINEEND_CONV
- /* Most FTP servers don't adjust their file SIZE response for CRLFs,
- so we'll check to see if the discrepancy can be explained
- by the number of CRLFs we've changed to LFs.
- */
- (k->bytecount != (k->size + data->state.crlf_conversions)) &&
-#endif /* CURL_DO_LINEEND_CONV */
+ }
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+ }
+ else {
+ /*
+ * The transfer has been performed. Just make some general checks before
+ * returning.
+ */
+
+ if(!(data->set.opt_no_body) && (k->size != -1) &&
+ (k->bytecount != k->size) &&
+#ifdef CURL_DO_LINEEND_CONV
+ /* Most FTP servers don't adjust their file SIZE response for CRLFs,
+ so we'll check to see if the discrepancy can be explained
+ by the number of CRLFs we've changed to LFs.
+ */
+ (k->bytecount != (k->size + data->state.crlf_conversions)) &&
+#endif /* CURL_DO_LINEEND_CONV */
!k->newurl) {
failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T
" bytes remaining to read", k->size - k->bytecount);
- return CURLE_PARTIAL_FILE;
- }
+ return CURLE_PARTIAL_FILE;
+ }
if(!(data->set.opt_no_body) && k->chunk &&
(conn->chunk.state != CHUNK_STOP)) {
- /*
- * In chunked mode, return an error if the connection is closed prior to
- * the empty (terminating) chunk is read.
- *
- * The condition above used to check for
- * conn->proto.http->chunk.datasize != 0 which is true after reading
- * *any* chunk, not just the empty chunk.
- *
- */
- failf(data, "transfer closed with outstanding read data remaining");
- return CURLE_PARTIAL_FILE;
- }
- if(Curl_pgrsUpdate(conn))
- return CURLE_ABORTED_BY_CALLBACK;
- }
-
- /* Now update the "done" boolean we return */
- *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
- KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
-
- return CURLE_OK;
-}
-
-/*
- * Curl_single_getsock() gets called by the multi interface code when the app
- * has requested to get the sockets for the current connection. This function
- * will then be called once for every connection that the multi interface
- * keeps track of. This function will only be called for connections that are
- * in the proper state to have this information available.
- */
-int Curl_single_getsock(const struct connectdata *conn,
+ /*
+ * In chunked mode, return an error if the connection is closed prior to
+ * the empty (terminating) chunk is read.
+ *
+ * The condition above used to check for
+ * conn->proto.http->chunk.datasize != 0 which is true after reading
+ * *any* chunk, not just the empty chunk.
+ *
+ */
+ failf(data, "transfer closed with outstanding read data remaining");
+ return CURLE_PARTIAL_FILE;
+ }
+ if(Curl_pgrsUpdate(conn))
+ return CURLE_ABORTED_BY_CALLBACK;
+ }
+
+ /* Now update the "done" boolean we return */
+ *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
+ KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_single_getsock() gets called by the multi interface code when the app
+ * has requested to get the sockets for the current connection. This function
+ * will then be called once for every connection that the multi interface
+ * keeps track of. This function will only be called for connections that are
+ * in the proper state to have this information available.
+ */
+int Curl_single_getsock(const struct connectdata *conn,
curl_socket_t *sock)
-{
+{
const struct Curl_easy *data = conn->data;
- int bitmap = GETSOCK_BLANK;
- unsigned sockindex = 0;
-
- if(conn->handler->perform_getsock)
+ int bitmap = GETSOCK_BLANK;
+ unsigned sockindex = 0;
+
+ if(conn->handler->perform_getsock)
return conn->handler->perform_getsock(conn, sock);
-
- /* don't include HOLD and PAUSE connections */
- if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
-
- DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
-
- bitmap |= GETSOCK_READSOCK(sockindex);
- sock[sockindex] = conn->sockfd;
- }
-
- /* don't include HOLD and PAUSE connections */
- if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
-
- if((conn->sockfd != conn->writesockfd) ||
+
+ /* don't include HOLD and PAUSE connections */
+ if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
+
+ DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
+
+ bitmap |= GETSOCK_READSOCK(sockindex);
+ sock[sockindex] = conn->sockfd;
+ }
+
+ /* don't include HOLD and PAUSE connections */
+ if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
+
+ if((conn->sockfd != conn->writesockfd) ||
bitmap == GETSOCK_BLANK) {
/* only if they are not the same socket and we have a readable
- one, we increase index */
+ one, we increase index */
if(bitmap != GETSOCK_BLANK)
- sockindex++; /* increase index if we need two entries */
-
- DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
-
- sock[sockindex] = conn->writesockfd;
- }
-
- bitmap |= GETSOCK_WRITESOCK(sockindex);
- }
-
- return bitmap;
-}
-
+ sockindex++; /* increase index if we need two entries */
+
+ DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
+
+ sock[sockindex] = conn->writesockfd;
+ }
+
+ bitmap |= GETSOCK_WRITESOCK(sockindex);
+ }
+
+ return bitmap;
+}
+
/* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
which means this gets called once for each subsequent redirect etc */
void Curl_init_CONNECT(struct Curl_easy *data)
-{
+{
data->state.fread_func = data->set.fread_func_set;
data->state.in = data->set.in_set;
-}
-
-/*
+}
+
+/*
* Curl_pretransfer() is called immediately before a transfer starts, and only
* once for one transfer no matter if it has redirects or do multi-pass
* authentication etc.
- */
+ */
CURLcode Curl_pretransfer(struct Curl_easy *data)
-{
+{
CURLcode result;
if(!data->change.url && !data->set.uh) {
- /* we can't do anything without URL */
- failf(data, "No URL set!");
- return CURLE_URL_MALFORMAT;
- }
-
+ /* we can't do anything without URL */
+ failf(data, "No URL set!");
+ return CURLE_URL_MALFORMAT;
+ }
+
/* since the URL may have been redirected in a previous use of this handle */
if(data->change.url_alloc) {
/* the already set URL is allocated, free it first! */
@@ -1457,24 +1457,24 @@ CURLcode Curl_pretransfer(struct Curl_easy *data)
data->state.httpreq = data->set.method;
data->change.url = data->set.str[STRING_SET_URL];
- /* Init the SSL session ID cache here. We do it here since we want to do it
- after the *_setopt() calls (that could specify the size of the cache) but
- before any transfer takes place. */
+ /* Init the SSL session ID cache here. We do it here since we want to do it
+ after the *_setopt() calls (that could specify the size of the cache) but
+ before any transfer takes place. */
result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions);
if(result)
return result;
-
+
data->state.wildcardmatch = data->set.wildcard_enabled;
data->set.followlocation = 0; /* reset the location-follow counter */
- data->state.this_is_a_follow = FALSE; /* reset this */
- data->state.errorbuf = FALSE; /* no error has occurred */
- data->state.httpversion = 0; /* don't assume any particular server version */
-
- data->state.authproblem = FALSE;
- data->state.authhost.want = data->set.httpauth;
- data->state.authproxy.want = data->set.proxyauth;
- Curl_safefree(data->info.wouldredirect);
-
+ data->state.this_is_a_follow = FALSE; /* reset this */
+ data->state.errorbuf = FALSE; /* no error has occurred */
+ data->state.httpversion = 0; /* don't assume any particular server version */
+
+ data->state.authproblem = FALSE;
+ data->state.authhost.want = data->set.httpauth;
+ data->state.authproxy.want = data->set.proxyauth;
+ Curl_safefree(data->info.wouldredirect);
+
if(data->state.httpreq == HTTPREQ_PUT)
data->state.infilesize = data->set.filesize;
else if((data->state.httpreq != HTTPREQ_GET) &&
@@ -1486,37 +1486,37 @@ CURLcode Curl_pretransfer(struct Curl_easy *data)
else
data->state.infilesize = 0;
- /* If there is a list of cookie files to read, do it now! */
- if(data->change.cookielist)
- Curl_cookie_loadfiles(data);
-
- /* If there is a list of host pairs to deal with */
- if(data->change.resolve)
+ /* If there is a list of cookie files to read, do it now! */
+ if(data->change.cookielist)
+ Curl_cookie_loadfiles(data);
+
+ /* If there is a list of host pairs to deal with */
+ if(data->change.resolve)
result = Curl_loadhostpairs(data);
-
+
if(!result) {
- /* Allow data->set.use_port to set which port to use. This needs to be
- * disabled for example when we follow Location: headers to URLs using
- * different ports! */
- data->state.allow_port = TRUE;
-
-#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
- /*************************************************************
- * Tell signal handler to ignore SIGPIPE
- *************************************************************/
- if(!data->set.no_signal)
- data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
-#endif
-
- Curl_initinfo(data); /* reset session-specific information "variables" */
+ /* Allow data->set.use_port to set which port to use. This needs to be
+ * disabled for example when we follow Location: headers to URLs using
+ * different ports! */
+ data->state.allow_port = TRUE;
+
+#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
+ /*************************************************************
+ * Tell signal handler to ignore SIGPIPE
+ *************************************************************/
+ if(!data->set.no_signal)
+ data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
+#endif
+
+ Curl_initinfo(data); /* reset session-specific information "variables" */
Curl_pgrsResetTransferSizes(data);
- Curl_pgrsStartNow(data);
-
- /* In case the handle is re-used and an authentication method was picked
- in the session we need to make sure we only use the one(s) we now
- consider to be fine */
- data->state.authhost.picked &= data->state.authhost.want;
- data->state.authproxy.picked &= data->state.authproxy.want;
+ Curl_pgrsStartNow(data);
+
+ /* In case the handle is re-used and an authentication method was picked
+ in the session we need to make sure we only use the one(s) we now
+ consider to be fine */
+ data->state.authhost.picked &= data->state.authhost.want;
+ data->state.authproxy.picked &= data->state.authproxy.want;
#ifndef CURL_DISABLE_FTP
if(data->state.wildcardmatch) {
@@ -1530,85 +1530,85 @@ CURLcode Curl_pretransfer(struct Curl_easy *data)
#endif
Curl_http2_init_state(&data->state);
Curl_hsts_loadcb(data, data->hsts);
- }
-
+ }
+
return result;
-}
-
-/*
- * Curl_posttransfer() is called immediately after a transfer ends
- */
+}
+
+/*
+ * Curl_posttransfer() is called immediately after a transfer ends
+ */
CURLcode Curl_posttransfer(struct Curl_easy *data)
-{
-#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
- /* restore the signal handler for SIGPIPE before we get back */
- if(!data->set.no_signal)
- signal(SIGPIPE, data->state.prev_signal);
-#else
- (void)data; /* unused parameter */
-#endif
-
- return CURLE_OK;
-}
-
-/*
- * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
- * as given by the remote server and set up the new URL to request.
+{
+#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
+ /* restore the signal handler for SIGPIPE before we get back */
+ if(!data->set.no_signal)
+ signal(SIGPIPE, data->state.prev_signal);
+#else
+ (void)data; /* unused parameter */
+#endif
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
+ * as given by the remote server and set up the new URL to request.
*
* This function DOES NOT FREE the given url.
- */
+ */
CURLcode Curl_follow(struct Curl_easy *data,
char *newurl, /* the Location: string */
- followtype type) /* see transfer.h */
-{
-#ifdef CURL_DISABLE_HTTP
- (void)data;
- (void)newurl;
- (void)type;
- /* Location: following will not happen when HTTP is disabled */
- return CURLE_TOO_MANY_REDIRECTS;
-#else
-
- /* Location: redirect */
- bool disallowport = FALSE;
+ followtype type) /* see transfer.h */
+{
+#ifdef CURL_DISABLE_HTTP
+ (void)data;
+ (void)newurl;
+ (void)type;
+ /* Location: following will not happen when HTTP is disabled */
+ return CURLE_TOO_MANY_REDIRECTS;
+#else
+
+ /* Location: redirect */
+ bool disallowport = FALSE;
bool reachedmax = FALSE;
CURLUcode uc;
-
- if(type == FOLLOW_REDIR) {
- if((data->set.maxredirs != -1) &&
+
+ if(type == FOLLOW_REDIR) {
+ if((data->set.maxredirs != -1) &&
(data->set.followlocation >= data->set.maxredirs)) {
reachedmax = TRUE;
type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
to URL */
- }
+ }
else {
/* mark the next request as a followed location: */
data->state.this_is_a_follow = TRUE;
-
+
data->set.followlocation++; /* count location-followers */
-
+
if(data->set.http_auto_referer) {
/* We are asked to automatically set the previous URL as the referer
when we get the next URL. We pick the ->url field, which may or may
not be 100% correct */
-
+
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
-
+
data->change.referer = strdup(data->change.url);
if(!data->change.referer)
return CURLE_OUT_OF_MEMORY;
data->change.referer_alloc = TRUE; /* yes, free this later */
- }
- }
- }
-
+ }
+ }
+ }
+
if(Curl_is_absolute_url(newurl, NULL, MAX_SCHEME_LEN))
- /* This is an absolute URL, don't allow the custom port number */
- disallowport = TRUE;
-
+ /* This is an absolute URL, don't allow the custom port number */
+ disallowport = TRUE;
+
DEBUGASSERT(data->state.uh);
uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl,
(type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
@@ -1616,7 +1616,7 @@ CURLcode Curl_follow(struct Curl_easy *data,
if(uc) {
if(type != FOLLOW_FAKE)
return Curl_uc_to_curlcode(uc);
-
+
/* the URL could not be parsed for some reason, but since this is FAKE
mode, just duplicate the field as-is */
newurl = strdup(newurl);
@@ -1624,81 +1624,81 @@ CURLcode Curl_follow(struct Curl_easy *data,
return CURLE_OUT_OF_MEMORY;
}
else {
-
+
uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
- }
-
- if(type == FOLLOW_FAKE) {
- /* we're only figuring out the new url if we would've followed locations
- but now we're done so we can get out! */
- data->info.wouldredirect = newurl;
+ }
+
+ if(type == FOLLOW_FAKE) {
+ /* we're only figuring out the new url if we would've followed locations
+ but now we're done so we can get out! */
+ data->info.wouldredirect = newurl;
if(reachedmax) {
failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
return CURLE_TOO_MANY_REDIRECTS;
}
- return CURLE_OK;
- }
-
- if(disallowport)
- data->state.allow_port = FALSE;
-
+ return CURLE_OK;
+ }
+
+ if(disallowport)
+ data->state.allow_port = FALSE;
+
if(data->change.url_alloc)
- Curl_safefree(data->change.url);
-
- data->change.url = newurl;
- data->change.url_alloc = TRUE;
-
- infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
-
- /*
- * We get here when the HTTP code is 300-399 (and 401). We need to perform
- * differently based on exactly what return code there was.
- *
- * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
- * a HTTP (proxy-) authentication scheme other than Basic.
- */
- switch(data->info.httpcode) {
- /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
- Authorization: XXXX header in the HTTP request code snippet */
- /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
- Proxy-Authorization: XXXX header in the HTTP request code snippet */
- /* 300 - Multiple Choices */
- /* 306 - Not used */
- /* 307 - Temporary Redirect */
- default: /* for all above (and the unknown ones) */
- /* Some codes are explicitly mentioned since I've checked RFC2616 and they
- * seem to be OK to POST to.
- */
- break;
- case 301: /* Moved Permanently */
+ Curl_safefree(data->change.url);
+
+ data->change.url = newurl;
+ data->change.url_alloc = TRUE;
+
+ infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
+
+ /*
+ * We get here when the HTTP code is 300-399 (and 401). We need to perform
+ * differently based on exactly what return code there was.
+ *
+ * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
+ * a HTTP (proxy-) authentication scheme other than Basic.
+ */
+ switch(data->info.httpcode) {
+ /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
+ Authorization: XXXX header in the HTTP request code snippet */
+ /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
+ Proxy-Authorization: XXXX header in the HTTP request code snippet */
+ /* 300 - Multiple Choices */
+ /* 306 - Not used */
+ /* 307 - Temporary Redirect */
+ default: /* for all above (and the unknown ones) */
+ /* Some codes are explicitly mentioned since I've checked RFC2616 and they
+ * seem to be OK to POST to.
+ */
+ break;
+ case 301: /* Moved Permanently */
/* (quote from RFC7231, section 6.4.2)
- *
+ *
* Note: For historical reasons, a user agent MAY change the request
* method from POST to GET for the subsequent request. If this
* behavior is undesired, the 307 (Temporary Redirect) status code
* can be used instead.
- *
- * ----
- *
+ *
+ * ----
+ *
* Many webservers expect this, so these servers often answers to a POST
* request with an error page. To be sure that libcurl gets the page that
- * most user agents would get, libcurl has to force GET.
- *
+ * most user agents would get, libcurl has to force GET.
+ *
* This behaviour is forbidden by RFC1945 and the obsolete RFC2616, and
* can be overridden with CURLOPT_POSTREDIR.
- */
+ */
if((data->state.httpreq == HTTPREQ_POST
|| data->state.httpreq == HTTPREQ_POST_FORM
|| data->state.httpreq == HTTPREQ_POST_MIME)
- && !(data->set.keep_post & CURL_REDIR_POST_301)) {
+ && !(data->set.keep_post & CURL_REDIR_POST_301)) {
infof(data, "Switch from POST to GET\n");
data->state.httpreq = HTTPREQ_GET;
- }
- break;
- case 302: /* Found */
+ }
+ break;
+ case 302: /* Found */
/* (quote from RFC7231, section 6.4.3)
*
* Note: For historical reasons, a user agent MAY change the request
@@ -1718,13 +1718,13 @@ CURLcode Curl_follow(struct Curl_easy *data,
if((data->state.httpreq == HTTPREQ_POST
|| data->state.httpreq == HTTPREQ_POST_FORM
|| data->state.httpreq == HTTPREQ_POST_MIME)
- && !(data->set.keep_post & CURL_REDIR_POST_302)) {
+ && !(data->set.keep_post & CURL_REDIR_POST_302)) {
infof(data, "Switch from POST to GET\n");
data->state.httpreq = HTTPREQ_GET;
- }
- break;
-
- case 303: /* See Other */
+ }
+ break;
+
+ case 303: /* See Other */
/* 'See Other' location is not the resource but a substitute for the
* resource. In this case we switch the method to GET/HEAD, unless the
* method is POST and the user specified to keep it as POST.
@@ -1738,47 +1738,47 @@ CURLcode Curl_follow(struct Curl_easy *data,
data->state.httpreq = HTTPREQ_GET;
data->set.upload = false;
infof(data, "Switch to %s\n",
- data->set.opt_no_body?"HEAD":"GET");
- }
- break;
- case 304: /* Not Modified */
- /* 304 means we did a conditional request and it was "Not modified".
- * We shouldn't get any Location: header in this response!
- */
- break;
- case 305: /* Use Proxy */
- /* (quote from RFC2616, section 10.3.6):
- * "The requested resource MUST be accessed through the proxy given
- * by the Location field. The Location field gives the URI of the
- * proxy. The recipient is expected to repeat this single request
- * via the proxy. 305 responses MUST only be generated by origin
- * servers."
- */
- break;
- }
- Curl_pgrsTime(data, TIMER_REDIRECT);
+ data->set.opt_no_body?"HEAD":"GET");
+ }
+ break;
+ case 304: /* Not Modified */
+ /* 304 means we did a conditional request and it was "Not modified".
+ * We shouldn't get any Location: header in this response!
+ */
+ break;
+ case 305: /* Use Proxy */
+ /* (quote from RFC2616, section 10.3.6):
+ * "The requested resource MUST be accessed through the proxy given
+ * by the Location field. The Location field gives the URI of the
+ * proxy. The recipient is expected to repeat this single request
+ * via the proxy. 305 responses MUST only be generated by origin
+ * servers."
+ */
+ break;
+ }
+ Curl_pgrsTime(data, TIMER_REDIRECT);
Curl_pgrsResetTransferSizes(data);
-
- return CURLE_OK;
-#endif /* CURL_DISABLE_HTTP */
-}
-
-/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
-
- NOTE: that the *url is malloc()ed. */
-CURLcode Curl_retry_request(struct connectdata *conn,
- char **url)
-{
+
+ return CURLE_OK;
+#endif /* CURL_DISABLE_HTTP */
+}
+
+/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
+
+ NOTE: that the *url is malloc()ed. */
+CURLcode Curl_retry_request(struct connectdata *conn,
+ char **url)
+{
struct Curl_easy *data = conn->data;
bool retry = FALSE;
- *url = NULL;
-
- /* if we're talking upload, we can't do the checks below, unless the protocol
- is HTTP as when uploading over HTTP we will still get a response */
- if(data->set.upload &&
+ *url = NULL;
+
+ /* if we're talking upload, we can't do the checks below, unless the protocol
+ is HTTP as when uploading over HTTP we will still get a response */
+ if(data->set.upload &&
!(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
- return CURLE_OK;
-
+ return CURLE_OK;
+
if((data->req.bytecount + data->req.headerbytecount == 0) &&
conn->bits.reuse &&
(!data->set.opt_no_body
@@ -1789,8 +1789,8 @@ CURLcode Curl_retry_request(struct connectdata *conn,
For other protocols we only try again only if we expected a body.
This might happen if the connection was left alive when we were
- done using it before, but that was closed when we wanted to read from
- it again. Bad luck. Retry the same request on a fresh connect! */
+ done using it before, but that was closed when we wanted to read from
+ it again. Bad luck. Retry the same request on a fresh connect! */
retry = TRUE;
else if(data->state.refused_stream &&
(data->req.bytecount + data->req.headerbytecount == 0) ) {
@@ -1813,18 +1813,18 @@ CURLcode Curl_retry_request(struct connectdata *conn,
}
infof(conn->data, "Connection died, retrying a fresh connect\
(retry count: %d)\n", data->state.retrycount);
- *url = strdup(conn->data->change.url);
- if(!*url)
- return CURLE_OUT_OF_MEMORY;
-
+ *url = strdup(conn->data->change.url);
+ if(!*url)
+ return CURLE_OUT_OF_MEMORY;
+
connclose(conn, "retry"); /* close this connection */
- conn->bits.retry = TRUE; /* mark this as a connection we're about
- to retry. Marking it this way should
- prevent i.e HTTP transfers to return
- error just because nothing has been
- transferred! */
-
-
+ conn->bits.retry = TRUE; /* mark this as a connection we're about
+ to retry. Marking it this way should
+ prevent i.e HTTP transfers to return
+ error just because nothing has been
+ transferred! */
+
+
if(conn->handler->protocol&PROTO_FAMILY_HTTP) {
if(data->req.writebytecount) {
CURLcode result = Curl_readrewind(conn);
@@ -1833,33 +1833,33 @@ CURLcode Curl_retry_request(struct connectdata *conn,
return result;
}
}
- }
- }
- return CURLE_OK;
-}
-
-/*
- * Curl_setup_transfer() is called to setup some basic properties for the
- * upcoming transfer.
- */
-void
-Curl_setup_transfer(
+ }
+ }
+ return CURLE_OK;
+}
+
+/*
+ * Curl_setup_transfer() is called to setup some basic properties for the
+ * upcoming transfer.
+ */
+void
+Curl_setup_transfer(
struct Curl_easy *data, /* transfer */
- int sockindex, /* socket index to read from or -1 */
- curl_off_t size, /* -1 if unknown at this point */
- bool getheader, /* TRUE if header parsing is wanted */
+ int sockindex, /* socket index to read from or -1 */
+ curl_off_t size, /* -1 if unknown at this point */
+ bool getheader, /* TRUE if header parsing is wanted */
int writesockindex /* socket index to write to, it may very well be
- the same we read from. -1 disables */
- )
-{
+ the same we read from. -1 disables */
+ )
+{
struct SingleRequest *k = &data->req;
struct connectdata *conn = data->conn;
struct HTTP *http = data->req.p.http;
bool httpsending = ((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
(http->sending == HTTPSEND_REQUEST));
- DEBUGASSERT(conn != NULL);
- DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
-
+ DEBUGASSERT(conn != NULL);
+ DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
+
if(conn->bits.multiplex || conn->httpversion == 20 || httpsending) {
/* when multiplexing, the read/write sockets need to be the same! */
conn->sockfd = sockindex == -1 ?
@@ -1872,60 +1872,60 @@ Curl_setup_transfer(
}
else {
conn->sockfd = sockindex == -1 ?
- CURL_SOCKET_BAD : conn->sock[sockindex];
+ CURL_SOCKET_BAD : conn->sock[sockindex];
conn->writesockfd = writesockindex == -1 ?
- CURL_SOCKET_BAD:conn->sock[writesockindex];
+ CURL_SOCKET_BAD:conn->sock[writesockindex];
}
- k->getheader = getheader;
-
- k->size = size;
-
- /* The code sequence below is placed in this function just because all
- necessary input is not always known in do_complete() as this function may
- be called after that */
-
- if(!k->getheader) {
- k->header = FALSE;
- if(size > 0)
- Curl_pgrsSetDownloadSize(data, size);
- }
- /* we want header and/or body, if neither then don't do this! */
- if(k->getheader || !data->set.opt_no_body) {
-
+ k->getheader = getheader;
+
+ k->size = size;
+
+ /* The code sequence below is placed in this function just because all
+ necessary input is not always known in do_complete() as this function may
+ be called after that */
+
+ if(!k->getheader) {
+ k->header = FALSE;
+ if(size > 0)
+ Curl_pgrsSetDownloadSize(data, size);
+ }
+ /* we want header and/or body, if neither then don't do this! */
+ if(k->getheader || !data->set.opt_no_body) {
+
if(sockindex != -1)
- k->keepon |= KEEP_RECV;
-
+ k->keepon |= KEEP_RECV;
+
if(writesockindex != -1) {
- /* HTTP 1.1 magic:
-
- Even if we require a 100-return code before uploading data, we might
- need to write data before that since the REQUEST may not have been
- finished sent off just yet.
-
- Thus, we must check if the request has been sent before we set the
- state info where we wait for the 100-return code
- */
- if((data->state.expect100header) &&
+ /* HTTP 1.1 magic:
+
+ Even if we require a 100-return code before uploading data, we might
+ need to write data before that since the REQUEST may not have been
+ finished sent off just yet.
+
+ Thus, we must check if the request has been sent before we set the
+ state info where we wait for the 100-return code
+ */
+ if((data->state.expect100header) &&
(conn->handler->protocol&PROTO_FAMILY_HTTP) &&
- (http->sending == HTTPSEND_BODY)) {
- /* wait with write until we either got 100-continue or a timeout */
- k->exp100 = EXP100_AWAITING_CONTINUE;
+ (http->sending == HTTPSEND_BODY)) {
+ /* wait with write until we either got 100-continue or a timeout */
+ k->exp100 = EXP100_AWAITING_CONTINUE;
k->start100 = Curl_now();
-
- /* Set a timeout for the multi interface. Add the inaccuracy margin so
- that we don't fire slightly too early and get denied to run. */
+
+ /* Set a timeout for the multi interface. Add the inaccuracy margin so
+ that we don't fire slightly too early and get denied to run. */
Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
- }
- else {
- if(data->state.expect100header)
- /* when we've sent off the rest of the headers, we must await a
- 100-continue but first finish sending the request */
- k->exp100 = EXP100_SENDING_REQUEST;
-
- /* enable the write bit when we're not waiting for continue */
- k->keepon |= KEEP_SEND;
- }
+ }
+ else {
+ if(data->state.expect100header)
+ /* when we've sent off the rest of the headers, we must await a
+ 100-continue but first finish sending the request */
+ k->exp100 = EXP100_SENDING_REQUEST;
+
+ /* enable the write bit when we're not waiting for continue */
+ k->keepon |= KEEP_SEND;
+ }
} /* if(writesockindex != -1) */
- } /* if(k->getheader || !data->set.opt_no_body) */
-
-}
+ } /* if(k->getheader || !data->set.opt_no_body) */
+
+}
diff --git a/contrib/libs/curl/lib/transfer.h b/contrib/libs/curl/lib/transfer.h
index 5323f97a50..178bb58fb0 100644
--- a/contrib/libs/curl/lib/transfer.h
+++ b/contrib/libs/curl/lib/transfer.h
@@ -1,27 +1,27 @@
-#ifndef HEADER_CURL_TRANSFER_H
-#define HEADER_CURL_TRANSFER_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_TRANSFER_H
+#define HEADER_CURL_TRANSFER_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#define Curl_headersep(x) ((((x)==':') || ((x)==';')))
char *Curl_checkheaders(const struct connectdata *conn,
const char *thisheader);
@@ -30,36 +30,36 @@ void Curl_init_CONNECT(struct Curl_easy *data);
CURLcode Curl_pretransfer(struct Curl_easy *data);
CURLcode Curl_posttransfer(struct Curl_easy *data);
-
-typedef enum {
- FOLLOW_NONE, /* not used within the function, just a placeholder to
- allow initing to this */
- FOLLOW_FAKE, /* only records stuff, not actually following */
- FOLLOW_RETRY, /* set if this is a request retry as opposed to a real
- redirect following */
- FOLLOW_REDIR, /* a full true redirect */
- FOLLOW_LAST /* never used */
-} followtype;
-
+
+typedef enum {
+ FOLLOW_NONE, /* not used within the function, just a placeholder to
+ allow initing to this */
+ FOLLOW_FAKE, /* only records stuff, not actually following */
+ FOLLOW_RETRY, /* set if this is a request retry as opposed to a real
+ redirect following */
+ FOLLOW_REDIR, /* a full true redirect */
+ FOLLOW_LAST /* never used */
+} followtype;
+
CURLcode Curl_follow(struct Curl_easy *data, char *newurl,
- followtype type);
+ followtype type);
CURLcode Curl_readwrite(struct connectdata *conn,
struct Curl_easy *data, bool *done,
bool *comeback);
-int Curl_single_getsock(const struct connectdata *conn,
+int Curl_single_getsock(const struct connectdata *conn,
curl_socket_t *socks);
-CURLcode Curl_readrewind(struct connectdata *conn);
+CURLcode Curl_readrewind(struct connectdata *conn);
CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
size_t *nreadp);
-CURLcode Curl_retry_request(struct connectdata *conn, char **url);
+CURLcode Curl_retry_request(struct connectdata *conn, char **url);
bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc);
CURLcode Curl_get_upload_buffer(struct Curl_easy *data);
-
+
CURLcode Curl_done_sending(struct connectdata *conn,
struct SingleRequest *k);
-/* This sets up a forthcoming transfer */
-void
+/* This sets up a forthcoming transfer */
+void
Curl_setup_transfer (struct Curl_easy *data,
int sockindex, /* socket index to read from or -1 */
curl_off_t size, /* -1 if unknown at this point */
@@ -68,5 +68,5 @@ Curl_setup_transfer (struct Curl_easy *data,
the same we read from. -1
disables */
);
-
-#endif /* HEADER_CURL_TRANSFER_H */
+
+#endif /* HEADER_CURL_TRANSFER_H */
diff --git a/contrib/libs/curl/lib/url.c b/contrib/libs/curl/lib/url.c
index ab9ad7bf26..95e37dfeed 100644
--- a/contrib/libs/curl/lib/url.c
+++ b/contrib/libs/curl/lib/url.c
@@ -1,136 +1,136 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_NET_IF_H
-#include <net/if.h>
-#endif
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NET_IF_H
+#include <net/if.h>
+#endif
#ifdef HAVE_IPHLPAPI_H
#include <Iphlpapi.h>
#endif
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#ifdef __VMS
-#include <in.h>
-#include <inet.h>
-#endif
-
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
-#ifndef HAVE_SOCKET
-#error "We can't compile without socket() support!"
-#endif
-
-#include <limits.h>
-
+#ifndef HAVE_SOCKET
+#error "We can't compile without socket() support!"
+#endif
+
+#include <limits.h>
+
#ifdef USE_LIBIDN2
#error #include <idn2.h>
-#elif defined(USE_WIN32_IDN)
-/* prototype for curl_win32_idn_to_ascii() */
+#elif defined(USE_WIN32_IDN)
+/* prototype for curl_win32_idn_to_ascii() */
bool curl_win32_idn_to_ascii(const char *in, char **out);
#endif /* USE_LIBIDN2 */
-
-#include "urldata.h"
-#include "netrc.h"
-
-#include "formdata.h"
+
+#include "urldata.h"
+#include "netrc.h"
+
+#include "formdata.h"
#include "mime.h"
#include "vtls/vtls.h"
-#include "hostip.h"
-#include "transfer.h"
-#include "sendf.h"
-#include "progress.h"
-#include "cookie.h"
+#include "hostip.h"
+#include "transfer.h"
+#include "sendf.h"
+#include "progress.h"
+#include "cookie.h"
#include "strcase.h"
-#include "strerror.h"
-#include "escape.h"
-#include "strtok.h"
-#include "share.h"
-#include "content_encoding.h"
-#include "http_digest.h"
-#include "http_negotiate.h"
-#include "select.h"
-#include "multiif.h"
-#include "easyif.h"
-#include "speedcheck.h"
-#include "warnless.h"
-#include "non-ascii.h"
-#include "inet_pton.h"
+#include "strerror.h"
+#include "escape.h"
+#include "strtok.h"
+#include "share.h"
+#include "content_encoding.h"
+#include "http_digest.h"
+#include "http_negotiate.h"
+#include "select.h"
+#include "multiif.h"
+#include "easyif.h"
+#include "speedcheck.h"
+#include "warnless.h"
+#include "non-ascii.h"
+#include "inet_pton.h"
#include "getinfo.h"
#include "urlapi-int.h"
#include "system_win32.h"
#include "hsts.h"
-
-/* And now for the protocols */
-#include "ftp.h"
-#include "dict.h"
-#include "telnet.h"
-#include "tftp.h"
-#include "http.h"
+
+/* And now for the protocols */
+#include "ftp.h"
+#include "dict.h"
+#include "telnet.h"
+#include "tftp.h"
+#include "http.h"
#include "http2.h"
-#include "file.h"
-#include "curl_ldap.h"
+#include "file.h"
+#include "curl_ldap.h"
#include "vssh/ssh.h"
-#include "imap.h"
-#include "url.h"
-#include "connect.h"
-#include "inet_ntop.h"
+#include "imap.h"
+#include "url.h"
+#include "connect.h"
+#include "inet_ntop.h"
#include "http_ntlm.h"
-#include "curl_rtmp.h"
-#include "gopher.h"
+#include "curl_rtmp.h"
+#include "gopher.h"
#include "mqtt.h"
-#include "http_proxy.h"
-#include "conncache.h"
-#include "multihandle.h"
-#include "dotdot.h"
+#include "http_proxy.h"
+#include "conncache.h"
+#include "multihandle.h"
+#include "dotdot.h"
#include "strdup.h"
#include "setopt.h"
#include "altsvc.h"
#include "dynbuf.h"
-
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-static void conn_free(struct connectdata *conn);
+#include "curl_memory.h"
+#include "memdebug.h"
+
+static void conn_free(struct connectdata *conn);
/* Some parts of the code (e.g. chunked encoding) assume this buffer has at
* more than just a few bytes to play with. Don't let it become too small or
@@ -159,38 +159,38 @@ static unsigned int get_protocol_family(const struct Curl_handler *h)
}
-/*
+/*
* Protocol table. Schemes (roughly) in 2019 popularity order:
*
* HTTPS, HTTP, FTP, FTPS, SFTP, FILE, SCP, SMTP, LDAP, IMAPS, TELNET, IMAP,
* LDAPS, SMTPS, TFTP, SMB, POP3, GOPHER POP3S, RTSP, RTMP, SMBS, DICT
- */
-static const struct Curl_handler * const protocols[] = {
-
+ */
+static const struct Curl_handler * const protocols[] = {
+
#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
&Curl_handler_https,
#endif
-#ifndef CURL_DISABLE_HTTP
- &Curl_handler_http,
-#endif
-
-#ifndef CURL_DISABLE_FTP
- &Curl_handler_ftp,
-#endif
-
-#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
- &Curl_handler_ftps,
-#endif
-
+#ifndef CURL_DISABLE_HTTP
+ &Curl_handler_http,
+#endif
+
+#ifndef CURL_DISABLE_FTP
+ &Curl_handler_ftp,
+#endif
+
+#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
+ &Curl_handler_ftps,
+#endif
+
#if defined(USE_SSH)
&Curl_handler_sftp,
-#endif
-
+#endif
+
#ifndef CURL_DISABLE_FILE
&Curl_handler_file,
-#endif
-
+#endif
+
#if defined(USE_SSH) && !defined(USE_WOLFSSH)
&Curl_handler_scp,
#endif
@@ -202,37 +202,37 @@ static const struct Curl_handler * const protocols[] = {
#endif
#endif
-#ifndef CURL_DISABLE_LDAP
- &Curl_handler_ldap,
-#if !defined(CURL_DISABLE_LDAPS) && \
- ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
- (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
- &Curl_handler_ldaps,
-#endif
-#endif
-
+#ifndef CURL_DISABLE_LDAP
+ &Curl_handler_ldap,
+#if !defined(CURL_DISABLE_LDAPS) && \
+ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
+ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
+ &Curl_handler_ldaps,
+#endif
+#endif
+
#ifndef CURL_DISABLE_IMAP
&Curl_handler_imap,
#ifdef USE_SSL
&Curl_handler_imaps,
-#endif
-#endif
-
+#endif
+#endif
+
#ifndef CURL_DISABLE_TELNET
&Curl_handler_telnet,
#endif
#ifndef CURL_DISABLE_TFTP
&Curl_handler_tftp,
-#endif
-
-#ifndef CURL_DISABLE_POP3
- &Curl_handler_pop3,
-#ifdef USE_SSL
- &Curl_handler_pop3s,
-#endif
-#endif
-
+#endif
+
+#ifndef CURL_DISABLE_POP3
+ &Curl_handler_pop3,
+#ifdef USE_SSL
+ &Curl_handler_pop3s,
+#endif
+#endif
+
#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \
(CURL_SIZEOF_CURL_OFF_T > 4)
&Curl_handler_smb,
@@ -241,91 +241,91 @@ static const struct Curl_handler * const protocols[] = {
#endif
#endif
-#ifndef CURL_DISABLE_RTSP
- &Curl_handler_rtsp,
-#endif
-
+#ifndef CURL_DISABLE_RTSP
+ &Curl_handler_rtsp,
+#endif
+
#ifndef CURL_DISABLE_MQTT
&Curl_handler_mqtt,
#endif
-#ifndef CURL_DISABLE_GOPHER
- &Curl_handler_gopher,
-#endif
-
-#ifdef USE_LIBRTMP
- &Curl_handler_rtmp,
- &Curl_handler_rtmpt,
- &Curl_handler_rtmpe,
- &Curl_handler_rtmpte,
- &Curl_handler_rtmps,
- &Curl_handler_rtmpts,
-#endif
-
+#ifndef CURL_DISABLE_GOPHER
+ &Curl_handler_gopher,
+#endif
+
+#ifdef USE_LIBRTMP
+ &Curl_handler_rtmp,
+ &Curl_handler_rtmpt,
+ &Curl_handler_rtmpe,
+ &Curl_handler_rtmpte,
+ &Curl_handler_rtmps,
+ &Curl_handler_rtmpts,
+#endif
+
#ifndef CURL_DISABLE_DICT
&Curl_handler_dict,
#endif
- (struct Curl_handler *) NULL
-};
-
-/*
- * Dummy handler for undefined protocol schemes.
- */
-
-static const struct Curl_handler Curl_handler_dummy = {
- "<no protocol>", /* scheme */
- ZERO_NULL, /* setup_connection */
- ZERO_NULL, /* do_it */
- ZERO_NULL, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
+ (struct Curl_handler *) NULL
+};
+
+/*
+ * Dummy handler for undefined protocol schemes.
+ */
+
+static const struct Curl_handler Curl_handler_dummy = {
+ "<no protocol>", /* scheme */
+ ZERO_NULL, /* setup_connection */
+ ZERO_NULL, /* do_it */
+ ZERO_NULL, /* done */
+ ZERO_NULL, /* do_more */
+ ZERO_NULL, /* connect_it */
+ ZERO_NULL, /* connecting */
+ ZERO_NULL, /* doing */
+ ZERO_NULL, /* proto_getsock */
+ ZERO_NULL, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ ZERO_NULL, /* perform_getsock */
+ ZERO_NULL, /* disconnect */
+ ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
- 0, /* defport */
- 0, /* protocol */
+ 0, /* defport */
+ 0, /* protocol */
0, /* family */
- PROTOPT_NONE /* flags */
-};
-
+ PROTOPT_NONE /* flags */
+};
+
void Curl_freeset(struct Curl_easy *data)
-{
- /* Free all dynamic strings stored in the data->set substructure. */
- enum dupstring i;
+{
+ /* Free all dynamic strings stored in the data->set substructure. */
+ enum dupstring i;
enum dupblob j;
for(i = (enum dupstring)0; i < STRING_LAST; i++) {
- Curl_safefree(data->set.str[i]);
+ Curl_safefree(data->set.str[i]);
}
-
+
for(j = (enum dupblob)0; j < BLOB_LAST; j++) {
Curl_safefree(data->set.blobs[j]);
}
- if(data->change.referer_alloc) {
- Curl_safefree(data->change.referer);
- data->change.referer_alloc = FALSE;
- }
- data->change.referer = NULL;
+ if(data->change.referer_alloc) {
+ Curl_safefree(data->change.referer);
+ data->change.referer_alloc = FALSE;
+ }
+ data->change.referer = NULL;
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
- }
+ }
data->change.url = NULL;
-
+
Curl_mime_cleanpart(&data->set.mimepost);
-}
-
+}
+
/* free the URL pieces */
static void up_free(struct Curl_easy *data)
-{
+{
struct urlpieces *up = &data->state.up;
Curl_safefree(up->scheme);
Curl_safefree(up->hostname);
@@ -337,74 +337,74 @@ static void up_free(struct Curl_easy *data)
Curl_safefree(up->query);
curl_url_cleanup(data->state.uh);
data->state.uh = NULL;
-}
-
-/*
- * This is the internal function curl_easy_cleanup() calls. This should
- * cleanup and free all resources associated with this sessionhandle.
- *
- * NOTE: if we ever add something that attempts to write to a socket or
- * similar here, we must ignore SIGPIPE first. It is currently only done
- * when curl_easy_perform() is invoked.
- */
-
+}
+
+/*
+ * This is the internal function curl_easy_cleanup() calls. This should
+ * cleanup and free all resources associated with this sessionhandle.
+ *
+ * NOTE: if we ever add something that attempts to write to a socket or
+ * similar here, we must ignore SIGPIPE first. It is currently only done
+ * when curl_easy_perform() is invoked.
+ */
+
CURLcode Curl_close(struct Curl_easy **datap)
-{
- struct Curl_multi *m;
+{
+ struct Curl_multi *m;
struct Curl_easy *data;
-
+
if(!datap || !*datap)
- return CURLE_OK;
-
+ return CURLE_OK;
+
data = *datap;
*datap = NULL;
Curl_expire_clear(data); /* shut off timers */
-
- m = data->multi;
- if(m)
- /* This handle is still part of a multi handle, take care of this first
- and detach this handle from there. */
- curl_multi_remove_handle(data->multi, data);
-
+
+ m = data->multi;
+ if(m)
+ /* This handle is still part of a multi handle, take care of this first
+ and detach this handle from there. */
+ curl_multi_remove_handle(data->multi, data);
+
if(data->multi_easy) {
- /* when curl_easy_perform() is used, it creates its own multi handle to
- use and this is the one */
- curl_multi_cleanup(data->multi_easy);
+ /* when curl_easy_perform() is used, it creates its own multi handle to
+ use and this is the one */
+ curl_multi_cleanup(data->multi_easy);
data->multi_easy = NULL;
}
-
- /* Destroy the timeout list that is held in the easy handle. It is
- /normally/ done by curl_multi_remove_handle() but this is "just in
- case" */
+
+ /* Destroy the timeout list that is held in the easy handle. It is
+ /normally/ done by curl_multi_remove_handle() but this is "just in
+ case" */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
-
- data->magic = 0; /* force a clear AFTER the possibly enforced removal from
- the multi handle, since that function uses the magic
- field! */
-
- if(data->state.rangestringalloc)
- free(data->state.range);
-
- /* freed here just in case DONE wasn't called */
- Curl_free_request_state(data);
-
- /* Close down all open SSL info and sessions */
- Curl_ssl_close_all(data);
- Curl_safefree(data->state.first_host);
- Curl_safefree(data->state.scratch);
- Curl_ssl_free_certinfo(data);
-
+
+ data->magic = 0; /* force a clear AFTER the possibly enforced removal from
+ the multi handle, since that function uses the magic
+ field! */
+
+ if(data->state.rangestringalloc)
+ free(data->state.range);
+
+ /* freed here just in case DONE wasn't called */
+ Curl_free_request_state(data);
+
+ /* Close down all open SSL info and sessions */
+ Curl_ssl_close_all(data);
+ Curl_safefree(data->state.first_host);
+ Curl_safefree(data->state.scratch);
+ Curl_ssl_free_certinfo(data);
+
/* Cleanup possible redirect junk */
free(data->req.newurl);
data->req.newurl = NULL;
- if(data->change.referer_alloc) {
- Curl_safefree(data->change.referer);
- data->change.referer_alloc = FALSE;
- }
- data->change.referer = NULL;
-
+ if(data->change.referer_alloc) {
+ Curl_safefree(data->change.referer);
+ data->change.referer_alloc = FALSE;
+ }
+ data->change.referer = NULL;
+
up_free(data);
Curl_safefree(data->state.buffer);
Curl_dyn_free(&data->state.headerb);
@@ -417,22 +417,22 @@ CURLcode Curl_close(struct Curl_easy **datap)
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
Curl_http_auth_cleanup_digest(data);
#endif
- Curl_safefree(data->info.contenttype);
- Curl_safefree(data->info.wouldredirect);
-
- /* this destroys the channel and we cannot use it anymore after this */
- Curl_resolver_cleanup(data->state.resolver);
-
+ Curl_safefree(data->info.contenttype);
+ Curl_safefree(data->info.wouldredirect);
+
+ /* this destroys the channel and we cannot use it anymore after this */
+ Curl_resolver_cleanup(data->state.resolver);
+
Curl_http2_cleanup_dependencies(data);
- Curl_convert_close(data);
-
- /* No longer a dirty share, if it exists */
- if(data->share) {
- Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
- data->share->dirty--;
- Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
- }
-
+ Curl_convert_close(data);
+
+ /* No longer a dirty share, if it exists */
+ if(data->share) {
+ Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
+ data->share->dirty--;
+ Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
+ }
+
Curl_safefree(data->state.aptr.proxyuserpwd);
Curl_safefree(data->state.aptr.uagent);
Curl_safefree(data->state.aptr.userpwd);
@@ -452,106 +452,106 @@ CURLcode Curl_close(struct Curl_easy **datap)
/* destruct wildcard structures if it is needed */
Curl_wildcard_dtor(&data->wildcard);
- Curl_freeset(data);
- free(data);
- return CURLE_OK;
-}
-
-/*
+ Curl_freeset(data);
+ free(data);
+ return CURLE_OK;
+}
+
+/*
* Initialize the UserDefined fields within a Curl_easy.
* This may be safely called on a new or existing Curl_easy.
- */
+ */
CURLcode Curl_init_userdefined(struct Curl_easy *data)
-{
+{
struct UserDefined *set = &data->set;
CURLcode result = CURLE_OK;
-
- set->out = stdout; /* default output to stdout */
+
+ set->out = stdout; /* default output to stdout */
set->in_set = stdin; /* default input from stdin */
- set->err = stderr; /* default stderr to stderr */
-
- /* use fwrite as default function to store output */
- set->fwrite_func = (curl_write_callback)fwrite;
-
- /* use fread as default function to read input */
+ set->err = stderr; /* default stderr to stderr */
+
+ /* use fwrite as default function to store output */
+ set->fwrite_func = (curl_write_callback)fwrite;
+
+ /* use fread as default function to read input */
set->fread_func_set = (curl_read_callback)fread;
- set->is_fread_set = 0;
- set->is_fwrite_set = 0;
-
- set->seek_func = ZERO_NULL;
- set->seek_client = ZERO_NULL;
-
- /* conversion callbacks for non-ASCII hosts */
- set->convfromnetwork = ZERO_NULL;
- set->convtonetwork = ZERO_NULL;
- set->convfromutf8 = ZERO_NULL;
-
+ set->is_fread_set = 0;
+ set->is_fwrite_set = 0;
+
+ set->seek_func = ZERO_NULL;
+ set->seek_client = ZERO_NULL;
+
+ /* conversion callbacks for non-ASCII hosts */
+ set->convfromnetwork = ZERO_NULL;
+ set->convtonetwork = ZERO_NULL;
+ set->convfromutf8 = ZERO_NULL;
+
set->filesize = -1; /* we don't know the size */
- set->postfieldsize = -1; /* unknown size */
- set->maxredirs = -1; /* allow any amount by default */
-
+ set->postfieldsize = -1; /* unknown size */
+ set->maxredirs = -1; /* allow any amount by default */
+
set->method = HTTPREQ_GET; /* Default HTTP request */
- set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
+ set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
#ifndef CURL_DISABLE_FTP
- set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
- set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
- set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
- set->ftp_filemethod = FTPFILE_MULTICWD;
+ set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
+ set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
+ set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
+ set->ftp_filemethod = FTPFILE_MULTICWD;
set->ftp_skip_ip = TRUE; /* skip PASV IP by default */
#endif
- set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
-
- /* Set the default size of the SSL session ID cache */
+ set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
+
+ /* Set the default size of the SSL session ID cache */
set->general_ssl.max_ssl_sessions = 5;
-
+
set->proxyport = 0;
- set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
- set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
- set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
-
+ set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
+ set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
+ set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
+
/* SOCKS5 proxy auth defaults to username/password + GSS-API */
set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
- /* make libcurl quiet by default: */
- set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
-
+ /* make libcurl quiet by default: */
+ set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
+
Curl_mime_initpart(&set->mimepost, data);
- /*
- * libcurl 7.10 introduced SSL verification *by default*! This needs to be
- * switched off unless wanted.
- */
+ /*
+ * libcurl 7.10 introduced SSL verification *by default*! This needs to be
+ * switched off unless wanted.
+ */
set->ssl.primary.verifypeer = TRUE;
set->ssl.primary.verifyhost = TRUE;
-#ifdef USE_TLS_SRP
- set->ssl.authtype = CURL_TLSAUTH_NONE;
-#endif
- set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
- type */
+#ifdef USE_TLS_SRP
+ set->ssl.authtype = CURL_TLSAUTH_NONE;
+#endif
+ set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
+ type */
set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
default */
#ifndef CURL_DISABLE_PROXY
set->proxy_ssl = set->ssl;
#endif
-
- set->new_file_perms = 0644; /* Default permissions */
- set->new_directory_perms = 0755; /* Default permissions */
-
- /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
- define since we internally only use the lower 16 bits for the passed
- in bitmask to not conflict with the private bits */
- set->allowed_protocols = CURLPROTO_ALL;
+
+ set->new_file_perms = 0644; /* Default permissions */
+ set->new_directory_perms = 0755; /* Default permissions */
+
+ /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
+ define since we internally only use the lower 16 bits for the passed
+ in bitmask to not conflict with the private bits */
+ set->allowed_protocols = CURLPROTO_ALL;
set->redir_protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP |
CURLPROTO_FTPS;
-
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
- /*
- * disallow unprotected protection negotiation NEC reference implementation
- * seem not to follow rfc1961 section 4.3/4.4
- */
- set->socks5_gssapi_nec = FALSE;
-#endif
-
+
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+ /*
+ * disallow unprotected protection negotiation NEC reference implementation
+ * seem not to follow rfc1961 section 4.3/4.4
+ */
+ set->socks5_gssapi_nec = FALSE;
+#endif
+
/* Set the default CA cert bundle/path detected/specified at build time.
*
* If Schannel is the selected SSL backend then these locations are
@@ -559,7 +559,7 @@ CURLcode Curl_init_userdefined(struct Curl_easy *data)
* specified by the user via CURLOPT_CAINFO / --cacert.
*/
if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) {
-#if defined(CURL_CA_BUNDLE)
+#if defined(CURL_CA_BUNDLE)
result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
if(result)
return result;
@@ -568,12 +568,12 @@ CURLcode Curl_init_userdefined(struct Curl_easy *data)
CURL_CA_BUNDLE);
if(result)
return result;
-#endif
+#endif
#if defined(CURL_CA_PATH)
result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
if(result)
return result;
-
+
result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
if(result)
return result;
@@ -581,11 +581,11 @@ CURLcode Curl_init_userdefined(struct Curl_easy *data)
}
set->wildcard_enabled = FALSE;
- set->chunk_bgn = ZERO_NULL;
- set->chunk_end = ZERO_NULL;
- set->tcp_keepalive = FALSE;
- set->tcp_keepintvl = 60;
- set->tcp_keepidle = 60;
+ set->chunk_bgn = ZERO_NULL;
+ set->chunk_end = ZERO_NULL;
+ set->tcp_keepalive = FALSE;
+ set->tcp_keepintvl = 60;
+ set->tcp_keepidle = 60;
set->tcp_fastopen = FALSE;
set->tcp_nodelay = TRUE;
set->ssl_enable_npn = TRUE;
@@ -609,67 +609,67 @@ CURLcode Curl_init_userdefined(struct Curl_easy *data)
;
Curl_http2_init_userset(set);
return result;
-}
-
-/**
- * Curl_open()
- *
- * @param curl is a pointer to a sessionhandle pointer that gets set by this
- * function.
- * @return CURLcode
- */
-
+}
+
+/**
+ * Curl_open()
+ *
+ * @param curl is a pointer to a sessionhandle pointer that gets set by this
+ * function.
+ * @return CURLcode
+ */
+
CURLcode Curl_open(struct Curl_easy **curl)
-{
+{
CURLcode result;
struct Curl_easy *data;
-
- /* Very simple start-up: alloc the struct, init it with zeroes and return */
+
+ /* Very simple start-up: alloc the struct, init it with zeroes and return */
data = calloc(1, sizeof(struct Curl_easy));
- if(!data) {
- /* this is a very serious error */
+ if(!data) {
+ /* this is a very serious error */
DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
- return CURLE_OUT_OF_MEMORY;
- }
-
- data->magic = CURLEASY_MAGIC_NUMBER;
-
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ data->magic = CURLEASY_MAGIC_NUMBER;
+
result = Curl_resolver_init(data, &data->state.resolver);
if(result) {
- DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
- free(data);
+ DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
+ free(data);
return result;
- }
-
+ }
+
result = Curl_init_userdefined(data);
if(!result) {
Curl_dyn_init(&data->state.headerb, CURL_MAX_HTTP_HEADER);
Curl_convert_init(data);
Curl_initinfo(data);
-
+
/* most recent connection is not yet defined */
data->state.lastconnect_id = -1;
-
+
data->progress.flags |= PGRS_HIDE;
data->state.current_speed = -1; /* init to negative == impossible */
- }
-
+ }
+
if(result) {
- Curl_resolver_cleanup(data->state.resolver);
+ Curl_resolver_cleanup(data->state.resolver);
Curl_dyn_free(&data->state.headerb);
- Curl_freeset(data);
- free(data);
- data = NULL;
- }
- else
- *curl = data;
-
+ Curl_freeset(data);
+ free(data);
+ data = NULL;
+ }
+ else
+ *curl = data;
+
return result;
-}
-
+}
+
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
static void conn_reset_postponed_data(struct connectdata *conn, int num)
-{
+{
struct postponed_data * const psnd = &(conn->postponed[num]);
if(psnd->buffer) {
DEBUGASSERT(psnd->allocated_size > 0);
@@ -686,51 +686,51 @@ static void conn_reset_postponed_data(struct connectdata *conn, int num)
#ifdef DEBUGBUILD
psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
#endif /* DEBUGBUILD */
- }
+ }
else {
DEBUGASSERT(psnd->allocated_size == 0);
DEBUGASSERT(psnd->recv_size == 0);
DEBUGASSERT(psnd->recv_processed == 0);
DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
- }
+ }
}
-
+
static void conn_reset_all_postponed_data(struct connectdata *conn)
{
conn_reset_postponed_data(conn, 0);
conn_reset_postponed_data(conn, 1);
-}
+}
#else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
/* Use "do-nothing" macro instead of function when workaround not used */
#define conn_reset_all_postponed_data(c) do {} while(0)
#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
-
+
static void conn_shutdown(struct connectdata *conn)
-{
+{
DEBUGASSERT(conn);
infof(conn->data, "Closing connection %ld\n", conn->connection_id);
DEBUGASSERT(conn->data);
- /* possible left-overs from the async name resolvers */
- Curl_resolver_cancel(conn);
-
- /* close the SSL stuff before we close any sockets since they will/may
- write to the sockets */
- Curl_ssl_close(conn, FIRSTSOCKET);
- Curl_ssl_close(conn, SECONDARYSOCKET);
-
- /* close possibly still open sockets */
- if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
- Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
- if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
- Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
+ /* possible left-overs from the async name resolvers */
+ Curl_resolver_cancel(conn);
+
+ /* close the SSL stuff before we close any sockets since they will/may
+ write to the sockets */
+ Curl_ssl_close(conn, FIRSTSOCKET);
+ Curl_ssl_close(conn, SECONDARYSOCKET);
+
+ /* close possibly still open sockets */
+ if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
+ Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
+ if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
+ Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
if(CURL_SOCKET_BAD != conn->tempsock[0])
Curl_closesocket(conn, conn->tempsock[0]);
if(CURL_SOCKET_BAD != conn->tempsock[1])
Curl_closesocket(conn, conn->tempsock[1]);
}
-
+
static void conn_free(struct connectdata *conn)
{
DEBUGASSERT(conn);
@@ -748,22 +748,22 @@ static void conn_free(struct connectdata *conn)
Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
#endif
- Curl_safefree(conn->user);
- Curl_safefree(conn->passwd);
+ Curl_safefree(conn->user);
+ Curl_safefree(conn->passwd);
Curl_safefree(conn->sasl_authzid);
- Curl_safefree(conn->options);
+ Curl_safefree(conn->options);
Curl_dyn_free(&conn->trailer);
- Curl_safefree(conn->host.rawalloc); /* host name buffer */
+ Curl_safefree(conn->host.rawalloc); /* host name buffer */
Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
Curl_safefree(conn->hostname_resolve);
Curl_safefree(conn->secondaryhostname);
Curl_safefree(conn->connect_state);
-
+
conn_reset_all_postponed_data(conn);
Curl_llist_destroy(&conn->easyq, NULL);
- Curl_safefree(conn->localdev);
+ Curl_safefree(conn->localdev);
Curl_free_primary_ssl_config(&conn->ssl_config);
-
+
#ifdef USE_UNIX_SOCKETS
Curl_safefree(conn->unix_domain_socket);
#endif
@@ -771,9 +771,9 @@ static void conn_free(struct connectdata *conn)
#ifdef USE_SSL
Curl_safefree(conn->ssl_extra);
#endif
- free(conn); /* free all the connection oriented data */
-}
-
+ free(conn); /* free all the connection oriented data */
+}
+
/*
* Disconnects the given connection. Note the connection may not be the
* primary connection, like when freeing room in the connection cache or
@@ -790,13 +790,13 @@ static void conn_free(struct connectdata *conn)
CURLcode Curl_disconnect(struct Curl_easy *data,
struct connectdata *conn, bool dead_connection)
-{
+{
/* there must be a connection to close */
DEBUGASSERT(conn);
-
+
/* it must be removed from the connection cache */
DEBUGASSERT(!conn->bundle);
-
+
/* there must be an associated transfer */
DEBUGASSERT(data);
@@ -812,17 +812,17 @@ CURLcode Curl_disconnect(struct Curl_easy *data,
return CURLE_OK;
}
- if(conn->dns_entry != NULL) {
- Curl_resolv_unlock(data, conn->dns_entry);
- conn->dns_entry = NULL;
- }
-
- /* Cleanup NTLM connection-related data */
+ if(conn->dns_entry != NULL) {
+ Curl_resolv_unlock(data, conn->dns_entry);
+ conn->dns_entry = NULL;
+ }
+
+ /* Cleanup NTLM connection-related data */
Curl_http_auth_cleanup_ntlm(conn);
/* Cleanup NEGOTIATE connection-related data */
Curl_http_auth_cleanup_negotiate(conn);
-
+
/* the protocol specific disconnect handler and conn_shutdown need a transfer
for the connection! */
conn->data = data;
@@ -831,33 +831,33 @@ CURLcode Curl_disconnect(struct Curl_easy *data,
/* treat the connection as dead in CONNECT_ONLY situations */
dead_connection = TRUE;
- if(conn->handler->disconnect)
- /* This is set if protocol-specific cleanups should be made */
- conn->handler->disconnect(conn, dead_connection);
-
+ if(conn->handler->disconnect)
+ /* This is set if protocol-specific cleanups should be made */
+ conn->handler->disconnect(conn, dead_connection);
+
conn_shutdown(conn);
- conn_free(conn);
- return CURLE_OK;
-}
-
-/*
- * This function should return TRUE if the socket is to be assumed to
- * be dead. Most commonly this happens when the server has closed the
- * connection due to inactivity.
- */
-static bool SocketIsDead(curl_socket_t sock)
-{
- int sval;
- bool ret_val = TRUE;
-
+ conn_free(conn);
+ return CURLE_OK;
+}
+
+/*
+ * This function should return TRUE if the socket is to be assumed to
+ * be dead. Most commonly this happens when the server has closed the
+ * connection due to inactivity.
+ */
+static bool SocketIsDead(curl_socket_t sock)
+{
+ int sval;
+ bool ret_val = TRUE;
+
sval = SOCKET_READABLE(sock, 0);
- if(sval == 0)
- /* timeout */
- ret_val = FALSE;
-
- return ret_val;
-}
-
+ if(sval == 0)
+ /* timeout */
+ ret_val = FALSE;
+
+ return ret_val;
+}
+
/*
* IsMultiplexingPossible()
*
@@ -866,33 +866,33 @@ static bool SocketIsDead(curl_socket_t sock)
*/
static int IsMultiplexingPossible(const struct Curl_easy *handle,
const struct connectdata *conn)
-{
+{
int avail = 0;
-
+
/* If a HTTP protocol and multiplexing is enabled */
if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
(!conn->bits.protoconnstart || !conn->bits.close)) {
-
+
if(Curl_multiplex_wanted(handle->multi) &&
(handle->set.httpversion >= CURL_HTTP_VERSION_2))
/* allows HTTP/2 */
avail |= CURLPIPE_MULTIPLEX;
}
return avail;
-}
-
+}
+
#ifndef CURL_DISABLE_PROXY
static bool
proxy_info_matches(const struct proxy_info *data,
const struct proxy_info *needle)
-{
+{
if((data->proxytype == needle->proxytype) &&
(data->port == needle->port) &&
Curl_safe_strcasecompare(data->host.name, needle->host.name))
return TRUE;
-
+
return FALSE;
-}
+}
static bool
socks_proxy_info_matches(const struct proxy_info *data,
@@ -925,7 +925,7 @@ socks_proxy_info_matches(const struct proxy_info *data,
#define proxy_info_matches(x,y) FALSE
#define socks_proxy_info_matches(x,y) FALSE
#endif
-
+
/* A connection has to have been idle for a shorter time than 'maxage_conn' to
be subject for reuse. The success rate is just too low after this. */
@@ -946,18 +946,18 @@ static bool conn_maxage(struct Curl_easy *data,
return FALSE;
}
-/*
+/*
* This function checks if the given connection is dead and extracts it from
* the connection cache if so.
- *
+ *
* When this is called as a Curl_conncache_foreach() callback, the connection
* cache lock is held!
*
* Returns TRUE if the connection was dead and extracted.
- */
+ */
static bool extract_if_dead(struct connectdata *conn,
struct Curl_easy *data)
-{
+{
if(!CONN_INUSE(conn) && !conn->data) {
/* The check for a dead socket makes sense only if the connection isn't in
use */
@@ -980,27 +980,27 @@ static bool extract_if_dead(struct connectdata *conn,
/* Use the general method for determining the death of a connection */
dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
}
-
+
if(dead) {
infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
Curl_conncache_remove_conn(data, conn, FALSE);
return TRUE;
- }
- }
+ }
+ }
return FALSE;
-}
-
+}
+
struct prunedead {
struct Curl_easy *data;
struct connectdata *extracted;
};
-/*
+/*
* Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
- *
- */
+ *
+ */
static int call_extract_if_dead(struct connectdata *conn, void *param)
-{
+{
struct prunedead *p = (struct prunedead *)param;
if(extract_if_dead(conn, p->data)) {
/* stop the iteration here, pass back the connection that was extracted */
@@ -1009,7 +1009,7 @@ static int call_extract_if_dead(struct connectdata *conn, void *param)
}
return 0; /* continue iteration */
}
-
+
/*
* This function scans the connection cache for half-open/dead connections,
* closes and removes them.
@@ -1024,7 +1024,7 @@ static void prune_dead_connections(struct Curl_easy *data)
elapsed =
Curl_timediff(now, data->state.conn_cache->last_cleanup);
CONNCACHE_UNLOCK(data);
-
+
if(elapsed >= 1000L) {
struct prunedead prune;
prune.data = data;
@@ -1038,38 +1038,38 @@ static void prune_dead_connections(struct Curl_easy *data)
/* disconnect it */
(void)Curl_disconnect(data, prune.extracted, TRUE);
- }
+ }
CONNCACHE_LOCK(data);
data->state.conn_cache->last_cleanup = now;
CONNCACHE_UNLOCK(data);
- }
+ }
}
-
-/*
- * Given one filled in connection struct (named needle), this function should
- * detect if there already is one that has all the significant details
- * exactly the same and thus should be used instead.
- *
- * If there is a match, this function returns TRUE - and has marked the
- * connection as 'in-use'. It must later be called with ConnectionDone() to
- * return back to 'idle' (unused) state.
- *
+
+/*
+ * Given one filled in connection struct (named needle), this function should
+ * detect if there already is one that has all the significant details
+ * exactly the same and thus should be used instead.
+ *
+ * If there is a match, this function returns TRUE - and has marked the
+ * connection as 'in-use'. It must later be called with ConnectionDone() to
+ * return back to 'idle' (unused) state.
+ *
* The force_reuse flag is set if the connection must be used.
- */
-static bool
+ */
+static bool
ConnectionExists(struct Curl_easy *data,
- struct connectdata *needle,
- struct connectdata **usethis,
+ struct connectdata *needle,
+ struct connectdata **usethis,
bool *force_reuse,
bool *waitpipe)
-{
- struct connectdata *check;
- struct connectdata *chosen = 0;
+{
+ struct connectdata *check;
+ struct connectdata *chosen = 0;
bool foundPendingCandidate = FALSE;
bool canmultiplex = IsMultiplexingPossible(data, needle);
- struct connectbundle *bundle;
+ struct connectbundle *bundle;
const char *hostbundle;
-
+
#ifdef USE_NTLM
bool wantNTLMhttp = ((data->state.authhost.want &
(CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
@@ -1084,21 +1084,21 @@ ConnectionExists(struct Curl_easy *data,
#endif
#endif
- *force_reuse = FALSE;
+ *force_reuse = FALSE;
*waitpipe = FALSE;
-
+
/* Look up the bundle with all the connections to this particular host.
Locks the connection cache, beware of early returns! */
bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache,
&hostbundle);
- if(bundle) {
+ if(bundle) {
/* Max pipe length is zero (unlimited) for multiplexed connections */
struct Curl_llist_element *curr;
-
+
infof(data, "Found bundle for host %s: %p [%s]\n",
hostbundle, (void *)bundle, (bundle->multiuse == BUNDLE_MULTIPLEX ?
"can multiplex" : "serially"));
-
+
/* We can't multiplex if we don't know anything about the server */
if(canmultiplex) {
if(bundle->multiuse == BUNDLE_UNKNOWN) {
@@ -1121,63 +1121,63 @@ ConnectionExists(struct Curl_easy *data,
infof(data, "Can not multiplex, even if we wanted to!\n");
canmultiplex = FALSE;
}
- }
-
+ }
+
curr = bundle->conn_list.head;
- while(curr) {
- bool match = FALSE;
+ while(curr) {
+ bool match = FALSE;
size_t multiplexed = 0;
-
- /*
+
+ /*
* Note that if we use a HTTP proxy in normal mode (no tunneling), we
* check connections to that proxy and not to the actual remote server.
- */
- check = curr->ptr;
- curr = curr->next;
-
+ */
+ check = curr->ptr;
+ curr = curr->next;
+
if(check->bits.connect_only || check->bits.close)
/* connect-only or to-be-closed connections will not be reused */
continue;
-
+
if(extract_if_dead(check, data)) {
/* disconnect it */
(void)Curl_disconnect(data, check, TRUE);
continue;
}
-
+
if(bundle->multiuse == BUNDLE_MULTIPLEX)
multiplexed = CONN_INUSE(check);
if(canmultiplex) {
;
- }
- else {
+ }
+ else {
if(multiplexed) {
- /* can only happen within multi handles, and means that another easy
- handle is using this connection */
- continue;
- }
-
- if(Curl_resolver_asynch()) {
- /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
- completed yet and until then we don't re-use this connection */
- if(!check->ip_addr_str[0]) {
- infof(data,
- "Connection #%ld is still name resolving, can't reuse\n",
- check->connection_id);
- continue;
- }
- }
-
+ /* can only happen within multi handles, and means that another easy
+ handle is using this connection */
+ continue;
+ }
+
+ if(Curl_resolver_asynch()) {
+ /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
+ completed yet and until then we don't re-use this connection */
+ if(!check->ip_addr_str[0]) {
+ infof(data,
+ "Connection #%ld is still name resolving, can't reuse\n",
+ check->connection_id);
+ continue;
+ }
+ }
+
if(check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) {
foundPendingCandidate = TRUE;
/* Don't pick a connection that hasn't connected yet */
- infof(data, "Connection #%ld isn't open enough, can't reuse\n",
- check->connection_id);
- continue;
- }
- }
-
+ infof(data, "Connection #%ld isn't open enough, can't reuse\n",
+ check->connection_id);
+ continue;
+ }
+ }
+
#ifdef USE_UNIX_SOCKETS
if(needle->unix_domain_socket) {
if(!check->unix_domain_socket)
@@ -1192,14 +1192,14 @@ ConnectionExists(struct Curl_easy *data,
continue;
#endif
- if((needle->handler->flags&PROTOPT_SSL) !=
- (check->handler->flags&PROTOPT_SSL))
- /* don't do mixed SSL and non-SSL connections */
+ if((needle->handler->flags&PROTOPT_SSL) !=
+ (check->handler->flags&PROTOPT_SSL))
+ /* don't do mixed SSL and non-SSL connections */
if(get_protocol_family(check->handler) !=
needle->handler->protocol || !check->bits.tls_upgraded)
- /* except protocols that have been upgraded via TLS */
- continue;
-
+ /* except protocols that have been upgraded via TLS */
+ continue;
+
#ifndef CURL_DISABLE_PROXY
if(needle->bits.httpproxy != check->bits.httpproxy ||
needle->bits.socksproxy != check->bits.socksproxy)
@@ -1223,7 +1223,7 @@ ConnectionExists(struct Curl_easy *data,
#ifndef CURL_DISABLE_PROXY
if(needle->bits.httpproxy) {
if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
- continue;
+ continue;
if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
continue;
@@ -1246,40 +1246,40 @@ ConnectionExists(struct Curl_easy *data,
continue;
}
}
- }
+ }
#endif
-
+
DEBUGASSERT(!check->data || GOOD_EASY_HANDLE(check->data));
if(!canmultiplex && check->data)
/* this request can't be multiplexed but the checked connection is
- already in use so we skip it */
- continue;
-
+ already in use so we skip it */
+ continue;
+
if(check->data && (check->data->multi != needle->data->multi))
/* this could be subject for multiplex use, but only if they belong to
* the same multi handle */
continue;
- if(needle->localdev || needle->localport) {
- /* If we are bound to a specific local end (IP+port), we must not
- re-use a random other one, although if we didn't ask for a
- particular one we can reuse one that was bound.
-
- This comparison is a bit rough and too strict. Since the input
- parameters can be specified in numerous ways and still end up the
- same it would take a lot of processing to make it really accurate.
- Instead, this matching will assume that re-uses of bound connections
- will most likely also re-use the exact same binding parameters and
- missing out a few edge cases shouldn't hurt anyone very much.
- */
- if((check->localport != needle->localport) ||
- (check->localportrange != needle->localportrange) ||
+ if(needle->localdev || needle->localport) {
+ /* If we are bound to a specific local end (IP+port), we must not
+ re-use a random other one, although if we didn't ask for a
+ particular one we can reuse one that was bound.
+
+ This comparison is a bit rough and too strict. Since the input
+ parameters can be specified in numerous ways and still end up the
+ same it would take a lot of processing to make it really accurate.
+ Instead, this matching will assume that re-uses of bound connections
+ will most likely also re-use the exact same binding parameters and
+ missing out a few edge cases shouldn't hurt anyone very much.
+ */
+ if((check->localport != needle->localport) ||
+ (check->localportrange != needle->localportrange) ||
(needle->localdev &&
(!check->localdev || strcmp(check->localdev, needle->localdev))))
- continue;
- }
-
+ continue;
+ }
+
if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
/* This protocol requires credentials per connection,
so verify that we're using the same name and password as well */
@@ -1288,17 +1288,17 @@ ConnectionExists(struct Curl_easy *data,
/* one of them was different */
continue;
}
- }
-
+ }
+
if((needle->handler->flags&PROTOPT_SSL)
#ifndef CURL_DISABLE_PROXY
|| !needle->bits.httpproxy || needle->bits.tunnel_proxy
#endif
) {
- /* The requested connection does not use a HTTP proxy or it uses SSL or
+ /* The requested connection does not use a HTTP proxy or it uses SSL or
it is a non-SSL protocol tunneled or it is a non-SSL protocol which
is allowed to be upgraded via TLS */
-
+
if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
(get_protocol_family(check->handler) ==
needle->handler->protocol && check->bits.tls_upgraded)) &&
@@ -1307,40 +1307,40 @@ ConnectionExists(struct Curl_easy *data,
(!needle->bits.conn_to_port ||
needle->conn_to_port == check->conn_to_port) &&
strcasecompare(needle->host.name, check->host.name) &&
- needle->remote_port == check->remote_port) {
+ needle->remote_port == check->remote_port) {
/* The schemes match or the protocol family is the same and the
previous connection was TLS upgraded, and the hostname and host
port match */
- if(needle->handler->flags & PROTOPT_SSL) {
- /* This is a SSL connection so verify that we're using the same
- SSL options as well */
- if(!Curl_ssl_config_matches(&needle->ssl_config,
- &check->ssl_config)) {
- DEBUGF(infof(data,
- "Connection #%ld has different SSL parameters, "
- "can't reuse\n",
- check->connection_id));
- continue;
- }
+ if(needle->handler->flags & PROTOPT_SSL) {
+ /* This is a SSL connection so verify that we're using the same
+ SSL options as well */
+ if(!Curl_ssl_config_matches(&needle->ssl_config,
+ &check->ssl_config)) {
+ DEBUGF(infof(data,
+ "Connection #%ld has different SSL parameters, "
+ "can't reuse\n",
+ check->connection_id));
+ continue;
+ }
if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
foundPendingCandidate = TRUE;
- DEBUGF(infof(data,
- "Connection #%ld has not started SSL connect, "
- "can't reuse\n",
- check->connection_id));
- continue;
- }
- }
- match = TRUE;
- }
- }
+ DEBUGF(infof(data,
+ "Connection #%ld has not started SSL connect, "
+ "can't reuse\n",
+ check->connection_id));
+ continue;
+ }
+ }
+ match = TRUE;
+ }
+ }
else {
/* The requested connection is using the same HTTP proxy in normal
mode (no tunneling) */
match = TRUE;
- }
-
- if(match) {
+ }
+
+ if(match) {
#if defined(USE_NTLM)
/* If we are looking for an HTTP+NTLM connection, check if this is
already authenticating with the right credentials. If not, keep
@@ -1362,7 +1362,7 @@ ConnectionExists(struct Curl_easy *data,
/* Connection is using NTLM auth but we don't want NTLM */
continue;
}
-
+
#ifndef CURL_DISABLE_PROXY
/* Same for Proxy NTLM authentication */
if(wantProxyNTLMhttp) {
@@ -1388,25 +1388,25 @@ ConnectionExists(struct Curl_easy *data,
(check->http_ntlm_state != NTLMSTATE_NONE)) ||
(wantProxyNTLMhttp &&
(check->proxy_ntlm_state != NTLMSTATE_NONE))) {
- /* We must use this connection, no other */
- *force_reuse = TRUE;
- break;
- }
+ /* We must use this connection, no other */
+ *force_reuse = TRUE;
+ break;
+ }
/* Continue look up for a better connection */
continue;
- }
+ }
#endif
if(canmultiplex) {
/* We can multiplex if we want to. Let's continue looking for
the optimal connection to use. */
-
+
if(!multiplexed) {
- /* We have the optimal connection. Let's stop looking. */
- chosen = check;
- break;
- }
-
+ /* We have the optimal connection. Let's stop looking. */
+ chosen = check;
+ break;
+ }
+
#ifdef USE_NGHTTP2
/* If multiplexed, make sure we don't go over concurrency limit */
if(check->bits.multiplex) {
@@ -1430,102 +1430,102 @@ ConnectionExists(struct Curl_easy *data,
chosen = check;
infof(data, "Multiplexed connection found!\n");
break;
- }
- else {
- /* We have found a connection. Let's stop searching. */
- chosen = check;
- break;
- }
- }
- }
- }
-
- if(chosen) {
+ }
+ else {
+ /* We have found a connection. Let's stop searching. */
+ chosen = check;
+ break;
+ }
+ }
+ }
+ }
+
+ if(chosen) {
/* mark it as used before releasing the lock */
chosen->data = data; /* own it! */
Curl_attach_connnection(data, chosen);
CONNCACHE_UNLOCK(data);
- *usethis = chosen;
- return TRUE; /* yes, we found one to use! */
- }
+ *usethis = chosen;
+ return TRUE; /* yes, we found one to use! */
+ }
CONNCACHE_UNLOCK(data);
-
+
if(foundPendingCandidate && data->set.pipewait) {
infof(data,
"Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
*waitpipe = TRUE;
- }
-
+ }
+
return FALSE; /* no matching connecting exists */
-}
-
-/*
- * verboseconnect() displays verbose information after a connect
- */
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-void Curl_verboseconnect(struct connectdata *conn)
-{
- if(conn->data->set.verbose)
- infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
+}
+
+/*
+ * verboseconnect() displays verbose information after a connect
+ */
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+void Curl_verboseconnect(struct connectdata *conn)
+{
+ if(conn->data->set.verbose)
+ infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
#ifndef CURL_DISABLE_PROXY
conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
conn->bits.httpproxy ? conn->http_proxy.host.dispname :
#endif
conn->bits.conn_to_host ? conn->conn_to_host.dispname :
conn->host.dispname,
- conn->ip_addr_str, conn->port, conn->connection_id);
-}
-#endif
-
-/*
+ conn->ip_addr_str, conn->port, conn->connection_id);
+}
+#endif
+
+/*
* Helpers for IDNA conversions.
- */
+ */
bool Curl_is_ASCII_name(const char *hostname)
-{
+{
/* get an UNSIGNED local version of the pointer */
const unsigned char *ch = (const unsigned char *)hostname;
-
+
if(!hostname) /* bad input, consider it ASCII! */
return TRUE;
- while(*ch) {
- if(*ch++ & 0x80)
- return FALSE;
- }
- return TRUE;
-}
-
-/*
+ while(*ch) {
+ if(*ch++ & 0x80)
+ return FALSE;
+ }
+ return TRUE;
+}
+
+/*
* Strip single trailing dot in the hostname,
* primarily for SNI and http host header.
- */
+ */
static void strip_trailing_dot(struct hostname *host)
-{
+{
size_t len;
if(!host || !host->name)
return;
len = strlen(host->name);
if(len && (host->name[len-1] == '.'))
host->name[len-1] = 0;
-}
-
-/*
- * Perform any necessary IDN conversion of hostname
- */
+}
+
+/*
+ * Perform any necessary IDN conversion of hostname
+ */
CURLcode Curl_idnconvert_hostname(struct connectdata *conn,
struct hostname *host)
-{
+{
struct Curl_easy *data = conn->data;
#ifndef USE_LIBIDN2
- (void)data;
- (void)conn;
-#elif defined(CURL_DISABLE_VERBOSE_STRINGS)
- (void)conn;
-#endif
-
- /* set the name we use to display the host name */
- host->dispname = host->name;
+ (void)data;
+ (void)conn;
+#elif defined(CURL_DISABLE_VERBOSE_STRINGS)
+ (void)conn;
+#endif
+
+ /* set the name we use to display the host name */
+ host->dispname = host->name;
/* Check name for non-ASCII and convert hostname to ACE form if we can */
if(!Curl_is_ASCII_name(host->name)) {
@@ -1553,26 +1553,26 @@ CURLcode Curl_idnconvert_hostname(struct connectdata *conn,
}
}
#elif defined(USE_WIN32_IDN)
- char *ace_hostname = NULL;
-
+ char *ace_hostname = NULL;
+
if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
- host->encalloc = ace_hostname;
- /* change the name pointer to point to the encoded hostname */
- host->name = host->encalloc;
- }
- else {
+ host->encalloc = ace_hostname;
+ /* change the name pointer to point to the encoded hostname */
+ host->name = host->encalloc;
+ }
+ else {
char buffer[STRERROR_LEN];
failf(data, "Failed to convert %s to ACE; %s\n", host->name,
Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer)));
return CURLE_URL_MALFORMAT;
- }
-#else
- infof(data, "IDN support not present, can't parse Unicode domains\n");
-#endif
- }
+ }
+#else
+ infof(data, "IDN support not present, can't parse Unicode domains\n");
+#endif
+ }
return CURLE_OK;
-}
-
+}
+
/*
* Frees data allocated by idnconvert_hostname()
*/
@@ -1593,15 +1593,15 @@ void Curl_free_idnconverted_hostname(struct hostname *host)
#endif
}
-/*
- * Allocate and initialize a new connectdata object.
- */
+/*
+ * Allocate and initialize a new connectdata object.
+ */
static struct connectdata *allocate_conn(struct Curl_easy *data)
-{
- struct connectdata *conn = calloc(1, sizeof(struct connectdata));
- if(!conn)
- return NULL;
-
+{
+ struct connectdata *conn = calloc(1, sizeof(struct connectdata));
+ if(!conn)
+ return NULL;
+
#ifdef USE_SSL
/* The SSL backend-specific data (ssl_backend_data) objects are allocated as
a separate array to ensure suitable alignment.
@@ -1624,50 +1624,50 @@ static struct connectdata *allocate_conn(struct Curl_easy *data)
}
#endif
- conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
- already from start to avoid NULL
- situations and checks */
-
- /* and we setup a few fields in case we end up actually using this struct */
-
- conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
- conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
+ conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
+ already from start to avoid NULL
+ situations and checks */
+
+ /* and we setup a few fields in case we end up actually using this struct */
+
+ conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
+ conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
- conn->connection_id = -1; /* no ID */
- conn->port = -1; /* unknown at this point */
+ conn->connection_id = -1; /* no ID */
+ conn->port = -1; /* unknown at this point */
conn->remote_port = -1; /* unknown at this point */
#if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
#endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
-
- /* Default protocol-independent behavior doesn't support persistent
- connections, so we set this to force-close. Protocols that support
- this need to set this to FALSE in their "curl_do" functions. */
+
+ /* Default protocol-independent behavior doesn't support persistent
+ connections, so we set this to force-close. Protocols that support
+ this need to set this to FALSE in their "curl_do" functions. */
connclose(conn, "Default to force-close");
-
- /* Store creation time to help future close decision making */
+
+ /* Store creation time to help future close decision making */
conn->created = Curl_now();
-
+
/* Store current time to give a baseline to keepalive connection times. */
conn->keepalive = Curl_now();
/* Store off the configured connection upkeep time. */
conn->upkeep_interval_ms = data->set.upkeep_interval_ms;
- conn->data = data; /* Setup the association between this connection
+ conn->data = data; /* Setup the association between this connection
and the Curl_easy */
-
+
#ifndef CURL_DISABLE_PROXY
conn->http_proxy.proxytype = data->set.proxytype;
conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
-
- /* note that these two proxy bits are now just on what looks to be
- requested, they may be altered down the road */
- conn->bits.proxy = (data->set.str[STRING_PROXY] &&
+
+ /* note that these two proxy bits are now just on what looks to be
+ requested, they may be altered down the road */
+ conn->bits.proxy = (data->set.str[STRING_PROXY] &&
*data->set.str[STRING_PROXY]) ? TRUE : FALSE;
- conn->bits.httpproxy = (conn->bits.proxy &&
+ conn->bits.httpproxy = (conn->bits.proxy &&
(conn->http_proxy.proxytype == CURLPROXY_HTTP ||
conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
@@ -1680,15 +1680,15 @@ static struct connectdata *allocate_conn(struct Curl_easy *data)
conn->bits.socksproxy = TRUE;
}
- conn->bits.proxy_user_passwd =
+ conn->bits.proxy_user_passwd =
(data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
- conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
-#endif /* CURL_DISABLE_PROXY */
-
+ conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
+#endif /* CURL_DISABLE_PROXY */
+
conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
#ifndef CURL_DISABLE_FTP
- conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
- conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
+ conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
+ conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
#endif
conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
@@ -1699,65 +1699,65 @@ static struct connectdata *allocate_conn(struct Curl_easy *data)
conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
#endif
- conn->ip_version = data->set.ipver;
+ conn->ip_version = data->set.ipver;
conn->bits.connect_only = data->set.connect_only;
conn->transport = TRNSPRT_TCP; /* most of them are TCP streams */
-
+
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
conn->ntlm.ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
conn->proxyntlm.ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
-#endif
-
+#endif
+
/* Initialize the easy handle list */
Curl_llist_init(&conn->easyq, NULL);
-
-#ifdef HAVE_GSSAPI
- conn->data_prot = PROT_CLEAR;
-#endif
-
- /* Store the local bind parameters that will be used for this connection */
- if(data->set.str[STRING_DEVICE]) {
- conn->localdev = strdup(data->set.str[STRING_DEVICE]);
- if(!conn->localdev)
- goto error;
- }
- conn->localportrange = data->set.localportrange;
- conn->localport = data->set.localport;
-
- /* the close socket stuff needs to be copied to the connection struct as
+
+#ifdef HAVE_GSSAPI
+ conn->data_prot = PROT_CLEAR;
+#endif
+
+ /* Store the local bind parameters that will be used for this connection */
+ if(data->set.str[STRING_DEVICE]) {
+ conn->localdev = strdup(data->set.str[STRING_DEVICE]);
+ if(!conn->localdev)
+ goto error;
+ }
+ conn->localportrange = data->set.localportrange;
+ conn->localport = data->set.localport;
+
+ /* the close socket stuff needs to be copied to the connection struct as
it may live on without (this specific) Curl_easy */
- conn->fclosesocket = data->set.fclosesocket;
- conn->closesocket_client = data->set.closesocket_client;
+ conn->fclosesocket = data->set.fclosesocket;
+ conn->closesocket_client = data->set.closesocket_client;
conn->lastused = Curl_now(); /* used now */
-
- return conn;
- error:
-
+
+ return conn;
+ error:
+
Curl_llist_destroy(&conn->easyq, NULL);
free(conn->localdev);
#ifdef USE_SSL
free(conn->ssl_extra);
#endif
free(conn);
- return NULL;
-}
-
+ return NULL;
+}
+
/* returns the handler if the given scheme is built-in */
const struct Curl_handler *Curl_builtin_scheme(const char *scheme)
-{
- const struct Curl_handler * const *pp;
- const struct Curl_handler *p;
+{
+ const struct Curl_handler * const *pp;
+ const struct Curl_handler *p;
/* Scan protocol handler table and match against 'scheme'. The handler may
be changed later when the protocol specific setup function is called. */
for(pp = protocols; (p = *pp) != NULL; pp++)
if(strcasecompare(p->scheme, scheme))
- /* Protocol found in table. Check if allowed */
+ /* Protocol found in table. Check if allowed */
return p;
return NULL; /* not found */
}
-
-
+
+
static CURLcode findprotocol(struct Curl_easy *data,
struct connectdata *conn,
const char *protostr)
@@ -1774,23 +1774,23 @@ static CURLcode findprotocol(struct Curl_easy *data,
/* nope, get out */
;
else {
- /* Perform setup complement if some. */
- conn->handler = conn->given = p;
-
- /* 'port' and 'remote_port' are set in setup_connection_internals() */
- return CURLE_OK;
- }
- }
-
- /* The protocol was not found in the table, but we don't have to assign it
- to anything since it is already assigned to a dummy-struct in the
- create_conn() function when the connectdata struct is allocated. */
+ /* Perform setup complement if some. */
+ conn->handler = conn->given = p;
+
+ /* 'port' and 'remote_port' are set in setup_connection_internals() */
+ return CURLE_OK;
+ }
+ }
+
+ /* The protocol was not found in the table, but we don't have to assign it
+ to anything since it is already assigned to a dummy-struct in the
+ create_conn() function when the connectdata struct is allocated. */
failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
- protostr);
-
- return CURLE_UNSUPPORTED_PROTOCOL;
-}
-
+ protostr);
+
+ return CURLE_UNSUPPORTED_PROTOCOL;
+}
+
CURLcode Curl_uc_to_curlcode(CURLUcode uc)
{
@@ -1806,7 +1806,7 @@ CURLcode Curl_uc_to_curlcode(CURLUcode uc)
}
}
-/*
+/*
* If the URL was set with an IPv6 numerical address with a zone id part, set
* the scope_id based on that!
*/
@@ -1851,30 +1851,30 @@ static void zonefrom_url(CURLU *uh, struct connectdata *conn)
}
/*
- * Parse URL and fill in the relevant members of the connection struct.
- */
+ * Parse URL and fill in the relevant members of the connection struct.
+ */
static CURLcode parseurlandfillconn(struct Curl_easy *data,
struct connectdata *conn)
-{
- CURLcode result;
+{
+ CURLcode result;
CURLU *uh;
CURLUcode uc;
char *hostname;
bool use_set_uh = (data->set.uh && !data->state.this_is_a_follow);
-
+
up_free(data); /* cleanup previous leftovers first */
-
+
/* parse the URL */
if(use_set_uh) {
uh = data->state.uh = curl_url_dup(data->set.uh);
- }
- else {
+ }
+ else {
uh = data->state.uh = curl_url();
}
-
+
if(!uh)
return CURLE_OUT_OF_MEMORY;
-
+
if(data->set.str[STRING_DEFAULT_PROTOCOL] &&
!Curl_is_absolute_url(data->change.url, NULL, MAX_SCHEME_LEN)) {
char *url;
@@ -1887,7 +1887,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
data->change.url = url;
data->change.url_alloc = TRUE;
}
-
+
if(!use_set_uh) {
char *newurl;
uc = curl_url_set(uh, CURLUPART_URL, data->change.url,
@@ -1910,11 +1910,11 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
data->change.url = newurl;
data->change.url_alloc = TRUE;
}
-
+
uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
-
+
uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0);
if(uc) {
if(!strcasecompare("file", data->state.up.scheme))
@@ -1949,7 +1949,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
result = findprotocol(data, conn, data->state.up.scheme);
if(result)
return result;
-
+
/* we don't use the URL API's URL decoder option here since it rejects
control codes and we want to allow them for some schemes in the user and
password fields */
@@ -1963,10 +1963,10 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
return result;
conn->user = decoded;
conn->bits.user_passwd = TRUE;
- }
+ }
else if(uc != CURLUE_NO_USER)
return Curl_uc_to_curlcode(uc);
-
+
uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password, 0);
if(!uc) {
char *decoded;
@@ -1980,34 +1980,34 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
}
else if(uc != CURLUE_NO_PASSWORD)
return Curl_uc_to_curlcode(uc);
-
+
uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options,
CURLU_URLDECODE);
if(!uc) {
conn->options = strdup(data->state.up.options);
if(!conn->options)
return CURLE_OUT_OF_MEMORY;
- }
+ }
else if(uc != CURLUE_NO_OPTIONS)
return Curl_uc_to_curlcode(uc);
-
+
uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
-
+
uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port,
CURLU_DEFAULT_PORT);
if(uc) {
if(!strcasecompare("file", data->state.up.scheme))
- return CURLE_OUT_OF_MEMORY;
+ return CURLE_OUT_OF_MEMORY;
}
else {
unsigned long port = strtoul(data->state.up.port, NULL, 10);
conn->port = conn->remote_port = curlx_ultous(port);
}
-
+
(void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0);
-
+
hostname = data->state.up.hostname;
if(hostname && hostname[0] == '[') {
/* This looks like an IPv6 address literal. See if there is an address
@@ -2020,8 +2020,8 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
hostname[hlen - 1] = 0;
zonefrom_url(uh, conn);
- }
-
+ }
+
/* make sure the connect struct gets its own copy of the host name */
conn->host.rawalloc = strdup(hostname ? hostname : "");
if(!conn->host.rawalloc)
@@ -2029,86 +2029,86 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
conn->host.name = conn->host.rawalloc;
if(data->set.scope_id)
- /* Override any scope that was set above. */
+ /* Override any scope that was set above. */
conn->scope_id = data->set.scope_id;
-
+
return CURLE_OK;
}
-
-
-/*
- * If we're doing a resumed transfer, we need to setup our stuff
- * properly.
- */
+
+
+/*
+ * If we're doing a resumed transfer, we need to setup our stuff
+ * properly.
+ */
static CURLcode setup_range(struct Curl_easy *data)
-{
- struct UrlState *s = &data->state;
- s->resume_from = data->set.set_resume_from;
- if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
- if(s->rangestringalloc)
- free(s->range);
-
- if(s->resume_from)
+{
+ struct UrlState *s = &data->state;
+ s->resume_from = data->set.set_resume_from;
+ if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
+ if(s->rangestringalloc)
+ free(s->range);
+
+ if(s->resume_from)
s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from);
- else
- s->range = strdup(data->set.str[STRING_SET_RANGE]);
-
+ else
+ s->range = strdup(data->set.str[STRING_SET_RANGE]);
+
s->rangestringalloc = (s->range) ? TRUE : FALSE;
-
- if(!s->range)
- return CURLE_OUT_OF_MEMORY;
-
- /* tell ourselves to fetch this range */
- s->use_range = TRUE; /* enable range download */
- }
- else
- s->use_range = FALSE; /* disable range download */
-
- return CURLE_OK;
-}
-
-
-/*
- * setup_connection_internals() -
- *
- * Setup connection internals specific to the requested protocol in the
+
+ if(!s->range)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* tell ourselves to fetch this range */
+ s->use_range = TRUE; /* enable range download */
+ }
+ else
+ s->use_range = FALSE; /* disable range download */
+
+ return CURLE_OK;
+}
+
+
+/*
+ * setup_connection_internals() -
+ *
+ * Setup connection internals specific to the requested protocol in the
* Curl_easy. This is inited and setup before the connection is made but
- * is about the particular protocol that is to be used.
- *
- * This MUST get called after proxy magic has been figured out.
- */
-static CURLcode setup_connection_internals(struct connectdata *conn)
-{
+ * is about the particular protocol that is to be used.
+ *
+ * This MUST get called after proxy magic has been figured out.
+ */
+static CURLcode setup_connection_internals(struct connectdata *conn)
+{
const struct Curl_handler *p;
- CURLcode result;
-
- /* Perform setup complement if some. */
- p = conn->handler;
-
- if(p->setup_connection) {
- result = (*p->setup_connection)(conn);
-
+ CURLcode result;
+
+ /* Perform setup complement if some. */
+ p = conn->handler;
+
+ if(p->setup_connection) {
+ result = (*p->setup_connection)(conn);
+
if(result)
- return result;
-
- p = conn->handler; /* May have changed. */
- }
-
- if(conn->port < 0)
- /* we check for -1 here since if proxy was detected already, this
- was very likely already set to the proxy port */
- conn->port = p->defport;
-
- return CURLE_OK;
-}
-
-/*
- * Curl_free_request_state() should free temp data that was allocated in the
+ return result;
+
+ p = conn->handler; /* May have changed. */
+ }
+
+ if(conn->port < 0)
+ /* we check for -1 here since if proxy was detected already, this
+ was very likely already set to the proxy port */
+ conn->port = p->defport;
+
+ return CURLE_OK;
+}
+
+/*
+ * Curl_free_request_state() should free temp data that was allocated in the
* Curl_easy for this single request.
- */
-
+ */
+
void Curl_free_request_state(struct Curl_easy *data)
-{
+{
Curl_safefree(data->req.p.http);
Curl_safefree(data->req.newurl);
@@ -2116,22 +2116,22 @@ void Curl_free_request_state(struct Curl_easy *data)
Curl_close(&data->req.doh.probe[0].easy);
Curl_close(&data->req.doh.probe[1].easy);
#endif
-}
-
-
-#ifndef CURL_DISABLE_PROXY
-/****************************************************************
-* Checks if the host is in the noproxy list. returns true if it matches
-* and therefore the proxy should NOT be used.
-****************************************************************/
+}
+
+
+#ifndef CURL_DISABLE_PROXY
+/****************************************************************
+* Checks if the host is in the noproxy list. returns true if it matches
+* and therefore the proxy should NOT be used.
+****************************************************************/
static bool check_noproxy(const char *name, const char *no_proxy)
-{
- /* no_proxy=domain1.dom,host.domain2.dom
- * (a comma-separated list of hosts which should
- * not be proxied, or an asterisk to override
- * all proxy variables)
- */
- if(no_proxy && no_proxy[0]) {
+{
+ /* no_proxy=domain1.dom,host.domain2.dom
+ * (a comma-separated list of hosts which should
+ * not be proxied, or an asterisk to override
+ * all proxy variables)
+ */
+ if(no_proxy && no_proxy[0]) {
size_t tok_start;
size_t tok_end;
const char *separator = ", ";
@@ -2139,107 +2139,107 @@ static bool check_noproxy(const char *name, const char *no_proxy)
size_t namelen;
char *endptr;
if(strcasecompare("*", no_proxy)) {
- return TRUE;
- }
-
- /* NO_PROXY was specified and it wasn't just an asterisk */
-
- no_proxy_len = strlen(no_proxy);
+ return TRUE;
+ }
+
+ /* NO_PROXY was specified and it wasn't just an asterisk */
+
+ no_proxy_len = strlen(no_proxy);
if(name[0] == '[') {
/* IPv6 numerical address */
endptr = strchr(name, ']');
if(!endptr)
return FALSE;
name++;
- namelen = endptr - name;
- }
- else
- namelen = strlen(name);
-
- for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
- while(tok_start < no_proxy_len &&
- strchr(separator, no_proxy[tok_start]) != NULL) {
- /* Look for the beginning of the token. */
- ++tok_start;
- }
-
- if(tok_start == no_proxy_len)
- break; /* It was all trailing separator chars, no more tokens. */
-
- for(tok_end = tok_start; tok_end < no_proxy_len &&
- strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
- /* Look for the end of the token. */
- ;
-
- /* To match previous behaviour, where it was necessary to specify
- * ".local.com" to prevent matching "notlocal.com", we will leave
- * the '.' off.
- */
- if(no_proxy[tok_start] == '.')
- ++tok_start;
-
- if((tok_end - tok_start) <= namelen) {
- /* Match the last part of the name to the domain we are checking. */
- const char *checkn = name + namelen - (tok_end - tok_start);
+ namelen = endptr - name;
+ }
+ else
+ namelen = strlen(name);
+
+ for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
+ while(tok_start < no_proxy_len &&
+ strchr(separator, no_proxy[tok_start]) != NULL) {
+ /* Look for the beginning of the token. */
+ ++tok_start;
+ }
+
+ if(tok_start == no_proxy_len)
+ break; /* It was all trailing separator chars, no more tokens. */
+
+ for(tok_end = tok_start; tok_end < no_proxy_len &&
+ strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
+ /* Look for the end of the token. */
+ ;
+
+ /* To match previous behaviour, where it was necessary to specify
+ * ".local.com" to prevent matching "notlocal.com", we will leave
+ * the '.' off.
+ */
+ if(no_proxy[tok_start] == '.')
+ ++tok_start;
+
+ if((tok_end - tok_start) <= namelen) {
+ /* Match the last part of the name to the domain we are checking. */
+ const char *checkn = name + namelen - (tok_end - tok_start);
if(strncasecompare(no_proxy + tok_start, checkn,
- tok_end - tok_start)) {
- if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
- /* We either have an exact match, or the previous character is a .
- * so it is within the same domain, so no proxy for this host.
- */
- return TRUE;
- }
- }
- } /* if((tok_end - tok_start) <= namelen) */
- } /* for(tok_start = 0; tok_start < no_proxy_len;
- tok_start = tok_end + 1) */
- } /* NO_PROXY was specified and it wasn't just an asterisk */
-
- return FALSE;
-}
-
+ tok_end - tok_start)) {
+ if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
+ /* We either have an exact match, or the previous character is a .
+ * so it is within the same domain, so no proxy for this host.
+ */
+ return TRUE;
+ }
+ }
+ } /* if((tok_end - tok_start) <= namelen) */
+ } /* for(tok_start = 0; tok_start < no_proxy_len;
+ tok_start = tok_end + 1) */
+ } /* NO_PROXY was specified and it wasn't just an asterisk */
+
+ return FALSE;
+}
+
#ifndef CURL_DISABLE_HTTP
-/****************************************************************
-* Detect what (if any) proxy to use. Remember that this selects a host
-* name and is not limited to HTTP proxies only.
-* The returned pointer must be freed by the caller (unless NULL)
-****************************************************************/
-static char *detect_proxy(struct connectdata *conn)
-{
- char *proxy = NULL;
-
- /* If proxy was not specified, we check for default proxy environment
- * variables, to enable i.e Lynx compliance:
- *
- * http_proxy=http://some.server.dom:port/
- * https_proxy=http://some.server.dom:port/
- * ftp_proxy=http://some.server.dom:port/
- * no_proxy=domain1.dom,host.domain2.dom
- * (a comma-separated list of hosts which should
- * not be proxied, or an asterisk to override
- * all proxy variables)
- * all_proxy=http://some.server.dom:port/
- * (seems to exist for the CERN www lib. Probably
- * the first to check for.)
- *
- * For compatibility, the all-uppercase versions of these variables are
- * checked if the lowercase versions don't exist.
- */
- char proxy_env[128];
+/****************************************************************
+* Detect what (if any) proxy to use. Remember that this selects a host
+* name and is not limited to HTTP proxies only.
+* The returned pointer must be freed by the caller (unless NULL)
+****************************************************************/
+static char *detect_proxy(struct connectdata *conn)
+{
+ char *proxy = NULL;
+
+ /* If proxy was not specified, we check for default proxy environment
+ * variables, to enable i.e Lynx compliance:
+ *
+ * http_proxy=http://some.server.dom:port/
+ * https_proxy=http://some.server.dom:port/
+ * ftp_proxy=http://some.server.dom:port/
+ * no_proxy=domain1.dom,host.domain2.dom
+ * (a comma-separated list of hosts which should
+ * not be proxied, or an asterisk to override
+ * all proxy variables)
+ * all_proxy=http://some.server.dom:port/
+ * (seems to exist for the CERN www lib. Probably
+ * the first to check for.)
+ *
+ * For compatibility, the all-uppercase versions of these variables are
+ * checked if the lowercase versions don't exist.
+ */
+ char proxy_env[128];
const char *protop = conn->handler->scheme;
char *envp = proxy_env;
char *prox;
-
+
/* Now, build <protocol>_proxy and check for such a one to use */
while(*protop)
*envp++ = (char)tolower((int)*protop++);
-
+
/* append _proxy */
strcpy(envp, "_proxy");
-
+
/* read the protocol proxy: */
prox = curl_getenv(proxy_env);
-
+
/*
* We don't try the uppercase version of HTTP_PROXY because of
* security reasons:
@@ -2257,7 +2257,7 @@ static char *detect_proxy(struct connectdata *conn)
Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
prox = curl_getenv(proxy_env);
}
-
+
envp = proxy_env;
if(prox) {
proxy = prox; /* use this */
@@ -2268,24 +2268,24 @@ static char *detect_proxy(struct connectdata *conn)
if(!proxy) {
envp = (char *)"ALL_PROXY";
proxy = curl_getenv(envp);
- }
+ }
}
if(proxy)
infof(conn->data, "Uses proxy env variable %s == '%s'\n", envp, proxy);
-
- return proxy;
-}
+
+ return proxy;
+}
#endif /* CURL_DISABLE_HTTP */
-
-/*
- * If this is supposed to use a proxy, we need to figure out the proxy
- * host name, so that we can re-use an existing connection
- * that may exist registered to the same proxy host.
- */
+
+/*
+ * If this is supposed to use a proxy, we need to figure out the proxy
+ * host name, so that we can re-use an existing connection
+ * that may exist registered to the same proxy host.
+ */
static CURLcode parse_proxy(struct Curl_easy *data,
struct connectdata *conn, char *proxy,
curl_proxytype proxytype)
-{
+{
char *portptr = NULL;
long port = -1;
char *proxyuser = NULL;
@@ -2297,7 +2297,7 @@ static CURLcode parse_proxy(struct Curl_easy *data,
CURLU *uhp = curl_url();
CURLcode result = CURLE_OK;
char *scheme = NULL;
-
+
/* When parsing the proxy, allowing non-supported schemes since we have
these made up ones for proxies. Guess scheme for URLs without it. */
uc = curl_url_set(uhp, CURLUPART_URL, proxy,
@@ -2309,7 +2309,7 @@ static CURLcode parse_proxy(struct Curl_easy *data,
result = CURLE_OUT_OF_MEMORY;
goto error;
}
-
+
if(strcasecompare("https", scheme))
proxytype = CURLPROXY_HTTPS;
else if(strcasecompare("socks5h", scheme))
@@ -2329,13 +2329,13 @@ static CURLcode parse_proxy(struct Curl_easy *data,
result = CURLE_COULDNT_CONNECT;
goto error;
}
- }
+ }
else {
failf(data, "Unsupported proxy syntax in \'%s\'", proxy);
result = CURLE_COULDNT_RESOLVE_PROXY;
goto error;
}
-
+
#ifdef USE_SSL
if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY))
#endif
@@ -2355,7 +2355,7 @@ static CURLcode parse_proxy(struct Curl_easy *data,
proxyinfo = sockstype ? &conn->socks_proxy : &conn->http_proxy;
proxyinfo->proxytype = proxytype;
- /* Is there a username and password given in this proxy url? */
+ /* Is there a username and password given in this proxy url? */
curl_url_get(uhp, CURLUPART_USER, &proxyuser, CURLU_URLDECODE);
curl_url_get(uhp, CURLUPART_PASSWORD, &proxypasswd, CURLU_URLDECODE);
if(proxyuser || proxypasswd) {
@@ -2371,18 +2371,18 @@ static CURLcode parse_proxy(struct Curl_easy *data,
}
proxyinfo->passwd = proxypasswd;
conn->bits.proxy_user_passwd = TRUE; /* enable it */
- }
-
+ }
+
curl_url_get(uhp, CURLUPART_PORT, &portptr, 0);
if(portptr) {
port = strtol(portptr, NULL, 10);
free(portptr);
- }
- else {
- if(data->set.proxyport)
- /* None given in the proxy string, then get the default one if it is
- given */
+ }
+ else {
+ if(data->set.proxyport)
+ /* None given in the proxy string, then get the default one if it is
+ given */
port = data->set.proxyport;
else {
if(proxytype == CURLPROXY_HTTPS)
@@ -2390,13 +2390,13 @@ static CURLcode parse_proxy(struct Curl_easy *data,
else
port = CURL_DEFAULT_PROXY_PORT;
}
- }
+ }
if(port >= 0) {
proxyinfo->port = port;
if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
conn->port = port;
}
-
+
/* now, clone the proxy host name */
uc = curl_url_get(uhp, CURLUPART_HOST, &host, CURLU_URLDECODE);
if(uc) {
@@ -2418,20 +2418,20 @@ static CURLcode parse_proxy(struct Curl_easy *data,
free(scheme);
curl_url_cleanup(uhp);
return result;
-}
-
-/*
- * Extract the user and password from the authentication string
- */
+}
+
+/*
+ * Extract the user and password from the authentication string
+ */
static CURLcode parse_proxy_auth(struct Curl_easy *data,
- struct connectdata *conn)
-{
+ struct connectdata *conn)
+{
const char *proxyuser = data->set.str[STRING_PROXYUSERNAME] ?
data->set.str[STRING_PROXYUSERNAME] : "";
const char *proxypasswd = data->set.str[STRING_PROXYPASSWORD] ?
data->set.str[STRING_PROXYPASSWORD] : "";
CURLcode result = CURLE_OK;
-
+
if(proxyuser)
result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
REJECT_ZERO);
@@ -2439,18 +2439,18 @@ static CURLcode parse_proxy_auth(struct Curl_easy *data,
result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
NULL, REJECT_ZERO);
return result;
-}
-
+}
+
/* create_conn helper to parse and init proxy values. to be called after unix
socket init but before any proxy vars are evaluated. */
static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
-{
+{
char *proxy = NULL;
char *socksproxy = NULL;
char *no_proxy = NULL;
- CURLcode result = CURLE_OK;
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
+
/*************************************************************
* Extract the user and password from the authentication string
*************************************************************/
@@ -2459,7 +2459,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
if(result)
goto out;
}
-
+
/*************************************************************
* Detect what (if any) proxy to use
*************************************************************/
@@ -2472,7 +2472,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
goto out;
}
}
-
+
if(data->set.str[STRING_PRE_PROXY]) {
socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
/* if global socks proxy is set, this is it */
@@ -2482,7 +2482,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
goto out;
}
}
-
+
if(!data->set.str[STRING_NOPROXY]) {
const char *p = "no_proxy";
no_proxy = curl_getenv(p);
@@ -2494,7 +2494,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
infof(conn->data, "Uses proxy env variable %s == '%s'\n", p, no_proxy);
}
}
-
+
if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
data->set.str[STRING_NOPROXY] : no_proxy)) {
Curl_safefree(proxy);
@@ -2505,9 +2505,9 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
/* if the host is not in the noproxy list, detect proxy. */
proxy = detect_proxy(conn);
#endif /* CURL_DISABLE_HTTP */
-
+
Curl_safefree(no_proxy);
-
+
#ifdef USE_UNIX_SOCKETS
/* For the time being do not mix proxy and unix domain sockets. See #1274 */
if(proxy && conn->unix_domain_socket) {
@@ -2515,7 +2515,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
proxy = NULL;
}
#endif
-
+
if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
free(proxy); /* Don't bother with an empty proxy string or if the
protocol doesn't work with network */
@@ -2527,7 +2527,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
the protocol doesn't work with network */
socksproxy = NULL;
}
-
+
/***********************************************************************
* If this is supposed to use a proxy, we need to figure out the proxy host
* name, proxy type and port number, so that we can re-use an existing
@@ -2540,7 +2540,7 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
if(result)
goto out;
}
-
+
if(socksproxy) {
result = parse_proxy(data, conn, socksproxy,
conn->socks_proxy.proxytype);
@@ -2549,12 +2549,12 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
if(result)
goto out;
}
-
+
if(conn->http_proxy.host.rawalloc) {
#ifdef CURL_DISABLE_HTTP
/* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
result = CURLE_UNSUPPORTED_PROTOCOL;
- goto out;
+ goto out;
#else
/* force this connection's protocol to become HTTP if compatible */
if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
@@ -2567,12 +2567,12 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
}
conn->bits.httpproxy = TRUE;
#endif
- }
+ }
else {
conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
}
-
+
if(conn->socks_proxy.host.rawalloc) {
if(!conn->http_proxy.host.rawalloc) {
/* once a socks proxy */
@@ -2585,16 +2585,16 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
}
}
conn->bits.socksproxy = TRUE;
- }
+ }
else
conn->bits.socksproxy = FALSE; /* not a socks proxy */
- }
+ }
else {
conn->bits.socksproxy = FALSE;
conn->bits.httpproxy = FALSE;
}
conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
-
+
if(!conn->bits.proxy) {
/* we aren't using the proxy after all... */
conn->bits.proxy = FALSE;
@@ -2605,183 +2605,183 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
/* CURLPROXY_HTTPS does not have its own flag in conn->bits, yet we need
to signal that CURLPROXY_HTTPS is not used for this connection */
conn->http_proxy.proxytype = CURLPROXY_HTTP;
- }
-
+ }
+
out:
-
+
free(socksproxy);
free(proxy);
- return result;
-}
+ return result;
+}
#endif /* CURL_DISABLE_PROXY */
-
-/*
+
+/*
* Curl_parse_login_details()
- *
- * This is used to parse a login string for user name, password and options in
- * the following formats:
- *
- * user
- * user:password
- * user:password;options
- * user;options
- * user;options:password
- * :password
- * :password;options
- * ;options
- * ;options:password
- *
- * Parameters:
- *
- * login [in] - The login string.
- * len [in] - The length of the login string.
- * userp [in/out] - The address where a pointer to newly allocated memory
- * holding the user will be stored upon completion.
+ *
+ * This is used to parse a login string for user name, password and options in
+ * the following formats:
+ *
+ * user
+ * user:password
+ * user:password;options
+ * user;options
+ * user;options:password
+ * :password
+ * :password;options
+ * ;options
+ * ;options:password
+ *
+ * Parameters:
+ *
+ * login [in] - The login string.
+ * len [in] - The length of the login string.
+ * userp [in/out] - The address where a pointer to newly allocated memory
+ * holding the user will be stored upon completion.
* passwdp [in/out] - The address where a pointer to newly allocated memory
- * holding the password will be stored upon completion.
- * optionsp [in/out] - The address where a pointer to newly allocated memory
- * holding the options will be stored upon completion.
- *
- * Returns CURLE_OK on success.
- */
+ * holding the password will be stored upon completion.
+ * optionsp [in/out] - The address where a pointer to newly allocated memory
+ * holding the options will be stored upon completion.
+ *
+ * Returns CURLE_OK on success.
+ */
CURLcode Curl_parse_login_details(const char *login, const size_t len,
char **userp, char **passwdp,
char **optionsp)
-{
- CURLcode result = CURLE_OK;
- char *ubuf = NULL;
- char *pbuf = NULL;
- char *obuf = NULL;
- const char *psep = NULL;
- const char *osep = NULL;
- size_t ulen;
- size_t plen;
- size_t olen;
-
+{
+ CURLcode result = CURLE_OK;
+ char *ubuf = NULL;
+ char *pbuf = NULL;
+ char *obuf = NULL;
+ const char *psep = NULL;
+ const char *osep = NULL;
+ size_t ulen;
+ size_t plen;
+ size_t olen;
+
/* the input length check is because this is called directcly from setopt
and isn't going through the regular string length check */
size_t llen = strlen(login);
if(llen > CURL_MAX_INPUT_LENGTH)
return CURLE_BAD_FUNCTION_ARGUMENT;
- /* Attempt to find the password separator */
- if(passwdp) {
- psep = strchr(login, ':');
-
- /* Within the constraint of the login string */
- if(psep >= login + len)
- psep = NULL;
- }
-
- /* Attempt to find the options separator */
- if(optionsp) {
- osep = strchr(login, ';');
-
- /* Within the constraint of the login string */
- if(osep >= login + len)
- osep = NULL;
- }
-
- /* Calculate the portion lengths */
- ulen = (psep ?
- (size_t)(osep && psep > osep ? osep - login : psep - login) :
- (osep ? (size_t)(osep - login) : len));
- plen = (psep ?
- (osep && osep > psep ? (size_t)(osep - psep) :
- (size_t)(login + len - psep)) - 1 : 0);
- olen = (osep ?
- (psep && psep > osep ? (size_t)(psep - osep) :
- (size_t)(login + len - osep)) - 1 : 0);
-
- /* Allocate the user portion buffer */
- if(userp && ulen) {
- ubuf = malloc(ulen + 1);
- if(!ubuf)
- result = CURLE_OUT_OF_MEMORY;
- }
-
- /* Allocate the password portion buffer */
- if(!result && passwdp && plen) {
- pbuf = malloc(plen + 1);
- if(!pbuf) {
+ /* Attempt to find the password separator */
+ if(passwdp) {
+ psep = strchr(login, ':');
+
+ /* Within the constraint of the login string */
+ if(psep >= login + len)
+ psep = NULL;
+ }
+
+ /* Attempt to find the options separator */
+ if(optionsp) {
+ osep = strchr(login, ';');
+
+ /* Within the constraint of the login string */
+ if(osep >= login + len)
+ osep = NULL;
+ }
+
+ /* Calculate the portion lengths */
+ ulen = (psep ?
+ (size_t)(osep && psep > osep ? osep - login : psep - login) :
+ (osep ? (size_t)(osep - login) : len));
+ plen = (psep ?
+ (osep && osep > psep ? (size_t)(osep - psep) :
+ (size_t)(login + len - psep)) - 1 : 0);
+ olen = (osep ?
+ (psep && psep > osep ? (size_t)(psep - osep) :
+ (size_t)(login + len - osep)) - 1 : 0);
+
+ /* Allocate the user portion buffer */
+ if(userp && ulen) {
+ ubuf = malloc(ulen + 1);
+ if(!ubuf)
+ result = CURLE_OUT_OF_MEMORY;
+ }
+
+ /* Allocate the password portion buffer */
+ if(!result && passwdp && plen) {
+ pbuf = malloc(plen + 1);
+ if(!pbuf) {
free(ubuf);
- result = CURLE_OUT_OF_MEMORY;
- }
- }
-
- /* Allocate the options portion buffer */
- if(!result && optionsp && olen) {
- obuf = malloc(olen + 1);
- if(!obuf) {
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ }
+
+ /* Allocate the options portion buffer */
+ if(!result && optionsp && olen) {
+ obuf = malloc(olen + 1);
+ if(!obuf) {
free(pbuf);
free(ubuf);
- result = CURLE_OUT_OF_MEMORY;
- }
- }
-
- if(!result) {
- /* Store the user portion if necessary */
- if(ubuf) {
- memcpy(ubuf, login, ulen);
- ubuf[ulen] = '\0';
- Curl_safefree(*userp);
- *userp = ubuf;
- }
-
- /* Store the password portion if necessary */
- if(pbuf) {
- memcpy(pbuf, psep + 1, plen);
- pbuf[plen] = '\0';
- Curl_safefree(*passwdp);
- *passwdp = pbuf;
- }
-
- /* Store the options portion if necessary */
- if(obuf) {
- memcpy(obuf, osep + 1, olen);
- obuf[olen] = '\0';
- Curl_safefree(*optionsp);
- *optionsp = obuf;
- }
- }
-
- return result;
-}
-
-/*************************************************************
- * Figure out the remote port number and fix it in the URL
- *
- * No matter if we use a proxy or not, we have to figure out the remote
- * port number of various reasons.
- *
- * The port number embedded in the URL is replaced, if necessary.
- *************************************************************/
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ }
+
+ if(!result) {
+ /* Store the user portion if necessary */
+ if(ubuf) {
+ memcpy(ubuf, login, ulen);
+ ubuf[ulen] = '\0';
+ Curl_safefree(*userp);
+ *userp = ubuf;
+ }
+
+ /* Store the password portion if necessary */
+ if(pbuf) {
+ memcpy(pbuf, psep + 1, plen);
+ pbuf[plen] = '\0';
+ Curl_safefree(*passwdp);
+ *passwdp = pbuf;
+ }
+
+ /* Store the options portion if necessary */
+ if(obuf) {
+ memcpy(obuf, osep + 1, olen);
+ obuf[olen] = '\0';
+ Curl_safefree(*optionsp);
+ *optionsp = obuf;
+ }
+ }
+
+ return result;
+}
+
+/*************************************************************
+ * Figure out the remote port number and fix it in the URL
+ *
+ * No matter if we use a proxy or not, we have to figure out the remote
+ * port number of various reasons.
+ *
+ * The port number embedded in the URL is replaced, if necessary.
+ *************************************************************/
static CURLcode parse_remote_port(struct Curl_easy *data,
- struct connectdata *conn)
-{
-
- if(data->set.use_port && data->state.allow_port) {
+ struct connectdata *conn)
+{
+
+ if(data->set.use_port && data->state.allow_port) {
/* if set, we use this instead of the port possibly given in the URL */
char portbuf[16];
CURLUcode uc;
- conn->remote_port = (unsigned short)data->set.use_port;
+ conn->remote_port = (unsigned short)data->set.use_port;
msnprintf(portbuf, sizeof(portbuf), "%d", conn->remote_port);
uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0);
if(uc)
return CURLE_OUT_OF_MEMORY;
- }
-
- return CURLE_OK;
-}
-
-/*
- * Override the login details from the URL with that in the CURLOPT_USERPWD
- * option or a .netrc file, if applicable.
- */
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Override the login details from the URL with that in the CURLOPT_USERPWD
+ * option or a .netrc file, if applicable.
+ */
static CURLcode override_login(struct Curl_easy *data,
- struct connectdata *conn,
- char **userp, char **passwdp, char **optionsp)
-{
+ struct connectdata *conn,
+ char **userp, char **passwdp, char **optionsp)
+{
bool user_changed = FALSE;
bool passwd_changed = FALSE;
CURLUcode uc;
@@ -2799,32 +2799,32 @@ static CURLcode override_login(struct Curl_easy *data,
conn->bits.user_passwd = FALSE; /* disable user+password */
}
- if(data->set.str[STRING_USERNAME]) {
- free(*userp);
- *userp = strdup(data->set.str[STRING_USERNAME]);
- if(!*userp)
- return CURLE_OUT_OF_MEMORY;
+ if(data->set.str[STRING_USERNAME]) {
+ free(*userp);
+ *userp = strdup(data->set.str[STRING_USERNAME]);
+ if(!*userp)
+ return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE; /* enable user+password */
user_changed = TRUE;
- }
-
- if(data->set.str[STRING_PASSWORD]) {
- free(*passwdp);
- *passwdp = strdup(data->set.str[STRING_PASSWORD]);
- if(!*passwdp)
- return CURLE_OUT_OF_MEMORY;
+ }
+
+ if(data->set.str[STRING_PASSWORD]) {
+ free(*passwdp);
+ *passwdp = strdup(data->set.str[STRING_PASSWORD]);
+ if(!*passwdp)
+ return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE; /* enable user+password */
passwd_changed = TRUE;
- }
-
- if(data->set.str[STRING_OPTIONS]) {
- free(*optionsp);
- *optionsp = strdup(data->set.str[STRING_OPTIONS]);
- if(!*optionsp)
- return CURLE_OUT_OF_MEMORY;
- }
-
- conn->bits.netrc = FALSE;
+ }
+
+ if(data->set.str[STRING_OPTIONS]) {
+ free(*optionsp);
+ *optionsp = strdup(data->set.str[STRING_OPTIONS]);
+ if(!*optionsp)
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ conn->bits.netrc = FALSE;
if(data->set.use_netrc != CURL_NETRC_IGNORED &&
(!*userp || !**userp || !*passwdp || !**passwdp)) {
bool netrc_user_changed = FALSE;
@@ -2837,27 +2837,27 @@ static CURLcode override_login(struct Curl_easy *data,
data->set.str[STRING_NETRC_FILE]);
if(ret > 0) {
infof(data, "Couldn't find host %s in the .netrc file; using defaults\n",
- conn->host.name);
- }
+ conn->host.name);
+ }
else if(ret < 0) {
return CURLE_OUT_OF_MEMORY;
}
- else {
- /* set bits.netrc TRUE to remember that we got the name from a .netrc
- file, so that it is safe to use even if we followed a Location: to a
- different host or similar. */
- conn->bits.netrc = TRUE;
+ else {
+ /* set bits.netrc TRUE to remember that we got the name from a .netrc
+ file, so that it is safe to use even if we followed a Location: to a
+ different host or similar. */
+ conn->bits.netrc = TRUE;
conn->bits.user_passwd = TRUE; /* enable user+password */
-
+
if(netrc_user_changed) {
user_changed = TRUE;
}
if(netrc_passwd_changed) {
passwd_changed = TRUE;
}
- }
- }
-
+ }
+ }
+
/* for updated strings, we update them in the URL */
if(user_changed) {
uc = curl_url_set(data->state.uh, CURLUPART_USER, *userp,
@@ -2871,19 +2871,19 @@ static CURLcode override_login(struct Curl_easy *data,
if(uc)
return Curl_uc_to_curlcode(uc);
}
- return CURLE_OK;
-}
-
-/*
+ return CURLE_OK;
+}
+
+/*
* Set the login details so they're available in the connection
- */
+ */
static CURLcode set_login(struct connectdata *conn)
-{
- CURLcode result = CURLE_OK;
+{
+ CURLcode result = CURLE_OK;
const char *setuser = CURL_DEFAULT_USER;
const char *setpasswd = CURL_DEFAULT_PASSWORD;
-
- /* If our protocol needs a password and we have none, use the defaults */
+
+ /* If our protocol needs a password and we have none, use the defaults */
if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd)
;
else {
@@ -2896,7 +2896,7 @@ static CURLcode set_login(struct connectdata *conn)
if(!conn->user)
return CURLE_OUT_OF_MEMORY;
}
-
+
/* Store the default password */
if(!conn->passwd) {
conn->passwd = strdup(setpasswd);
@@ -2961,7 +2961,7 @@ static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
if(*ptr == ']')
/* yeps, it ended nicely with a bracket as well */
*ptr++ = '\0';
- else
+ else
infof(data, "Invalid IPv6 address format\n");
portptr = ptr;
/* Note that if this didn't end with a bracket, we still advanced the
@@ -2974,7 +2974,7 @@ static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
return CURLE_NOT_BUILT_IN;
#endif
}
-
+
/* Get port number off server.com:1080 */
host_portno = strchr(portptr, ':');
if(host_portno) {
@@ -2992,7 +2992,7 @@ static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
else
port = (int)portparse; /* we know it will fit */
}
- }
+ }
/* now, clone the cleaned host name */
if(hostptr) {
@@ -3032,7 +3032,7 @@ static CURLcode parse_connect_to_string(struct Curl_easy *data,
host_match = TRUE;
ptr++;
}
- else {
+ else {
/* check whether the URL's hostname matches */
size_t hostname_to_match_len;
char *hostname_to_match = aprintf("%s%s%s",
@@ -3046,11 +3046,11 @@ static CURLcode parse_connect_to_string(struct Curl_easy *data,
hostname_to_match_len);
free(hostname_to_match);
ptr += hostname_to_match_len;
-
+
host_match = host_match && *ptr == ':';
ptr++;
- }
-
+ }
+
if(host_match) {
if(*ptr == ':') {
/* an empty port always matches */
@@ -3070,12 +3070,12 @@ static CURLcode parse_connect_to_string(struct Curl_easy *data,
}
}
}
-
+
if(host_match && port_match) {
/* parse the hostname and port to connect to */
result = parse_connect_to_host_port(data, ptr, host_result, port_result);
}
-
+
return result;
}
@@ -3122,8 +3122,8 @@ static CURLcode parse_connect_to_slist(struct Curl_easy *data,
}
conn_to_host = conn_to_host->next;
- }
-
+ }
+
#ifndef CURL_DISABLE_ALTSVC
if(data->asi && !host && (port == -1) &&
((conn->handler->protocol == CURLPROTO_HTTPS) ||
@@ -3198,42 +3198,42 @@ static CURLcode parse_connect_to_slist(struct Curl_easy *data,
}
#endif
- return result;
-}
-
-/*************************************************************
- * Resolve the address of the server or proxy
- *************************************************************/
+ return result;
+}
+
+/*************************************************************
+ * Resolve the address of the server or proxy
+ *************************************************************/
static CURLcode resolve_server(struct Curl_easy *data,
- struct connectdata *conn,
- bool *async)
-{
+ struct connectdata *conn,
+ bool *async)
+{
CURLcode result = CURLE_OK;
timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
-
+
DEBUGASSERT(conn);
DEBUGASSERT(data);
- /*************************************************************
- * Resolve the name of the server or proxy
- *************************************************************/
- if(conn->bits.reuse)
- /* We're reusing the connection - no need to resolve anything, and
+ /*************************************************************
+ * Resolve the name of the server or proxy
+ *************************************************************/
+ if(conn->bits.reuse)
+ /* We're reusing the connection - no need to resolve anything, and
idnconvert_hostname() was called already in create_conn() for the re-use
- case. */
- *async = FALSE;
-
- else {
- /* this is a fresh connect */
- int rc;
+ case. */
+ *async = FALSE;
+
+ else {
+ /* this is a fresh connect */
+ int rc;
struct Curl_dns_entry *hostaddr = NULL;
-
+
#ifdef USE_UNIX_SOCKETS
if(conn->unix_domain_socket) {
/* Unix domain sockets are local. The host gets ignored, just use the
* specified domain socket address. Do not cache "DNS entries". There is
* no DNS involved and we already have the filesystem path available */
const char *path = conn->unix_domain_socket;
-
+
hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
if(!hostaddr)
result = CURLE_OUT_OF_MEMORY;
@@ -3266,104 +3266,104 @@ static CURLcode resolve_server(struct Curl_easy *data,
else
connhost = &conn->host;
- /* If not connecting via a proxy, extract the port from the URL, if it is
- * there, thus overriding any defaults that might have been set above. */
+ /* If not connecting via a proxy, extract the port from the URL, if it is
+ * there, thus overriding any defaults that might have been set above. */
if(conn->bits.conn_to_port)
conn->port = conn->conn_to_port;
else
conn->port = conn->remote_port;
-
- /* Resolve target host right on */
+
+ /* Resolve target host right on */
conn->hostname_resolve = strdup(connhost->name);
if(!conn->hostname_resolve)
return CURLE_OUT_OF_MEMORY;
rc = Curl_resolv_timeout(conn, conn->hostname_resolve, (int)conn->port,
- &hostaddr, timeout_ms);
- if(rc == CURLRESOLV_PENDING)
- *async = TRUE;
-
- else if(rc == CURLRESOLV_TIMEDOUT)
- result = CURLE_OPERATION_TIMEDOUT;
-
- else if(!hostaddr) {
+ &hostaddr, timeout_ms);
+ if(rc == CURLRESOLV_PENDING)
+ *async = TRUE;
+
+ else if(rc == CURLRESOLV_TIMEDOUT)
+ result = CURLE_OPERATION_TIMEDOUT;
+
+ else if(!hostaddr) {
failf(data, "Couldn't resolve host '%s'", connhost->dispname);
result = CURLE_COULDNT_RESOLVE_HOST;
- /* don't return yet, we need to clean up the timeout first */
- }
- }
+ /* don't return yet, we need to clean up the timeout first */
+ }
+ }
#ifndef CURL_DISABLE_PROXY
- else {
- /* This is a proxy that hasn't been resolved yet. */
-
+ else {
+ /* This is a proxy that hasn't been resolved yet. */
+
struct hostname * const host = conn->bits.socksproxy ?
&conn->socks_proxy.host : &conn->http_proxy.host;
-
- /* resolve proxy */
+
+ /* resolve proxy */
conn->hostname_resolve = strdup(host->name);
if(!conn->hostname_resolve)
return CURLE_OUT_OF_MEMORY;
rc = Curl_resolv_timeout(conn, conn->hostname_resolve, (int)conn->port,
- &hostaddr, timeout_ms);
-
- if(rc == CURLRESOLV_PENDING)
- *async = TRUE;
-
- else if(rc == CURLRESOLV_TIMEDOUT)
- result = CURLE_OPERATION_TIMEDOUT;
-
- else if(!hostaddr) {
+ &hostaddr, timeout_ms);
+
+ if(rc == CURLRESOLV_PENDING)
+ *async = TRUE;
+
+ else if(rc == CURLRESOLV_TIMEDOUT)
+ result = CURLE_OPERATION_TIMEDOUT;
+
+ else if(!hostaddr) {
failf(data, "Couldn't resolve proxy '%s'", host->dispname);
- result = CURLE_COULDNT_RESOLVE_PROXY;
- /* don't return yet, we need to clean up the timeout first */
- }
- }
-#endif
- DEBUGASSERT(conn->dns_entry == NULL);
- conn->dns_entry = hostaddr;
- }
-
- return result;
-}
-
-/*
- * Cleanup the connection just allocated before we can move along and use the
- * previously existing one. All relevant data is copied over and old_conn is
- * ready for freeing once this function returns.
- */
-static void reuse_conn(struct connectdata *old_conn,
- struct connectdata *conn)
-{
+ result = CURLE_COULDNT_RESOLVE_PROXY;
+ /* don't return yet, we need to clean up the timeout first */
+ }
+ }
+#endif
+ DEBUGASSERT(conn->dns_entry == NULL);
+ conn->dns_entry = hostaddr;
+ }
+
+ return result;
+}
+
+/*
+ * Cleanup the connection just allocated before we can move along and use the
+ * previously existing one. All relevant data is copied over and old_conn is
+ * ready for freeing once this function returns.
+ */
+static void reuse_conn(struct connectdata *old_conn,
+ struct connectdata *conn)
+{
#ifndef CURL_DISABLE_PROXY
Curl_free_idnconverted_hostname(&old_conn->http_proxy.host);
Curl_free_idnconverted_hostname(&old_conn->socks_proxy.host);
-
+
free(old_conn->http_proxy.host.rawalloc);
free(old_conn->socks_proxy.host.rawalloc);
Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
#endif
- /* free the SSL config struct from this connection struct as this was
- allocated in vain and is targeted for destruction */
+ /* free the SSL config struct from this connection struct as this was
+ allocated in vain and is targeted for destruction */
Curl_free_primary_ssl_config(&old_conn->ssl_config);
-
- conn->data = old_conn->data;
-
- /* get the user+password information from the old_conn struct since it may
- * be new for this request even when we re-use an existing connection */
- conn->bits.user_passwd = old_conn->bits.user_passwd;
- if(conn->bits.user_passwd) {
- /* use the new user name and password though */
- Curl_safefree(conn->user);
- Curl_safefree(conn->passwd);
- conn->user = old_conn->user;
- conn->passwd = old_conn->passwd;
- old_conn->user = NULL;
- old_conn->passwd = NULL;
- }
-
+
+ conn->data = old_conn->data;
+
+ /* get the user+password information from the old_conn struct since it may
+ * be new for this request even when we re-use an existing connection */
+ conn->bits.user_passwd = old_conn->bits.user_passwd;
+ if(conn->bits.user_passwd) {
+ /* use the new user name and password though */
+ Curl_safefree(conn->user);
+ Curl_safefree(conn->passwd);
+ conn->user = old_conn->user;
+ conn->passwd = old_conn->passwd;
+ old_conn->user = NULL;
+ old_conn->passwd = NULL;
+ }
+
#ifndef CURL_DISABLE_PROXY
- conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
- if(conn->bits.proxy_user_passwd) {
- /* use the new proxy user name and proxy password though */
+ conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
+ if(conn->bits.proxy_user_passwd) {
+ /* use the new proxy user name and proxy password though */
Curl_safefree(conn->http_proxy.user);
Curl_safefree(conn->socks_proxy.user);
Curl_safefree(conn->http_proxy.passwd);
@@ -3376,108 +3376,108 @@ static void reuse_conn(struct connectdata *old_conn,
old_conn->socks_proxy.user = NULL;
old_conn->http_proxy.passwd = NULL;
old_conn->socks_proxy.passwd = NULL;
- }
+ }
Curl_safefree(old_conn->http_proxy.user);
Curl_safefree(old_conn->socks_proxy.user);
Curl_safefree(old_conn->http_proxy.passwd);
Curl_safefree(old_conn->socks_proxy.passwd);
#endif
-
- /* host can change, when doing keepalive with a proxy or if the case is
- different this time etc */
+
+ /* host can change, when doing keepalive with a proxy or if the case is
+ different this time etc */
Curl_free_idnconverted_hostname(&conn->host);
Curl_free_idnconverted_hostname(&conn->conn_to_host);
- Curl_safefree(conn->host.rawalloc);
+ Curl_safefree(conn->host.rawalloc);
Curl_safefree(conn->conn_to_host.rawalloc);
conn->host = old_conn->host;
conn->conn_to_host = old_conn->conn_to_host;
conn->conn_to_port = old_conn->conn_to_port;
conn->remote_port = old_conn->remote_port;
Curl_safefree(conn->hostname_resolve);
-
+
conn->hostname_resolve = old_conn->hostname_resolve;
old_conn->hostname_resolve = NULL;
- /* persist connection info in session handle */
- Curl_persistconninfo(conn);
-
+ /* persist connection info in session handle */
+ Curl_persistconninfo(conn);
+
conn_reset_all_postponed_data(old_conn); /* free buffers */
- /* re-use init */
- conn->bits.reuse = TRUE; /* yes, we're re-using here */
-
- Curl_safefree(old_conn->user);
- Curl_safefree(old_conn->passwd);
+ /* re-use init */
+ conn->bits.reuse = TRUE; /* yes, we're re-using here */
+
+ Curl_safefree(old_conn->user);
+ Curl_safefree(old_conn->passwd);
Curl_safefree(old_conn->options);
- Curl_safefree(old_conn->localdev);
+ Curl_safefree(old_conn->localdev);
Curl_llist_destroy(&old_conn->easyq, NULL);
-
+
#ifdef USE_UNIX_SOCKETS
Curl_safefree(old_conn->unix_domain_socket);
#endif
-}
-
-/**
- * create_conn() sets up a new connectdata struct, or re-uses an already
- * existing one, and resolves host name.
- *
- * if this function returns CURLE_OK and *async is set to TRUE, the resolve
- * response will be coming asynchronously. If *async is FALSE, the name is
- * already resolved.
- *
- * @param data The sessionhandle pointer
- * @param in_connect is set to the next connection data pointer
- * @param async is set TRUE when an async DNS resolution is pending
- * @see Curl_setup_conn()
- *
- * *NOTE* this function assigns the conn->data pointer!
- */
-
+}
+
+/**
+ * create_conn() sets up a new connectdata struct, or re-uses an already
+ * existing one, and resolves host name.
+ *
+ * if this function returns CURLE_OK and *async is set to TRUE, the resolve
+ * response will be coming asynchronously. If *async is FALSE, the name is
+ * already resolved.
+ *
+ * @param data The sessionhandle pointer
+ * @param in_connect is set to the next connection data pointer
+ * @param async is set TRUE when an async DNS resolution is pending
+ * @see Curl_setup_conn()
+ *
+ * *NOTE* this function assigns the conn->data pointer!
+ */
+
static CURLcode create_conn(struct Curl_easy *data,
- struct connectdata **in_connect,
- bool *async)
-{
- CURLcode result = CURLE_OK;
- struct connectdata *conn;
- struct connectdata *conn_temp = NULL;
- bool reuse;
+ struct connectdata **in_connect,
+ bool *async)
+{
+ CURLcode result = CURLE_OK;
+ struct connectdata *conn;
+ struct connectdata *conn_temp = NULL;
+ bool reuse;
bool connections_available = TRUE;
bool force_reuse = FALSE;
bool waitpipe = FALSE;
- size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
- size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
-
- *async = FALSE;
+ size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
+ size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
+
+ *async = FALSE;
*in_connect = NULL;
-
- /*************************************************************
- * Check input data
- *************************************************************/
- if(!data->change.url) {
- result = CURLE_URL_MALFORMAT;
- goto out;
- }
-
- /* First, split up the current URL in parts so that we can use the
- parts for checking against the already present connections. In order
- to not have to modify everything at once, we allocate a temporary
- connection data struct and fill in for comparison purposes. */
- conn = allocate_conn(data);
-
- if(!conn) {
- result = CURLE_OUT_OF_MEMORY;
- goto out;
- }
-
- /* We must set the return variable as soon as possible, so that our
- parent can cleanup any possible allocs we may have done before
- any failure */
- *in_connect = conn;
-
+
+ /*************************************************************
+ * Check input data
+ *************************************************************/
+ if(!data->change.url) {
+ result = CURLE_URL_MALFORMAT;
+ goto out;
+ }
+
+ /* First, split up the current URL in parts so that we can use the
+ parts for checking against the already present connections. In order
+ to not have to modify everything at once, we allocate a temporary
+ connection data struct and fill in for comparison purposes. */
+ conn = allocate_conn(data);
+
+ if(!conn) {
+ result = CURLE_OUT_OF_MEMORY;
+ goto out;
+ }
+
+ /* We must set the return variable as soon as possible, so that our
+ parent can cleanup any possible allocs we may have done before
+ any failure */
+ *in_connect = conn;
+
result = parseurlandfillconn(data, conn);
if(result)
- goto out;
-
+ goto out;
+
if(data->set.str[STRING_SASL_AUTHZID]) {
conn->sasl_authzid = strdup(data->set.str[STRING_SASL_AUTHZID]);
if(!conn->sasl_authzid) {
@@ -3494,74 +3494,74 @@ static CURLcode create_conn(struct Curl_easy *data,
goto out;
}
conn->bits.abstract_unix_socket = data->set.abstract_unix_socket;
- }
+ }
#endif
-
+
/* After the unix socket init but before the proxy vars are used, parse and
initialize the proxy vars */
#ifndef CURL_DISABLE_PROXY
result = create_conn_helper_init_proxy(conn);
if(result)
- goto out;
-
- /*************************************************************
+ goto out;
+
+ /*************************************************************
* If the protocol is using SSL and HTTP proxy is used, we set
* the tunnel_proxy bit.
- *************************************************************/
+ *************************************************************/
if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
#endif
-
- /*************************************************************
+
+ /*************************************************************
* Figure out the remote port number and fix it in the URL
- *************************************************************/
+ *************************************************************/
result = parse_remote_port(data, conn);
if(result)
goto out;
-
+
/* Check for overridden login details and set them accordingly so they
they are known when protocol->setup_connection is called! */
result = override_login(data, conn, &conn->user, &conn->passwd,
&conn->options);
if(result)
goto out;
-
+
result = set_login(conn); /* default credentials */
if(result)
goto out;
-
- /*************************************************************
+
+ /*************************************************************
* Process the "connect to" linked list of hostname/port mappings.
* Do this after the remote port number has been fixed in the URL.
- *************************************************************/
+ *************************************************************/
result = parse_connect_to_slist(data, conn, data->set.connect_to);
if(result)
goto out;
-
- /*************************************************************
+
+ /*************************************************************
* IDN-convert the hostnames
- *************************************************************/
+ *************************************************************/
result = Curl_idnconvert_hostname(conn, &conn->host);
if(result)
goto out;
if(conn->bits.conn_to_host) {
result = Curl_idnconvert_hostname(conn, &conn->conn_to_host);
if(result)
- goto out;
- }
+ goto out;
+ }
#ifndef CURL_DISABLE_PROXY
if(conn->bits.httpproxy) {
result = Curl_idnconvert_hostname(conn, &conn->http_proxy.host);
if(result)
goto out;
- }
+ }
if(conn->bits.socksproxy) {
result = Curl_idnconvert_hostname(conn, &conn->socks_proxy.host);
- if(result)
- goto out;
+ if(result)
+ goto out;
}
#endif
-
+
/*************************************************************
* Check whether the host and the "connect to host" are equal.
* Do this after the hostnames have been IDN-converted.
@@ -3569,91 +3569,91 @@ static CURLcode create_conn(struct Curl_easy *data,
if(conn->bits.conn_to_host &&
strcasecompare(conn->conn_to_host.name, conn->host.name)) {
conn->bits.conn_to_host = FALSE;
- }
-
- /*************************************************************
+ }
+
+ /*************************************************************
* Check whether the port and the "connect to port" are equal.
* Do this after the remote port number has been fixed in the URL.
- *************************************************************/
+ *************************************************************/
if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
conn->bits.conn_to_port = FALSE;
}
-
+
#ifndef CURL_DISABLE_PROXY
- /*************************************************************
+ /*************************************************************
* If the "connect to" feature is used with an HTTP proxy,
* we set the tunnel_proxy bit.
- *************************************************************/
+ *************************************************************/
if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
#endif
-
- /*************************************************************
- * Setup internals depending on protocol. Needs to be done after
- * we figured out what/if proxy to use.
- *************************************************************/
- result = setup_connection_internals(conn);
+
+ /*************************************************************
+ * Setup internals depending on protocol. Needs to be done after
+ * we figured out what/if proxy to use.
+ *************************************************************/
+ result = setup_connection_internals(conn);
if(result)
- goto out;
-
- conn->recv[FIRSTSOCKET] = Curl_recv_plain;
- conn->send[FIRSTSOCKET] = Curl_send_plain;
- conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
- conn->send[SECONDARYSOCKET] = Curl_send_plain;
-
+ goto out;
+
+ conn->recv[FIRSTSOCKET] = Curl_recv_plain;
+ conn->send[FIRSTSOCKET] = Curl_send_plain;
+ conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
+ conn->send[SECONDARYSOCKET] = Curl_send_plain;
+
conn->bits.tcp_fastopen = data->set.tcp_fastopen;
- /***********************************************************************
- * file: is a special case in that it doesn't need a network connection
- ***********************************************************************/
-#ifndef CURL_DISABLE_FILE
- if(conn->handler->flags & PROTOPT_NONETWORK) {
- bool done;
- /* this is supposed to be the connect function so we better at least check
- that the file is present here! */
- DEBUGASSERT(conn->handler->connect_it);
+ /***********************************************************************
+ * file: is a special case in that it doesn't need a network connection
+ ***********************************************************************/
+#ifndef CURL_DISABLE_FILE
+ if(conn->handler->flags & PROTOPT_NONETWORK) {
+ bool done;
+ /* this is supposed to be the connect function so we better at least check
+ that the file is present here! */
+ DEBUGASSERT(conn->handler->connect_it);
Curl_persistconninfo(conn);
- result = conn->handler->connect_it(conn, &done);
-
- /* Setup a "faked" transfer that'll do nothing */
+ result = conn->handler->connect_it(conn, &done);
+
+ /* Setup a "faked" transfer that'll do nothing */
if(!result) {
- conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
-
+ conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
+
Curl_attach_connnection(data, conn);
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result)
goto out;
-
- /*
- * Setup whatever necessary for a resumed transfer
- */
- result = setup_range(data);
- if(result) {
- DEBUGASSERT(conn->handler->done);
- /* we ignore the return code for the protocol-specific DONE */
- (void)conn->handler->done(conn, result, FALSE);
- goto out;
- }
+
+ /*
+ * Setup whatever necessary for a resumed transfer
+ */
+ result = setup_range(data);
+ if(result) {
+ DEBUGASSERT(conn->handler->done);
+ /* we ignore the return code for the protocol-specific DONE */
+ (void)conn->handler->done(conn, result, FALSE);
+ goto out;
+ }
Curl_setup_transfer(data, -1, -1, FALSE, -1);
- }
-
- /* since we skip do_init() */
+ }
+
+ /* since we skip do_init() */
Curl_init_do(data, conn);
-
- goto out;
- }
-#endif
-
- /* Get a cloned copy of the SSL config situation stored in the
- connection struct. But to get this going nicely, we must first make
- sure that the strings in the master copy are pointing to the correct
- strings in the session handle strings array!
-
- Keep in mind that the pointers in the master copy are pointing to strings
+
+ goto out;
+ }
+#endif
+
+ /* Get a cloned copy of the SSL config situation stored in the
+ connection struct. But to get this going nicely, we must first make
+ sure that the strings in the master copy are pointing to the correct
+ strings in the session handle strings array!
+
+ Keep in mind that the pointers in the master copy are pointing to strings
that will be freed as part of the Curl_easy struct, but all cloned
- copies will be separately allocated.
- */
+ copies will be separately allocated.
+ */
data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
@@ -3696,24 +3696,24 @@ static CURLcode create_conn(struct Curl_easy *data,
data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
-#ifdef USE_TLS_SRP
+#ifdef USE_TLS_SRP
data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
#ifndef CURL_DISABLE_PROXY
data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
-#endif
#endif
-
+#endif
+
data->set.ssl.key_blob = data->set.blobs[BLOB_KEY_ORIG];
data->set.ssl.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT_ORIG];
if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
&conn->ssl_config)) {
- result = CURLE_OUT_OF_MEMORY;
- goto out;
- }
-
+ result = CURLE_OUT_OF_MEMORY;
+ goto out;
+ }
+
#ifndef CURL_DISABLE_PROXY
if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
&conn->proxy_ssl_config)) {
@@ -3724,43 +3724,43 @@ static CURLcode create_conn(struct Curl_easy *data,
prune_dead_connections(data);
- /*************************************************************
- * Check the current list of connections to see if we can
- * re-use an already existing one or if we have to create a
- * new one.
- *************************************************************/
-
+ /*************************************************************
+ * Check the current list of connections to see if we can
+ * re-use an already existing one or if we have to create a
+ * new one.
+ *************************************************************/
+
DEBUGASSERT(conn->user);
DEBUGASSERT(conn->passwd);
- /* reuse_fresh is TRUE if we are told to use a new connection by force, but
- we only acknowledge this option if this is not a re-used connection
- already (which happens due to follow-location or during a HTTP
+ /* reuse_fresh is TRUE if we are told to use a new connection by force, but
+ we only acknowledge this option if this is not a re-used connection
+ already (which happens due to follow-location or during a HTTP
authentication phase). CONNECT_ONLY transfers also refuse reuse. */
if((data->set.reuse_fresh && !data->state.this_is_a_follow) ||
data->set.connect_only)
- reuse = FALSE;
- else
+ reuse = FALSE;
+ else
reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
-
- if(reuse) {
- /*
- * We already have a connection for this, we got the former connection
- * in the conn_temp variable and thus we need to cleanup the one we
- * just allocated before we can move along and use the previously
- * existing one.
- */
- reuse_conn(conn, conn_temp);
+
+ if(reuse) {
+ /*
+ * We already have a connection for this, we got the former connection
+ * in the conn_temp variable and thus we need to cleanup the one we
+ * just allocated before we can move along and use the previously
+ * existing one.
+ */
+ reuse_conn(conn, conn_temp);
#ifdef USE_SSL
free(conn->ssl_extra);
#endif
- free(conn); /* we don't need this anymore */
- conn = conn_temp;
- *in_connect = conn;
-
+ free(conn); /* we don't need this anymore */
+ conn = conn_temp;
+ *in_connect = conn;
+
#ifndef CURL_DISABLE_PROXY
infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
- conn->connection_id,
+ conn->connection_id,
conn->bits.proxy?"proxy":"host",
conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
@@ -3769,12 +3769,12 @@ static CURLcode create_conn(struct Curl_easy *data,
infof(data, "Re-using existing connection! (#%ld) with host %s\n",
conn->connection_id, conn->host.dispname);
#endif
- }
- else {
- /* We have decided that we want a new connection. However, we may not
- be able to do that if we have reached the limit of how many
- connections we are allowed to open. */
-
+ }
+ else {
+ /* We have decided that we want a new connection. However, we may not
+ be able to do that if we have reached the limit of how many
+ connections we are allowed to open. */
+
if(conn->handler->flags & PROTOPT_ALPN_NPN) {
/* The protocol wants it, so set the bits if enabled in the easy handle
(default) */
@@ -3783,7 +3783,7 @@ static CURLcode create_conn(struct Curl_easy *data,
if(data->set.ssl_enable_npn)
conn->bits.tls_enable_npn = TRUE;
}
-
+
if(waitpipe)
/* There is a connection that *might* become usable for multiplexing
"soon", and we wait for that */
@@ -3793,7 +3793,7 @@ static CURLcode create_conn(struct Curl_easy *data,
const char *bundlehost;
struct connectbundle *bundle =
Curl_conncache_find_bundle(conn, data->state.conn_cache, &bundlehost);
-
+
if(max_host_connections > 0 && bundle &&
(bundle->num_connections >= max_host_connections)) {
struct connectdata *conn_candidate;
@@ -3809,47 +3809,47 @@ static CURLcode create_conn(struct Curl_easy *data,
bundlehost, max_host_connections);
connections_available = FALSE;
}
- }
- else
+ }
+ else
CONNCACHE_UNLOCK(data);
- }
-
+ }
+
if(connections_available &&
(max_total_connections > 0) &&
(Curl_conncache_size(data) >= max_total_connections)) {
- struct connectdata *conn_candidate;
-
- /* The cache is full. Let's see if we can kill a connection. */
+ struct connectdata *conn_candidate;
+
+ /* The cache is full. Let's see if we can kill a connection. */
conn_candidate = Curl_conncache_extract_oldest(data);
if(conn_candidate)
(void)Curl_disconnect(data, conn_candidate, FALSE);
else {
infof(data, "No connections available in cache\n");
connections_available = FALSE;
- }
- }
-
+ }
+ }
+
if(!connections_available) {
- infof(data, "No connections available.\n");
-
- conn_free(conn);
- *in_connect = NULL;
-
- result = CURLE_NO_CONNECTION_AVAILABLE;
- goto out;
- }
- else {
- /*
- * This is a brand new connection, so let's store it in the connection
- * cache of ours!
- */
+ infof(data, "No connections available.\n");
+
+ conn_free(conn);
+ *in_connect = NULL;
+
+ result = CURLE_NO_CONNECTION_AVAILABLE;
+ goto out;
+ }
+ else {
+ /*
+ * This is a brand new connection, so let's store it in the connection
+ * cache of ours!
+ */
Curl_attach_connnection(data, conn);
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result)
goto out;
- }
+ }
#if defined(USE_NTLM)
/* If NTLM is requested in a part of this connection, make sure we don't
@@ -3869,32 +3869,32 @@ static CURLcode create_conn(struct Curl_easy *data,
data->state.authproxy.done = FALSE;
}
#endif
- }
-
- /* Setup and init stuff before DO starts, in preparing for the transfer. */
+ }
+
+ /* Setup and init stuff before DO starts, in preparing for the transfer. */
Curl_init_do(data, conn);
-
- /*
- * Setup whatever necessary for a resumed transfer
- */
- result = setup_range(data);
- if(result)
- goto out;
-
- /* Continue connectdata initialization here. */
-
- /*
- * Inherit the proper values from the urldata struct AFTER we have arranged
- * the persistent connection stuff
- */
- conn->seek_func = data->set.seek_func;
- conn->seek_client = data->set.seek_client;
-
- /*************************************************************
- * Resolve the address of the server or proxy
- *************************************************************/
- result = resolve_server(data, conn, async);
-
+
+ /*
+ * Setup whatever necessary for a resumed transfer
+ */
+ result = setup_range(data);
+ if(result)
+ goto out;
+
+ /* Continue connectdata initialization here. */
+
+ /*
+ * Inherit the proper values from the urldata struct AFTER we have arranged
+ * the persistent connection stuff
+ */
+ conn->seek_func = data->set.seek_func;
+ conn->seek_client = data->set.seek_client;
+
+ /*************************************************************
+ * Resolve the address of the server or proxy
+ *************************************************************/
+ result = resolve_server(data, conn, async);
+
/* Strip trailing dots. resolve_server copied the name. */
strip_trailing_dot(&conn->host);
#ifndef CURL_DISABLE_PROXY
@@ -3905,70 +3905,70 @@ static CURLcode create_conn(struct Curl_easy *data,
#endif
if(conn->bits.conn_to_host)
strip_trailing_dot(&conn->conn_to_host);
-
+
out:
- return result;
-}
-
-/* Curl_setup_conn() is called after the name resolve initiated in
- * create_conn() is all done.
- *
- * Curl_setup_conn() also handles reused connections
- *
- * conn->data MUST already have been setup fine (in create_conn)
- */
-
-CURLcode Curl_setup_conn(struct connectdata *conn,
- bool *protocol_done)
-{
- CURLcode result = CURLE_OK;
+ return result;
+}
+
+/* Curl_setup_conn() is called after the name resolve initiated in
+ * create_conn() is all done.
+ *
+ * Curl_setup_conn() also handles reused connections
+ *
+ * conn->data MUST already have been setup fine (in create_conn)
+ */
+
+CURLcode Curl_setup_conn(struct connectdata *conn,
+ bool *protocol_done)
+{
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
- Curl_pgrsTime(data, TIMER_NAMELOOKUP);
-
- if(conn->handler->flags & PROTOPT_NONETWORK) {
- /* nothing to setup when not using a network */
- *protocol_done = TRUE;
- return result;
- }
- *protocol_done = FALSE; /* default to not done */
-
+
+ Curl_pgrsTime(data, TIMER_NAMELOOKUP);
+
+ if(conn->handler->flags & PROTOPT_NONETWORK) {
+ /* nothing to setup when not using a network */
+ *protocol_done = TRUE;
+ return result;
+ }
+ *protocol_done = FALSE; /* default to not done */
+
#ifndef CURL_DISABLE_PROXY
- /* set proxy_connect_closed to false unconditionally already here since it
- is used strictly to provide extra information to a parent function in the
- case of proxy CONNECT failures and we must make sure we don't have it
- lingering set from a previous invoke */
- conn->bits.proxy_connect_closed = FALSE;
-#endif
- /*
- * Set user-agent. Used for HTTP, but since we can attempt to tunnel
- * basically anything through a http proxy we can't limit this based on
- * protocol.
- */
- if(data->set.str[STRING_USERAGENT]) {
+ /* set proxy_connect_closed to false unconditionally already here since it
+ is used strictly to provide extra information to a parent function in the
+ case of proxy CONNECT failures and we must make sure we don't have it
+ lingering set from a previous invoke */
+ conn->bits.proxy_connect_closed = FALSE;
+#endif
+ /*
+ * Set user-agent. Used for HTTP, but since we can attempt to tunnel
+ * basically anything through a http proxy we can't limit this based on
+ * protocol.
+ */
+ if(data->set.str[STRING_USERAGENT]) {
Curl_safefree(data->state.aptr.uagent);
data->state.aptr.uagent =
- aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
+ aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
if(!data->state.aptr.uagent)
- return CURLE_OUT_OF_MEMORY;
- }
-
- data->req.headerbytecount = 0;
-
-#ifdef CURL_DO_LINEEND_CONV
- data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
-#endif /* CURL_DO_LINEEND_CONV */
-
- /* set start time here for timeout purposes in the connect procedure, it
- is later set again for the progress meter purpose */
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ data->req.headerbytecount = 0;
+
+#ifdef CURL_DO_LINEEND_CONV
+ data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
+#endif /* CURL_DO_LINEEND_CONV */
+
+ /* set start time here for timeout purposes in the connect procedure, it
+ is later set again for the progress meter purpose */
conn->now = Curl_now();
-
+
if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
result = Curl_connecthost(conn, conn->dns_entry);
if(result)
return result;
- }
+ }
else {
Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
if(conn->ssl[FIRSTSOCKET].use ||
@@ -3978,70 +3978,70 @@ CURLcode Curl_setup_conn(struct connectdata *conn,
*protocol_done = TRUE;
Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
Curl_verboseconnect(conn);
- }
-
+ }
+
conn->now = Curl_now(); /* time this *after* the connect is done, we set
this here perhaps a second time */
- return result;
-}
-
+ return result;
+}
+
CURLcode Curl_connect(struct Curl_easy *data,
- bool *asyncp,
- bool *protocol_done)
-{
+ bool *asyncp,
+ bool *protocol_done)
+{
CURLcode result;
struct connectdata *conn;
-
- *asyncp = FALSE; /* assume synchronous resolves by default */
-
+
+ *asyncp = FALSE; /* assume synchronous resolves by default */
+
/* init the single-transfer specific data */
Curl_free_request_state(data);
memset(&data->req, 0, sizeof(struct SingleRequest));
data->req.maxdownload = -1;
- /* call the stuff that needs to be called */
+ /* call the stuff that needs to be called */
result = create_conn(data, &conn, asyncp);
-
+
if(!result) {
if(CONN_INUSE(conn) > 1)
/* multiplexed */
- *protocol_done = TRUE;
- else if(!*asyncp) {
- /* DNS resolution is done: that's either because this is a reused
- connection, in which case DNS was unnecessary, or because DNS
- really did finish already (synch resolver/fast async resolve) */
+ *protocol_done = TRUE;
+ else if(!*asyncp) {
+ /* DNS resolution is done: that's either because this is a reused
+ connection, in which case DNS was unnecessary, or because DNS
+ really did finish already (synch resolver/fast async resolve) */
result = Curl_setup_conn(conn, protocol_done);
- }
- }
-
+ }
+ }
+
if(result == CURLE_NO_CONNECTION_AVAILABLE) {
return result;
- }
+ }
else if(result && conn) {
/* We're not allowed to return failure with memory left allocated in the
connectdata struct, free those here */
Curl_detach_connnection(data);
Curl_conncache_remove_conn(data, conn, TRUE);
Curl_disconnect(data, conn, TRUE);
- }
-
- return result;
-}
-
-/*
+ }
+
+ return result;
+}
+
+/*
* Curl_init_do() inits the readwrite session. This is inited each time (in
* the DO function before the protocol-specific DO functions are invoked) for
* a transfer, sometimes multiple times on the same Curl_easy. Make sure
- * nothing in here depends on stuff that are setup dynamically for the
- * transfer.
+ * nothing in here depends on stuff that are setup dynamically for the
+ * transfer.
*
* Allow this function to get called with 'conn' set to NULL.
- */
-
+ */
+
CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
-{
- struct SingleRequest *k = &data->req;
-
+{
+ struct SingleRequest *k = &data->req;
+
/* if this is a pushed stream, we need this: */
CURLcode result = Curl_preconnect(data);
if(result)
@@ -4057,21 +4057,21 @@ CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
}
data->state.done = FALSE; /* *_done() is not called yet */
- data->state.expect100header = FALSE;
-
- if(data->set.opt_no_body)
- /* in HTTP lingo, no body means using the HEAD request... */
+ data->state.expect100header = FALSE;
+
+ if(data->set.opt_no_body)
+ /* in HTTP lingo, no body means using the HEAD request... */
data->state.httpreq = HTTPREQ_HEAD;
-
+
k->start = Curl_now(); /* start time */
- k->now = k->start; /* current time is now */
- k->header = TRUE; /* assume header */
- k->bytecount = 0;
+ k->now = k->start; /* current time is now */
+ k->header = TRUE; /* assume header */
+ k->bytecount = 0;
k->ignorebody = FALSE;
-
- Curl_speedinit(data);
- Curl_pgrsSetUploadCounter(data, 0);
- Curl_pgrsSetDownloadCounter(data, 0);
-
- return CURLE_OK;
-}
+
+ Curl_speedinit(data);
+ Curl_pgrsSetUploadCounter(data, 0);
+ Curl_pgrsSetDownloadCounter(data, 0);
+
+ return CURLE_OK;
+}
diff --git a/contrib/libs/curl/lib/url.h b/contrib/libs/curl/lib/url.h
index 2422b9b614..a9d5bda29c 100644
--- a/contrib/libs/curl/lib/url.h
+++ b/contrib/libs/curl/lib/url.h
@@ -1,28 +1,28 @@
-#ifndef HEADER_CURL_URL_H
-#define HEADER_CURL_URL_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_URL_H
+#define HEADER_CURL_URL_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#include "curl_setup.h"
+
#define READBUFFER_SIZE CURL_MAX_WRITE_SIZE
#define READBUFFER_MAX CURL_MAX_READ_SIZE
#define READBUFFER_MIN 1024
@@ -39,10 +39,10 @@
#define UPLOADBUFFER_MAX (2*1024*1024)
#define UPLOADBUFFER_MIN CURL_MAX_WRITE_SIZE
-/*
- * Prototypes for library-wide functions provided by url.c
- */
-
+/*
+ * Prototypes for library-wide functions provided by url.c
+ */
+
CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn);
CURLcode Curl_open(struct Curl_easy **curl);
CURLcode Curl_init_userdefined(struct Curl_easy *data);
@@ -53,13 +53,13 @@ CURLcode Curl_close(struct Curl_easy **datap); /* opposite of curl_open() */
CURLcode Curl_connect(struct Curl_easy *, bool *async, bool *protocol_connect);
CURLcode Curl_disconnect(struct Curl_easy *data,
struct connectdata *, bool dead_connection);
-CURLcode Curl_setup_conn(struct connectdata *conn,
- bool *protocol_done);
+CURLcode Curl_setup_conn(struct connectdata *conn,
+ bool *protocol_done);
void Curl_free_request_state(struct Curl_easy *data);
CURLcode Curl_parse_login_details(const char *login, const size_t len,
char **userptr, char **passwdptr,
char **optionsptr);
-
+
const struct Curl_handler *Curl_builtin_scheme(const char *scheme);
bool Curl_is_ASCII_name(const char *hostname);
@@ -67,16 +67,16 @@ CURLcode Curl_idnconvert_hostname(struct connectdata *conn,
struct hostname *host);
void Curl_free_idnconverted_hostname(struct hostname *host);
-#define CURL_DEFAULT_PROXY_PORT 1080 /* default proxy port unless specified */
+#define CURL_DEFAULT_PROXY_PORT 1080 /* default proxy port unless specified */
#define CURL_DEFAULT_HTTPS_PROXY_PORT 443 /* default https proxy port unless
specified */
-
-#ifdef CURL_DISABLE_VERBOSE_STRINGS
-#define Curl_verboseconnect(x) Curl_nop_stmt
-#else
-void Curl_verboseconnect(struct connectdata *conn);
-#endif
-
+
+#ifdef CURL_DISABLE_VERBOSE_STRINGS
+#define Curl_verboseconnect(x) Curl_nop_stmt
+#else
+void Curl_verboseconnect(struct connectdata *conn);
+#endif
+
#ifdef CURL_DISABLE_PROXY
#define CONNECT_PROXY_SSL() FALSE
#else
@@ -84,7 +84,7 @@ void Curl_verboseconnect(struct connectdata *conn);
#define CONNECT_PROXY_SSL()\
(conn->http_proxy.proxytype == CURLPROXY_HTTPS &&\
!conn->bits.proxy_ssl_connected[sockindex])
-
+
#define CONNECT_FIRSTSOCKET_PROXY_SSL()\
(conn->http_proxy.proxytype == CURLPROXY_HTTPS &&\
!conn->bits.proxy_ssl_connected[FIRSTSOCKET])
@@ -94,4 +94,4 @@ void Curl_verboseconnect(struct connectdata *conn);
!conn->bits.proxy_ssl_connected[SECONDARYSOCKET])
#endif /* !CURL_DISABLE_PROXY */
-#endif /* HEADER_CURL_URL_H */
+#endif /* HEADER_CURL_URL_H */
diff --git a/contrib/libs/curl/lib/urldata.h b/contrib/libs/curl/lib/urldata.h
index e28f9a767f..b824856427 100644
--- a/contrib/libs/curl/lib/urldata.h
+++ b/contrib/libs/curl/lib/urldata.h
@@ -1,66 +1,66 @@
-#ifndef HEADER_CURL_URLDATA_H
-#define HEADER_CURL_URLDATA_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_URLDATA_H
+#define HEADER_CURL_URLDATA_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* This file is for lib internal stuff */
-
-#include "curl_setup.h"
-
-#define PORT_FTP 21
-#define PORT_FTPS 990
-#define PORT_TELNET 23
-#define PORT_HTTP 80
-#define PORT_HTTPS 443
-#define PORT_DICT 2628
-#define PORT_LDAP 389
-#define PORT_LDAPS 636
-#define PORT_TFTP 69
-#define PORT_SSH 22
-#define PORT_IMAP 143
-#define PORT_IMAPS 993
-#define PORT_POP3 110
-#define PORT_POP3S 995
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* This file is for lib internal stuff */
+
+#include "curl_setup.h"
+
+#define PORT_FTP 21
+#define PORT_FTPS 990
+#define PORT_TELNET 23
+#define PORT_HTTP 80
+#define PORT_HTTPS 443
+#define PORT_DICT 2628
+#define PORT_LDAP 389
+#define PORT_LDAPS 636
+#define PORT_TFTP 69
+#define PORT_SSH 22
+#define PORT_IMAP 143
+#define PORT_IMAPS 993
+#define PORT_POP3 110
+#define PORT_POP3S 995
#define PORT_SMB 445
#define PORT_SMBS 445
-#define PORT_SMTP 25
-#define PORT_SMTPS 465 /* sometimes called SSMTP */
-#define PORT_RTSP 554
-#define PORT_RTMP 1935
-#define PORT_RTMPT PORT_HTTP
-#define PORT_RTMPS PORT_HTTPS
-#define PORT_GOPHER 70
+#define PORT_SMTP 25
+#define PORT_SMTPS 465 /* sometimes called SSMTP */
+#define PORT_RTSP 554
+#define PORT_RTMP 1935
+#define PORT_RTMPT PORT_HTTP
+#define PORT_RTMPS PORT_HTTPS
+#define PORT_GOPHER 70
#define PORT_MQTT 1883
-
-#define DICT_MATCH "/MATCH:"
-#define DICT_MATCH2 "/M:"
-#define DICT_MATCH3 "/FIND:"
-#define DICT_DEFINE "/DEFINE:"
-#define DICT_DEFINE2 "/D:"
-#define DICT_DEFINE3 "/LOOKUP:"
-
-#define CURL_DEFAULT_USER "anonymous"
-#define CURL_DEFAULT_PASSWORD "ftp@example.com"
-
+
+#define DICT_MATCH "/MATCH:"
+#define DICT_MATCH2 "/M:"
+#define DICT_MATCH3 "/FIND:"
+#define DICT_DEFINE "/DEFINE:"
+#define DICT_DEFINE2 "/D:"
+#define DICT_DEFINE3 "/LOOKUP:"
+
+#define CURL_DEFAULT_USER "anonymous"
+#define CURL_DEFAULT_PASSWORD "ftp@example.com"
+
/* Convenience defines for checking protocols or their SSL based version. Each
protocol handler should only ever have a single CURLPROTO_ in its protocol
field. */
@@ -71,39 +71,39 @@
#define PROTO_FAMILY_SMTP (CURLPROTO_SMTP|CURLPROTO_SMTPS)
#define PROTO_FAMILY_SSH (CURLPROTO_SCP|CURLPROTO_SFTP)
-#define DEFAULT_CONNCACHE_SIZE 5
-
-/* length of longest IPv6 address string including the trailing null */
-#define MAX_IPADR_LEN sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
-
+#define DEFAULT_CONNCACHE_SIZE 5
+
+/* length of longest IPv6 address string including the trailing null */
+#define MAX_IPADR_LEN sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
+
/* Default FTP/IMAP etc response timeout in milliseconds */
#define RESP_TIMEOUT (120*1000)
-
+
/* Max string input length is a precaution against abuse and to detect junk
input easier and better. */
#define CURL_MAX_INPUT_LENGTH 8000000
-#include "cookie.h"
+#include "cookie.h"
#include "psl.h"
-#include "formdata.h"
-
-#ifdef HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
+#include "formdata.h"
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
#ifdef HAVE_NETINET_IN6_H
#error #include <netinet/in6.h>
#endif
-
-#include "timeval.h"
-
-#include <curl/curl.h>
-
-#include "http_chunks.h" /* for the structs and enum stuff */
-#include "hostip.h"
-#include "hash.h"
-#include "splay.h"
+
+#include "timeval.h"
+
+#include <curl/curl.h>
+
+#include "http_chunks.h" /* for the structs and enum stuff */
+#include "hostip.h"
+#include "hash.h"
+#include "splay.h"
#include "dynbuf.h"
-
+
/* return the count of bytes sent, or -1 on error */
typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */
int sockindex, /* socketindex */
@@ -119,42 +119,42 @@ typedef ssize_t (Curl_recv)(struct connectdata *conn, /* connection data */
CURLcode *err); /* error to return */
#include "mime.h"
-#include "imap.h"
-#include "pop3.h"
-#include "smtp.h"
-#include "ftp.h"
-#include "file.h"
+#include "imap.h"
+#include "pop3.h"
+#include "smtp.h"
+#include "ftp.h"
+#include "file.h"
#include "vssh/ssh.h"
-#include "http.h"
-#include "rtsp.h"
+#include "http.h"
+#include "rtsp.h"
#include "smb.h"
#include "mqtt.h"
-#include "wildcard.h"
-#include "multihandle.h"
+#include "wildcard.h"
+#include "multihandle.h"
#include "quic.h"
-
-#ifdef HAVE_GSSAPI
-# ifdef HAVE_GSSGNU
-# include <gss.h>
+
+#ifdef HAVE_GSSAPI
+# ifdef HAVE_GSSGNU
+# include <gss.h>
# elif defined HAVE_GSSAPI_GSSAPI_H
-# include <gssapi/gssapi.h>
-# else
-# include <gssapi.h>
-# endif
+# include <gssapi/gssapi.h>
+# else
+# include <gssapi.h>
+# endif
# ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
# include <gssapi/gssapi_generic.h>
# endif
-#endif
-
-#ifdef HAVE_LIBSSH2_H
+#endif
+
+#ifdef HAVE_LIBSSH2_H
#error #include <libssh2.h>
#error #include <libssh2_sftp.h>
-#endif /* HAVE_LIBSSH2_H */
-
-#define CURLEASY_MAGIC_NUMBER 0xc0dedbadU
+#endif /* HAVE_LIBSSH2_H */
+
+#define CURLEASY_MAGIC_NUMBER 0xc0dedbadU
#define GOOD_EASY_HANDLE(x) \
((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER))
-
+
/* the type we use for storing a single boolean bit */
#ifdef _MSC_VER
typedef bool bit;
@@ -164,67 +164,67 @@ typedef unsigned int bit;
#define BIT(x) bit x:1
#endif
-#ifdef HAVE_GSSAPI
-/* Types needed for krb5-ftp connections */
-struct krb5buffer {
- void *data;
- size_t size;
- size_t index;
+#ifdef HAVE_GSSAPI
+/* Types needed for krb5-ftp connections */
+struct krb5buffer {
+ void *data;
+ size_t size;
+ size_t index;
BIT(eof_flag);
-};
-
-enum protection_level {
- PROT_NONE, /* first in list */
- PROT_CLEAR,
- PROT_SAFE,
- PROT_CONFIDENTIAL,
- PROT_PRIVATE,
- PROT_CMD,
- PROT_LAST /* last in list */
-};
-#endif
-
-/* enum for the nonblocking SSL connection state machine */
-typedef enum {
- ssl_connect_1,
- ssl_connect_2,
- ssl_connect_2_reading,
- ssl_connect_2_writing,
- ssl_connect_3,
- ssl_connect_done
-} ssl_connect_state;
-
-typedef enum {
- ssl_connection_none,
- ssl_connection_negotiating,
- ssl_connection_complete
-} ssl_connection_state;
-
+};
+
+enum protection_level {
+ PROT_NONE, /* first in list */
+ PROT_CLEAR,
+ PROT_SAFE,
+ PROT_CONFIDENTIAL,
+ PROT_PRIVATE,
+ PROT_CMD,
+ PROT_LAST /* last in list */
+};
+#endif
+
+/* enum for the nonblocking SSL connection state machine */
+typedef enum {
+ ssl_connect_1,
+ ssl_connect_2,
+ ssl_connect_2_reading,
+ ssl_connect_2_writing,
+ ssl_connect_3,
+ ssl_connect_done
+} ssl_connect_state;
+
+typedef enum {
+ ssl_connection_none,
+ ssl_connection_negotiating,
+ ssl_connection_complete
+} ssl_connection_state;
+
/* SSL backend-specific data; declared differently by each SSL backend */
struct ssl_backend_data;
-/* struct for data related to each SSL connection */
-struct ssl_connect_data {
- ssl_connection_state state;
- ssl_connect_state connecting_state;
+/* struct for data related to each SSL connection */
+struct ssl_connect_data {
+ ssl_connection_state state;
+ ssl_connect_state connecting_state;
#if defined(USE_SSL)
struct ssl_backend_data *backend;
-#endif
+#endif
/* Use ssl encrypted communications TRUE/FALSE. The library is not
necessarily using ssl at the moment but at least asked to or means to use
it. See 'state' for the exact current state of the connection. */
BIT(use);
-};
-
+};
+
struct ssl_primary_config {
- long version; /* what version the client wants to use */
+ long version; /* what version the client wants to use */
long version_max; /* max supported version the client wants to use*/
- char *CApath; /* certificate dir (doesn't work on windows) */
- char *CAfile; /* certificate to verify peer against */
+ char *CApath; /* certificate dir (doesn't work on windows) */
+ char *CAfile; /* certificate to verify peer against */
char *clientcert;
- char *random_file; /* path to file containing "random" data */
- char *egdsocket; /* path to file containing the EGD daemon socket */
- char *cipher_list; /* list of ciphers to use */
+ char *random_file; /* path to file containing "random" data */
+ char *egdsocket; /* path to file containing the EGD daemon socket */
+ char *cipher_list; /* list of ciphers to use */
char *cipher_list13; /* list of TLS 1.3 cipher suites to use */
char *pinned_key;
struct curl_blob *cert_blob;
@@ -241,18 +241,18 @@ struct ssl_config_data {
char *CRLfile; /* CRL to check certificate revocation */
char *issuercert;/* optional issuer certificate filename */
struct curl_blob *issuercert_blob;
- curl_ssl_ctx_callback fsslctx; /* function to initialize ssl ctx */
- void *fsslctxp; /* parameter for call back */
+ curl_ssl_ctx_callback fsslctx; /* function to initialize ssl ctx */
+ void *fsslctxp; /* parameter for call back */
char *cert_type; /* format for certificate (default: PEM)*/
char *key; /* private key file name */
struct curl_blob *key_blob;
char *key_type; /* format for private key (default: PEM) */
char *key_passwd; /* plain text private key password */
-#ifdef USE_TLS_SRP
- char *username; /* TLS username (for, e.g., SRP) */
- char *password; /* TLS password (for, e.g., SRP) */
- enum CURL_TLSAUTH authtype; /* TLS authentication type (default SRP) */
-#endif
+#ifdef USE_TLS_SRP
+ char *username; /* TLS username (for, e.g., SRP) */
+ char *password; /* TLS password (for, e.g., SRP) */
+ enum CURL_TLSAUTH authtype; /* TLS authentication type (default SRP) */
+#endif
BIT(certinfo); /* gather lots of certificate info */
BIT(falsestart);
BIT(enable_beast); /* allow this flaw for interoperability's sake*/
@@ -261,31 +261,31 @@ struct ssl_config_data {
BIT(revoke_best_effort); /* ignore SSL revocation offline/missing revocation
list errors */
BIT(native_ca_store); /* use the native ca store of operating system */
-};
-
+};
+
struct ssl_general_config {
size_t max_ssl_sessions; /* SSL session id cache size */
};
-/* information stored about one single SSL session */
+/* information stored about one single SSL session */
struct Curl_ssl_session {
- char *name; /* host name for which this ID was used */
+ char *name; /* host name for which this ID was used */
char *conn_to_host; /* host name for the connection (may be NULL) */
const char *scheme; /* protocol scheme used */
- void *sessionid; /* as returned from the SSL layer */
- size_t idsize; /* if known, otherwise 0 */
- long age; /* just a number, the higher the more recent */
+ void *sessionid; /* as returned from the SSL layer */
+ size_t idsize; /* if known, otherwise 0 */
+ long age; /* just a number, the higher the more recent */
int remote_port; /* remote port */
int conn_to_port; /* remote port for the connection (may be -1) */
struct ssl_primary_config ssl_config; /* setup for this session */
-};
-
+};
+
#ifdef USE_WINDOWS_SSPI
#include "curl_sspi.h"
#endif
-/* Struct used for Digest challenge-response authentication */
-struct digestdata {
+/* Struct used for Digest challenge-response authentication */
+struct digestdata {
#if defined(USE_WINDOWS_SSPI)
BYTE *input_token;
size_t input_token_len;
@@ -295,27 +295,27 @@ struct digestdata {
char *user;
char *passwd;
#else
- char *nonce;
- char *cnonce;
- char *realm;
- int algo;
- char *opaque;
- char *qop;
- char *algorithm;
- int nc; /* nounce count */
+ char *nonce;
+ char *cnonce;
+ char *realm;
+ int algo;
+ char *opaque;
+ char *qop;
+ char *algorithm;
+ int nc; /* nounce count */
BIT(stale); /* set true for re-negotiation */
BIT(userhash);
#endif
-};
-
-typedef enum {
- NTLMSTATE_NONE,
- NTLMSTATE_TYPE1,
- NTLMSTATE_TYPE2,
- NTLMSTATE_TYPE3,
- NTLMSTATE_LAST
-} curlntlm;
-
+};
+
+typedef enum {
+ NTLMSTATE_NONE,
+ NTLMSTATE_TYPE1,
+ NTLMSTATE_TYPE2,
+ NTLMSTATE_TYPE3,
+ NTLMSTATE_LAST
+} curlntlm;
+
typedef enum {
GSS_AUTHNONE,
GSS_AUTHRECV,
@@ -324,10 +324,10 @@ typedef enum {
GSS_AUTHSUCC
} curlnegotiate;
-#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
-#include <iconv.h>
-#endif
-
+#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
+#include <iconv.h>
+#endif
+
/* Struct used for GSSAPI (Kerberos V5) authentication */
#if defined(USE_KERBEROS5)
struct kerberos5data {
@@ -346,10 +346,10 @@ struct kerberos5data {
};
#endif
-/* Struct used for NTLM challenge-response authentication */
+/* Struct used for NTLM challenge-response authentication */
#if defined(USE_NTLM)
-struct ntlmdata {
-#ifdef USE_WINDOWS_SSPI
+struct ntlmdata {
+#ifdef USE_WINDOWS_SSPI
/* The sslContext is used for the Schannel bindings. The
* api is available on the Windows 7 SDK and later.
*/
@@ -358,16 +358,16 @@ struct ntlmdata {
#endif
CredHandle *credentials;
CtxtHandle *context;
- SEC_WINNT_AUTH_IDENTITY identity;
- SEC_WINNT_AUTH_IDENTITY *p_identity;
+ SEC_WINNT_AUTH_IDENTITY identity;
+ SEC_WINNT_AUTH_IDENTITY *p_identity;
size_t token_max;
BYTE *output_token;
BYTE *input_token;
size_t input_token_len;
TCHAR *spn;
-#else
- unsigned int flags;
- unsigned char nonce[8];
+#else
+ unsigned int flags;
+ unsigned char nonce[8];
void *target_info; /* TargetInfo received in the ntlm type-2 message */
unsigned int target_info_len;
@@ -377,47 +377,47 @@ struct ntlmdata {
pid_t ntlm_auth_hlpr_pid;
char *challenge; /* The received base64 encoded ntlm type-2 message */
char *response; /* The generated base64 ntlm type-1/type-3 message */
-#endif
#endif
-};
#endif
-
+};
+#endif
+
/* Struct used for Negotiate (SPNEGO) authentication */
#ifdef USE_SPNEGO
-struct negotiatedata {
-#ifdef HAVE_GSSAPI
- OM_uint32 status;
- gss_ctx_id_t context;
+struct negotiatedata {
+#ifdef HAVE_GSSAPI
+ OM_uint32 status;
+ gss_ctx_id_t context;
gss_name_t spn;
- gss_buffer_desc output_token;
-#else
-#ifdef USE_WINDOWS_SSPI
+ gss_buffer_desc output_token;
+#else
+#ifdef USE_WINDOWS_SSPI
#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS
CtxtHandle *sslContext;
#endif
- DWORD status;
+ DWORD status;
CredHandle *credentials;
- CtxtHandle *context;
+ CtxtHandle *context;
SEC_WINNT_AUTH_IDENTITY identity;
SEC_WINNT_AUTH_IDENTITY *p_identity;
TCHAR *spn;
size_t token_max;
- BYTE *output_token;
- size_t output_token_length;
-#endif
-#endif
+ BYTE *output_token;
+ size_t output_token_length;
+#endif
+#endif
BIT(noauthpersist);
BIT(havenoauthpersist);
BIT(havenegdata);
BIT(havemultiplerequests);
-};
-#endif
-
-
-/*
- * Boolean values that concerns this connection.
- */
-struct ConnectBits {
+};
+#endif
+
+
+/*
+ * Boolean values that concerns this connection.
+ */
+struct ConnectBits {
bool tcpconnect[2]; /* the TCP layer (or similar) is connected, this is set
the first time on the first connect function call */
#ifndef CURL_DISABLE_PROXY
@@ -488,58 +488,58 @@ struct ConnectBits {
accept() */
BIT(parallel_connect); /* set TRUE when a parallel connect attempt has
started (happy eyeballs) */
-};
-
-struct hostname {
- char *rawalloc; /* allocated "raw" version of the name */
- char *encalloc; /* allocated IDN-encoded version of the name */
- char *name; /* name to use internally, might be encoded, might be raw */
- const char *dispname; /* name to display, as 'name' might be encoded */
-};
-
-/*
- * Flags on the keepon member of the Curl_transfer_keeper
- */
-
-#define KEEP_NONE 0
-#define KEEP_RECV (1<<0) /* there is or may be data to read */
-#define KEEP_SEND (1<<1) /* there is or may be data to write */
-#define KEEP_RECV_HOLD (1<<2) /* when set, no reading should be done but there
- might still be data to read */
-#define KEEP_SEND_HOLD (1<<3) /* when set, no writing should be done but there
- might still be data to write */
-#define KEEP_RECV_PAUSE (1<<4) /* reading is paused */
-#define KEEP_SEND_PAUSE (1<<5) /* writing is paused */
-
-#define KEEP_RECVBITS (KEEP_RECV | KEEP_RECV_HOLD | KEEP_RECV_PAUSE)
-#define KEEP_SENDBITS (KEEP_SEND | KEEP_SEND_HOLD | KEEP_SEND_PAUSE)
-
-struct Curl_async {
- char *hostname;
- int port;
- struct Curl_dns_entry *dns;
- int status; /* if done is TRUE, this is the status from the callback */
+};
+
+struct hostname {
+ char *rawalloc; /* allocated "raw" version of the name */
+ char *encalloc; /* allocated IDN-encoded version of the name */
+ char *name; /* name to use internally, might be encoded, might be raw */
+ const char *dispname; /* name to display, as 'name' might be encoded */
+};
+
+/*
+ * Flags on the keepon member of the Curl_transfer_keeper
+ */
+
+#define KEEP_NONE 0
+#define KEEP_RECV (1<<0) /* there is or may be data to read */
+#define KEEP_SEND (1<<1) /* there is or may be data to write */
+#define KEEP_RECV_HOLD (1<<2) /* when set, no reading should be done but there
+ might still be data to read */
+#define KEEP_SEND_HOLD (1<<3) /* when set, no writing should be done but there
+ might still be data to write */
+#define KEEP_RECV_PAUSE (1<<4) /* reading is paused */
+#define KEEP_SEND_PAUSE (1<<5) /* writing is paused */
+
+#define KEEP_RECVBITS (KEEP_RECV | KEEP_RECV_HOLD | KEEP_RECV_PAUSE)
+#define KEEP_SENDBITS (KEEP_SEND | KEEP_SEND_HOLD | KEEP_SEND_PAUSE)
+
+struct Curl_async {
+ char *hostname;
+ int port;
+ struct Curl_dns_entry *dns;
+ int status; /* if done is TRUE, this is the status from the callback */
struct thread_data *tdata;
BIT(done); /* set TRUE when the lookup is complete */
-};
-
-#define FIRSTSOCKET 0
-#define SECONDARYSOCKET 1
-
-/* These function pointer types are here only to allow easier typecasting
- within the source when we need to cast between data pointers (such as NULL)
- and function pointers. */
-typedef CURLcode (*Curl_do_more_func)(struct connectdata *, int *);
-typedef CURLcode (*Curl_done_func)(struct connectdata *, CURLcode, bool);
-
-enum expect100 {
- EXP100_SEND_DATA, /* enough waiting, just send the body now */
- EXP100_AWAITING_CONTINUE, /* waiting for the 100 Continue header */
- EXP100_SENDING_REQUEST, /* still sending the request but will wait for
- the 100 header once done with the request */
- EXP100_FAILED /* used on 417 Expectation Failed */
-};
-
+};
+
+#define FIRSTSOCKET 0
+#define SECONDARYSOCKET 1
+
+/* These function pointer types are here only to allow easier typecasting
+ within the source when we need to cast between data pointers (such as NULL)
+ and function pointers. */
+typedef CURLcode (*Curl_do_more_func)(struct connectdata *, int *);
+typedef CURLcode (*Curl_done_func)(struct connectdata *, CURLcode, bool);
+
+enum expect100 {
+ EXP100_SEND_DATA, /* enough waiting, just send the body now */
+ EXP100_AWAITING_CONTINUE, /* waiting for the 100 Continue header */
+ EXP100_SENDING_REQUEST, /* still sending the request but will wait for
+ the 100 header once done with the request */
+ EXP100_FAILED /* used on 417 Expectation Failed */
+};
+
enum upgrade101 {
UPGR101_INIT, /* default state */
UPGR101_REQUESTED, /* upgrade requested */
@@ -582,20 +582,20 @@ struct dohdata {
int port;
};
-/*
+/*
* Request specific data in the easy handle (Curl_easy). Previously,
- * these members were on the connectdata struct but since a conn struct may
+ * these members were on the connectdata struct but since a conn struct may
* now be shared between different Curl_easys, we store connection-specific
- * data here. This struct only keeps stuff that's interesting for *this*
- * request, as it will be cleared between multiple ones
- */
-struct SingleRequest {
- curl_off_t size; /* -1 if unknown at this point */
- curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch,
- -1 means unlimited */
- curl_off_t bytecount; /* total number of bytes read */
- curl_off_t writebytecount; /* number of bytes written */
-
+ * data here. This struct only keeps stuff that's interesting for *this*
+ * request, as it will be cleared between multiple ones
+ */
+struct SingleRequest {
+ curl_off_t size; /* -1 if unknown at this point */
+ curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch,
+ -1 means unlimited */
+ curl_off_t bytecount; /* total number of bytes read */
+ curl_off_t writebytecount; /* number of bytes written */
+
curl_off_t headerbytecount; /* only count received headers */
curl_off_t deductheadercount; /* this amount of bytes doesn't count when we
check if anything has been transferred at
@@ -603,46 +603,46 @@ struct SingleRequest {
counter to make only a 100 reply (without a
following second response code) result in a
CURLE_GOT_NOTHING error code */
-
+
struct curltime start; /* transfer started at this time */
struct curltime now; /* current time */
- enum {
- HEADER_NORMAL, /* no bad header at all */
- HEADER_PARTHEADER, /* part of the chunk is a bad header, the rest
- is normal data */
- HEADER_ALLBAD /* all was believed to be header */
- } badheader; /* the header was deemed bad and will be
- written as body */
- int headerline; /* counts header lines to better track the
- first one */
- char *str; /* within buf */
- curl_off_t offset; /* possible resume offset read from the
- Content-Range: header */
- int httpcode; /* error code from the 'HTTP/1.? XXX' or
- 'RTSP/1.? XXX' line */
+ enum {
+ HEADER_NORMAL, /* no bad header at all */
+ HEADER_PARTHEADER, /* part of the chunk is a bad header, the rest
+ is normal data */
+ HEADER_ALLBAD /* all was believed to be header */
+ } badheader; /* the header was deemed bad and will be
+ written as body */
+ int headerline; /* counts header lines to better track the
+ first one */
+ char *str; /* within buf */
+ curl_off_t offset; /* possible resume offset read from the
+ Content-Range: header */
+ int httpcode; /* error code from the 'HTTP/1.? XXX' or
+ 'RTSP/1.? XXX' line */
struct curltime start100; /* time stamp to wait for the 100 code from */
- enum expect100 exp100; /* expect 100 continue state */
+ enum expect100 exp100; /* expect 100 continue state */
enum upgrade101 upgr101; /* 101 upgrade state */
-
+
/* Content unencoding stack. See sec 3.5, RFC2616. */
struct contenc_writer *writer_stack;
- time_t timeofdoc;
- long bodywrites;
- int keepon;
- char *location; /* This points to an allocated version of the Location:
- header data */
- char *newurl; /* Set to the new URL to use when a redirect or a retry is
- wanted */
-
- /* 'upload_present' is used to keep a byte counter of how much data there is
- still left in the buffer, aimed for upload. */
- ssize_t upload_present;
-
+ time_t timeofdoc;
+ long bodywrites;
+ int keepon;
+ char *location; /* This points to an allocated version of the Location:
+ header data */
+ char *newurl; /* Set to the new URL to use when a redirect or a retry is
+ wanted */
+
+ /* 'upload_present' is used to keep a byte counter of how much data there is
+ still left in the buffer, aimed for upload. */
+ ssize_t upload_present;
+
/* 'upload_fromhere' is used as a read-pointer when we uploaded parts of a
buffer, so the next read should read from where this pointer points to,
and the 'upload_present' contains the number of bytes available at this
position */
- char *upload_fromhere;
+ char *upload_fromhere;
/* Allocated protocol-specific data. Each protocol handler makes sure this
points to data it needs. */
@@ -677,101 +677,101 @@ struct SingleRequest {
BIT(forbidchunk); /* used only to explicitly forbid chunk-upload for
specific upload buffers. See readmoredata() in http.c
for details. */
-};
-
-/*
- * Specific protocol handler.
- */
-
-struct Curl_handler {
+};
+
+/*
+ * Specific protocol handler.
+ */
+
+struct Curl_handler {
const char *scheme; /* URL scheme name. */
-
- /* Complement to setup_connection_internals(). */
- CURLcode (*setup_connection)(struct connectdata *);
-
- /* These two functions MUST be set to be protocol dependent */
- CURLcode (*do_it)(struct connectdata *, bool *done);
- Curl_done_func done;
-
- /* If the curl_do() function is better made in two halves, this
- * curl_do_more() function will be called afterwards, if set. For example
- * for doing the FTP stuff after the PASV/PORT command.
- */
- Curl_do_more_func do_more;
-
- /* This function *MAY* be set to a protocol-dependent function that is run
- * after the connect() and everything is done, as a step in the connection.
- * The 'done' pointer points to a bool that should be set to TRUE if the
- * function completes before return. If it doesn't complete, the caller
- * should call the curl_connecting() function until it is.
- */
- CURLcode (*connect_it)(struct connectdata *, bool *done);
-
+
+ /* Complement to setup_connection_internals(). */
+ CURLcode (*setup_connection)(struct connectdata *);
+
+ /* These two functions MUST be set to be protocol dependent */
+ CURLcode (*do_it)(struct connectdata *, bool *done);
+ Curl_done_func done;
+
+ /* If the curl_do() function is better made in two halves, this
+ * curl_do_more() function will be called afterwards, if set. For example
+ * for doing the FTP stuff after the PASV/PORT command.
+ */
+ Curl_do_more_func do_more;
+
+ /* This function *MAY* be set to a protocol-dependent function that is run
+ * after the connect() and everything is done, as a step in the connection.
+ * The 'done' pointer points to a bool that should be set to TRUE if the
+ * function completes before return. If it doesn't complete, the caller
+ * should call the curl_connecting() function until it is.
+ */
+ CURLcode (*connect_it)(struct connectdata *, bool *done);
+
/* See above. */
- CURLcode (*connecting)(struct connectdata *, bool *done);
- CURLcode (*doing)(struct connectdata *, bool *done);
-
- /* Called from the multi interface during the PROTOCONNECT phase, and it
- should then return a proper fd set */
- int (*proto_getsock)(struct connectdata *conn,
+ CURLcode (*connecting)(struct connectdata *, bool *done);
+ CURLcode (*doing)(struct connectdata *, bool *done);
+
+ /* Called from the multi interface during the PROTOCONNECT phase, and it
+ should then return a proper fd set */
+ int (*proto_getsock)(struct connectdata *conn,
curl_socket_t *socks);
-
- /* Called from the multi interface during the DOING phase, and it should
- then return a proper fd set */
- int (*doing_getsock)(struct connectdata *conn,
+
+ /* Called from the multi interface during the DOING phase, and it should
+ then return a proper fd set */
+ int (*doing_getsock)(struct connectdata *conn,
curl_socket_t *socks);
-
- /* Called from the multi interface during the DO_MORE phase, and it should
- then return a proper fd set */
- int (*domore_getsock)(struct connectdata *conn,
+
+ /* Called from the multi interface during the DO_MORE phase, and it should
+ then return a proper fd set */
+ int (*domore_getsock)(struct connectdata *conn,
curl_socket_t *socks);
-
- /* Called from the multi interface during the DO_DONE, PERFORM and
- WAITPERFORM phases, and it should then return a proper fd set. Not setting
- this will make libcurl use the generic default one. */
- int (*perform_getsock)(const struct connectdata *conn,
+
+ /* Called from the multi interface during the DO_DONE, PERFORM and
+ WAITPERFORM phases, and it should then return a proper fd set. Not setting
+ this will make libcurl use the generic default one. */
+ int (*perform_getsock)(const struct connectdata *conn,
curl_socket_t *socks);
-
- /* This function *MAY* be set to a protocol-dependent function that is run
- * by the curl_disconnect(), as a step in the disconnection. If the handler
- * is called because the connection has been considered dead, dead_connection
- * is set to TRUE.
- */
- CURLcode (*disconnect)(struct connectdata *, bool dead_connection);
-
- /* If used, this function gets called from transfer.c:readwrite_data() to
- allow the protocol to do extra reads/writes */
+
+ /* This function *MAY* be set to a protocol-dependent function that is run
+ * by the curl_disconnect(), as a step in the disconnection. If the handler
+ * is called because the connection has been considered dead, dead_connection
+ * is set to TRUE.
+ */
+ CURLcode (*disconnect)(struct connectdata *, bool dead_connection);
+
+ /* If used, this function gets called from transfer.c:readwrite_data() to
+ allow the protocol to do extra reads/writes */
CURLcode (*readwrite)(struct Curl_easy *data, struct connectdata *conn,
- ssize_t *nread, bool *readmore);
-
+ ssize_t *nread, bool *readmore);
+
/* This function can perform various checks on the connection. See
CONNCHECK_* for more information about the checks that can be performed,
and CONNRESULT_* for the results that can be returned. */
unsigned int (*connection_check)(struct connectdata *conn,
unsigned int checks_to_perform);
- long defport; /* Default port. */
+ long defport; /* Default port. */
unsigned int protocol; /* See CURLPROTO_* - this needs to be the single
specific protocol bit */
unsigned int family; /* single bit for protocol family; basically the
non-TLS name of the protocol this is */
- unsigned int flags; /* Extra particular characteristics, see PROTOPT_* */
-};
-
-#define PROTOPT_NONE 0 /* nothing extra */
-#define PROTOPT_SSL (1<<0) /* uses SSL */
-#define PROTOPT_DUAL (1<<1) /* this protocol uses two connections */
-#define PROTOPT_CLOSEACTION (1<<2) /* need action before socket close */
-/* some protocols will have to call the underlying functions without regard to
- what exact state the socket signals. IE even if the socket says "readable",
- the send function might need to be called while uploading, or vice versa.
-*/
-#define PROTOPT_DIRLOCK (1<<3)
-#define PROTOPT_NONETWORK (1<<4) /* protocol doesn't use the network! */
-#define PROTOPT_NEEDSPWD (1<<5) /* needs a password, and if none is set it
- gets a default */
-#define PROTOPT_NOURLQUERY (1<<6) /* protocol can't handle
- url query strings (?foo=bar) ! */
+ unsigned int flags; /* Extra particular characteristics, see PROTOPT_* */
+};
+
+#define PROTOPT_NONE 0 /* nothing extra */
+#define PROTOPT_SSL (1<<0) /* uses SSL */
+#define PROTOPT_DUAL (1<<1) /* this protocol uses two connections */
+#define PROTOPT_CLOSEACTION (1<<2) /* need action before socket close */
+/* some protocols will have to call the underlying functions without regard to
+ what exact state the socket signals. IE even if the socket says "readable",
+ the send function might need to be called while uploading, or vice versa.
+*/
+#define PROTOPT_DIRLOCK (1<<3)
+#define PROTOPT_NONETWORK (1<<4) /* protocol doesn't use the network! */
+#define PROTOPT_NEEDSPWD (1<<5) /* needs a password, and if none is set it
+ gets a default */
+#define PROTOPT_NOURLQUERY (1<<6) /* protocol can't handle
+ url query strings (?foo=bar) ! */
#define PROTOPT_CREDSPERREQUEST (1<<7) /* requires login credentials per
request instead of per connection */
#define PROTOPT_ALPN_NPN (1<<8) /* set ALPN and/or NPN for this */
@@ -784,14 +784,14 @@ struct Curl_handler {
#define PROTOPT_WILDCARD (1<<12) /* protocol supports wildcard matching */
#define PROTOPT_USERPWDCTRL (1<<13) /* Allow "control bytes" (< 32 ascii) in
user name and password */
-
+
#define CONNCHECK_NONE 0 /* No checks */
#define CONNCHECK_ISDEAD (1<<0) /* Check if the connection is dead. */
#define CONNCHECK_KEEPALIVE (1<<1) /* Perform any keepalive function. */
-
+
#define CONNRESULT_NONE 0 /* No extra information. */
#define CONNRESULT_DEAD (1<<0) /* The connection is dead. */
-
+
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
struct postponed_data {
char *buffer; /* Temporal store for received data during
@@ -805,7 +805,7 @@ struct postponed_data {
#endif /* DEBUGBUILD */
};
#endif /* USE_RECV_BEFORE_SEND_WORKAROUND */
-
+
struct proxy_info {
struct hostname host;
long port;
@@ -869,67 +869,67 @@ struct connstate {
unsigned char *outp; /* send from this pointer */
};
-/*
- * The connectdata struct contains all fields and variables that should be
- * unique for an entire connection.
- */
-struct connectdata {
+/*
+ * The connectdata struct contains all fields and variables that should be
+ * unique for an entire connection.
+ */
+struct connectdata {
/* 'data' is the CURRENT Curl_easy using this connection -- take great
- caution that this might very well vary between different times this
- connection is used! */
+ caution that this might very well vary between different times this
+ connection is used! */
struct Curl_easy *data;
struct connstate cnnct;
struct Curl_llist_element bundle_node; /* conncache */
-
- /* chunk is for HTTP chunked encoding, but is in the general connectdata
- struct only because we can do just about any protocol through a HTTP proxy
- and a HTTP proxy may in fact respond using chunked encoding */
- struct Curl_chunker chunk;
-
- curl_closesocket_callback fclosesocket; /* function closing the socket(s) */
- void *closesocket_client;
-
+
+ /* chunk is for HTTP chunked encoding, but is in the general connectdata
+ struct only because we can do just about any protocol through a HTTP proxy
+ and a HTTP proxy may in fact respond using chunked encoding */
+ struct Curl_chunker chunk;
+
+ curl_closesocket_callback fclosesocket; /* function closing the socket(s) */
+ void *closesocket_client;
+
/* This is used by the connection cache logic. If this returns TRUE, this
handle is still used by one or more easy handles and can only used by any
other easy handle without careful consideration (== only for
multiplexing) and it cannot be used by another multi handle! */
#define CONN_INUSE(c) ((c)->easyq.size)
-
- /**** Fields set when inited and not modified again */
- long connection_id; /* Contains a unique number to make it easier to
- track the connections in the log output */
-
- /* 'dns_entry' is the particular host we use. This points to an entry in the
- DNS cache and it will not get pruned while locked. It gets unlocked in
+
+ /**** Fields set when inited and not modified again */
+ long connection_id; /* Contains a unique number to make it easier to
+ track the connections in the log output */
+
+ /* 'dns_entry' is the particular host we use. This points to an entry in the
+ DNS cache and it will not get pruned while locked. It gets unlocked in
multi_done(). This entry will be NULL if the connection is re-used as then
- there is no name resolve done. */
- struct Curl_dns_entry *dns_entry;
-
- /* 'ip_addr' is the particular IP we connected to. It points to a struct
- within the DNS cache, so this pointer is only valid as long as the DNS
+ there is no name resolve done. */
+ struct Curl_dns_entry *dns_entry;
+
+ /* 'ip_addr' is the particular IP we connected to. It points to a struct
+ within the DNS cache, so this pointer is only valid as long as the DNS
cache entry remains locked. It gets unlocked in multi_done() */
struct Curl_addrinfo *ip_addr;
struct Curl_addrinfo *tempaddr[2]; /* for happy eyeballs */
-
- /* 'ip_addr_str' is the ip_addr data as a human readable string.
- It remains available as long as the connection does, which is longer than
- the ip_addr itself. */
- char ip_addr_str[MAX_IPADR_LEN];
-
+
+ /* 'ip_addr_str' is the ip_addr data as a human readable string.
+ It remains available as long as the connection does, which is longer than
+ the ip_addr itself. */
+ char ip_addr_str[MAX_IPADR_LEN];
+
unsigned int scope_id; /* Scope id for IPv6 */
-
+
enum {
TRNSPRT_TCP = 3,
TRNSPRT_UDP = 4,
TRNSPRT_QUIC = 5
} transport;
-
+
#ifdef ENABLE_QUIC
struct quicsocket hequic[2]; /* two, for happy eyeballs! */
struct quicsocket *quic;
#endif
- struct hostname host;
+ struct hostname host;
char *hostname_resolve; /* host name to resolve to address, allocated */
char *secondaryhostname; /* secondary socket host name (ftp) */
struct hostname conn_to_host; /* the host to connect to. valid only if
@@ -938,53 +938,53 @@ struct connectdata {
struct proxy_info socks_proxy;
struct proxy_info http_proxy;
#endif
- long port; /* which port to use locally */
+ long port; /* which port to use locally */
int remote_port; /* the remote port, not the proxy port! */
int conn_to_port; /* the remote port to connect to. valid only if
bits.conn_to_port is set */
unsigned short secondary_port; /* secondary socket remote port to connect to
(ftp) */
-
- /* 'primary_ip' and 'primary_port' get filled with peer's numerical
- ip address and port number whenever an outgoing connection is
- *attempted* from the primary socket to a remote address. When more
- than one address is tried for a connection these will hold data
- for the last attempt. When the connection is actually established
- these are updated with data which comes directly from the socket. */
-
- char primary_ip[MAX_IPADR_LEN];
- long primary_port;
-
- /* 'local_ip' and 'local_port' get filled with local's numerical
- ip address and port number whenever an outgoing connection is
- **established** from the primary socket to a remote address. */
-
- char local_ip[MAX_IPADR_LEN];
- long local_port;
-
- char *user; /* user name string, allocated */
- char *passwd; /* password string, allocated */
- char *options; /* options string, allocated */
-
+
+ /* 'primary_ip' and 'primary_port' get filled with peer's numerical
+ ip address and port number whenever an outgoing connection is
+ *attempted* from the primary socket to a remote address. When more
+ than one address is tried for a connection these will hold data
+ for the last attempt. When the connection is actually established
+ these are updated with data which comes directly from the socket. */
+
+ char primary_ip[MAX_IPADR_LEN];
+ long primary_port;
+
+ /* 'local_ip' and 'local_port' get filled with local's numerical
+ ip address and port number whenever an outgoing connection is
+ **established** from the primary socket to a remote address. */
+
+ char local_ip[MAX_IPADR_LEN];
+ long local_port;
+
+ char *user; /* user name string, allocated */
+ char *passwd; /* password string, allocated */
+ char *options; /* options string, allocated */
+
char *sasl_authzid; /* authorisation identity string, allocated */
-
- int httpversion; /* the HTTP version*10 reported by the server */
- int rtspversion; /* the RTSP version*10 reported by the server */
-
+
+ int httpversion; /* the HTTP version*10 reported by the server */
+ int rtspversion; /* the RTSP version*10 reported by the server */
+
struct curltime now; /* "current" time */
struct curltime created; /* creation time */
struct curltime lastused; /* when returned to the connection cache */
- curl_socket_t sock[2]; /* two sockets, the second is used for the data
- transfer when doing FTP */
+ curl_socket_t sock[2]; /* two sockets, the second is used for the data
+ transfer when doing FTP */
curl_socket_t tempsock[2]; /* temporary sockets for happy eyeballs */
int tempfamily[2]; /* family used for the temp sockets */
- Curl_recv *recv[2];
- Curl_send *send[2];
-
+ Curl_recv *recv[2];
+ Curl_send *send[2];
+
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
struct postponed_data postponed[2]; /* two buffers for two sockets */
#endif /* USE_RECV_BEFORE_SEND_WORKAROUND */
- struct ssl_connect_data ssl[2]; /* this is for ssl-stuff */
+ struct ssl_connect_data ssl[2]; /* this is for ssl-stuff */
#ifndef CURL_DISABLE_PROXY
struct ssl_connect_data proxy_ssl[2]; /* this is for proxy ssl-stuff */
#endif
@@ -995,24 +995,24 @@ struct connectdata {
#ifndef CURL_DISABLE_PROXY
struct ssl_primary_config proxy_ssl_config;
#endif
- struct ConnectBits bits; /* various state-flags for this connection */
-
- /* connecttime: when connect() is called on the current IP address. Used to
- be able to track when to move on to try next IP - but only when the multi
- interface is used. */
+ struct ConnectBits bits; /* various state-flags for this connection */
+
+ /* connecttime: when connect() is called on the current IP address. Used to
+ be able to track when to move on to try next IP - but only when the multi
+ interface is used. */
struct curltime connecttime;
- /* The two fields below get set in Curl_connecthost */
- int num_addr; /* number of addresses to try to connect to */
-
+ /* The two fields below get set in Curl_connecthost */
+ int num_addr; /* number of addresses to try to connect to */
+
/* how long time in milliseconds to spend on trying to connect to each IP
address, per family */
timediff_t timeoutms_per_addr[2];
- const struct Curl_handler *handler; /* Connection's protocol handler */
- const struct Curl_handler *given; /* The protocol first given */
-
+ const struct Curl_handler *handler; /* Connection's protocol handler */
+ const struct Curl_handler *given; /* The protocol first given */
+
long ip_version; /* copied from the Curl_easy at creation time */
-
+
/* Protocols can use a custom keepalive mechanism to keep connections alive.
This allows those protocols to track the last time the keepalive mechanism
was used on this connection. */
@@ -1020,48 +1020,48 @@ struct connectdata {
long upkeep_interval_ms; /* Time between calls for connection upkeep. */
- /**** curl_get() phase fields */
-
- curl_socket_t sockfd; /* socket to read from or CURL_SOCKET_BAD */
- curl_socket_t writesockfd; /* socket to write to, it may very
- well be the same we read from.
- CURL_SOCKET_BAD disables */
-
-#ifdef HAVE_GSSAPI
+ /**** curl_get() phase fields */
+
+ curl_socket_t sockfd; /* socket to read from or CURL_SOCKET_BAD */
+ curl_socket_t writesockfd; /* socket to write to, it may very
+ well be the same we read from.
+ CURL_SOCKET_BAD disables */
+
+#ifdef HAVE_GSSAPI
BIT(sec_complete); /* if Kerberos is enabled for this connection */
- enum protection_level command_prot;
- enum protection_level data_prot;
- enum protection_level request_data_prot;
- size_t buffer_size;
- struct krb5buffer in_buffer;
- void *app_data;
- const struct Curl_sec_client_mech *mech;
- struct sockaddr_in local_addr;
-#endif
-
+ enum protection_level command_prot;
+ enum protection_level data_prot;
+ enum protection_level request_data_prot;
+ size_t buffer_size;
+ struct krb5buffer in_buffer;
+ void *app_data;
+ const struct Curl_sec_client_mech *mech;
+ struct sockaddr_in local_addr;
+#endif
+
#if defined(USE_KERBEROS5) /* Consider moving some of the above GSS-API */
struct kerberos5data krb5; /* variables into the structure definition, */
#endif /* however, some of them are ftp specific. */
struct Curl_llist easyq; /* List of easy handles using this connection */
- curl_seek_callback seek_func; /* function that seeks the input */
- void *seek_client; /* pointer to pass to the seek() above */
-
- /*************** Request - specific items ************/
+ curl_seek_callback seek_func; /* function that seeks the input */
+ void *seek_client; /* pointer to pass to the seek() above */
+
+ /*************** Request - specific items ************/
#if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS)
CtxtHandle *sslContext;
#endif
-
+
#if defined(USE_NTLM)
curlntlm http_ntlm_state;
curlntlm proxy_ntlm_state;
- struct ntlmdata ntlm; /* NTLM differs from other authentication schemes
- because it authenticates connections, not
- single requests! */
- struct ntlmdata proxyntlm; /* NTLM data for proxy */
-#endif
-
+ struct ntlmdata ntlm; /* NTLM differs from other authentication schemes
+ because it authenticates connections, not
+ single requests! */
+ struct ntlmdata proxyntlm; /* NTLM data for proxy */
+#endif
+
#ifdef USE_SPNEGO
curlnegotiate http_negotiate_state;
curlnegotiate proxy_negotiate_state;
@@ -1070,125 +1070,125 @@ struct connectdata {
struct negotiatedata proxyneg; /* state data for proxy Negotiate auth */
#endif
- /* data used for the asynch name resolve callback */
- struct Curl_async async;
-
+ /* data used for the asynch name resolve callback */
+ struct Curl_async async;
+
/* for chunked-encoded trailer */
struct dynbuf trailer;
-
- union {
- struct ftp_conn ftpc;
- struct http_conn httpc;
- struct ssh_conn sshc;
- struct tftp_state_data *tftpc;
- struct imap_conn imapc;
- struct pop3_conn pop3c;
- struct smtp_conn smtpc;
- struct rtsp_conn rtspc;
+
+ union {
+ struct ftp_conn ftpc;
+ struct http_conn httpc;
+ struct ssh_conn sshc;
+ struct tftp_state_data *tftpc;
+ struct imap_conn imapc;
+ struct pop3_conn pop3c;
+ struct smtp_conn smtpc;
+ struct rtsp_conn rtspc;
struct smb_conn smbc;
void *rtmp;
struct ldapconninfo *ldapc;
struct mqtt_conn mqtt;
- } proto;
-
- int cselect_bits; /* bitmask of socket events */
- int waitfor; /* current READ/WRITE bits to wait for */
-
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
- int socks5_gssapi_enctype;
-#endif
-
- /* When this connection is created, store the conditions for the local end
- bind. This is stored before the actual bind and before any connection is
- made and will serve the purpose of being used for comparison reasons so
- that subsequent bound-requested connections aren't accidentally re-using
- wrong connections. */
- char *localdev;
- unsigned short localport;
- int localportrange;
+ } proto;
+
+ int cselect_bits; /* bitmask of socket events */
+ int waitfor; /* current READ/WRITE bits to wait for */
+
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+ int socks5_gssapi_enctype;
+#endif
+
+ /* When this connection is created, store the conditions for the local end
+ bind. This is stored before the actual bind and before any connection is
+ made and will serve the purpose of being used for comparison reasons so
+ that subsequent bound-requested connections aren't accidentally re-using
+ wrong connections. */
+ char *localdev;
+ unsigned short localport;
+ int localportrange;
struct http_connect_state *connect_state; /* for HTTP CONNECT */
struct connectbundle *bundle; /* The bundle we are member of */
int negnpn; /* APLN or NPN TLS negotiated protocol, CURL_HTTP_VERSION* */
#ifdef USE_UNIX_SOCKETS
char *unix_domain_socket;
#endif
-};
-
-/* The end of connectdata. */
-
-/*
- * Struct to keep statistical and informational data.
+};
+
+/* The end of connectdata. */
+
+/*
+ * Struct to keep statistical and informational data.
* All variables in this struct must be initialized/reset in Curl_initinfo().
- */
-struct PureInfo {
+ */
+struct PureInfo {
int httpcode; /* Recent HTTP, FTP, RTSP or SMTP response code */
- int httpproxycode; /* response code from proxy when received separate */
- int httpversion; /* the http version number X.Y = X*10+Y */
+ int httpproxycode; /* response code from proxy when received separate */
+ int httpversion; /* the http version number X.Y = X*10+Y */
time_t filetime; /* If requested, this is might get set. Set to -1 if the
time was unretrievable. */
curl_off_t header_size; /* size of read header(s) in bytes */
curl_off_t request_size; /* the amount of bytes sent in the request(s) */
- unsigned long proxyauthavail; /* what proxy auth types were announced */
- unsigned long httpauthavail; /* what host auth types were announced */
- long numconnects; /* how many new connection did libcurl created */
- char *contenttype; /* the content type of the object */
- char *wouldredirect; /* URL this would've been redirected to if asked to */
+ unsigned long proxyauthavail; /* what proxy auth types were announced */
+ unsigned long httpauthavail; /* what host auth types were announced */
+ long numconnects; /* how many new connection did libcurl created */
+ char *contenttype; /* the content type of the object */
+ char *wouldredirect; /* URL this would've been redirected to if asked to */
curl_off_t retry_after; /* info from Retry-After: header */
-
- /* PureInfo members 'conn_primary_ip', 'conn_primary_port', 'conn_local_ip'
- and, 'conn_local_port' are copied over from the connectdata struct in
- order to allow curl_easy_getinfo() to return this information even when
- the session handle is no longer associated with a connection, and also
- allow curl_easy_reset() to clear this information from the session handle
- without disturbing information which is still alive, and that might be
- reused, in the connection cache. */
-
- char conn_primary_ip[MAX_IPADR_LEN];
- long conn_primary_port;
- char conn_local_ip[MAX_IPADR_LEN];
- long conn_local_port;
+
+ /* PureInfo members 'conn_primary_ip', 'conn_primary_port', 'conn_local_ip'
+ and, 'conn_local_port' are copied over from the connectdata struct in
+ order to allow curl_easy_getinfo() to return this information even when
+ the session handle is no longer associated with a connection, and also
+ allow curl_easy_reset() to clear this information from the session handle
+ without disturbing information which is still alive, and that might be
+ reused, in the connection cache. */
+
+ char conn_primary_ip[MAX_IPADR_LEN];
+ long conn_primary_port;
+ char conn_local_ip[MAX_IPADR_LEN];
+ long conn_local_port;
const char *conn_scheme;
unsigned int conn_protocol;
- struct curl_certinfo certs; /* info about the certs, only populated in
+ struct curl_certinfo certs; /* info about the certs, only populated in
OpenSSL, GnuTLS, Schannel, NSS and GSKit
builds. Asked for with CURLOPT_CERTINFO
/ CURLINFO_CERTINFO */
CURLproxycode pxcode;
BIT(timecond); /* set to TRUE if the time condition didn't match, which
thus made the document NOT get fetched */
-};
-
-
-struct Progress {
+};
+
+
+struct Progress {
time_t lastshow; /* time() of the last displayed progress meter or NULL to
force redraw at next call */
- curl_off_t size_dl; /* total expected size */
- curl_off_t size_ul; /* total expected size */
- curl_off_t downloaded; /* transferred so far */
- curl_off_t uploaded; /* transferred so far */
-
- curl_off_t current_speed; /* uses the currently fastest transfer */
-
- int width; /* screen width at download start */
- int flags; /* see progress.h */
-
+ curl_off_t size_dl; /* total expected size */
+ curl_off_t size_ul; /* total expected size */
+ curl_off_t downloaded; /* transferred so far */
+ curl_off_t uploaded; /* transferred so far */
+
+ curl_off_t current_speed; /* uses the currently fastest transfer */
+
+ int width; /* screen width at download start */
+ int flags; /* see progress.h */
+
timediff_t timespent;
-
- curl_off_t dlspeed;
- curl_off_t ulspeed;
-
+
+ curl_off_t dlspeed;
+ curl_off_t ulspeed;
+
timediff_t t_nslookup;
timediff_t t_connect;
timediff_t t_appconnect;
timediff_t t_pretransfer;
timediff_t t_starttransfer;
timediff_t t_redirect;
-
+
struct curltime start;
struct curltime t_startsingle;
struct curltime t_startop;
struct curltime t_acceptdata;
-
+
/* upload speed limit */
struct curltime ul_limit_start;
@@ -1199,54 +1199,54 @@ struct Progress {
#define CURR_TIME (5 + 1) /* 6 entries for 5 seconds */
- curl_off_t speeder[ CURR_TIME ];
+ curl_off_t speeder[ CURR_TIME ];
struct curltime speeder_time[ CURR_TIME ];
- int speeder_c;
+ int speeder_c;
BIT(callback); /* set when progress callback is used */
BIT(is_t_startransfer_set);
-};
-
-typedef enum {
- HTTPREQ_NONE, /* first in list */
- HTTPREQ_GET,
- HTTPREQ_POST,
- HTTPREQ_POST_FORM, /* we make a difference internally */
+};
+
+typedef enum {
+ HTTPREQ_NONE, /* first in list */
+ HTTPREQ_GET,
+ HTTPREQ_POST,
+ HTTPREQ_POST_FORM, /* we make a difference internally */
HTTPREQ_POST_MIME, /* we make a difference internally */
- HTTPREQ_PUT,
- HTTPREQ_HEAD,
- HTTPREQ_LAST /* last in list */
-} Curl_HttpReq;
-
-typedef enum {
- RTSPREQ_NONE, /* first in list */
- RTSPREQ_OPTIONS,
- RTSPREQ_DESCRIBE,
- RTSPREQ_ANNOUNCE,
- RTSPREQ_SETUP,
- RTSPREQ_PLAY,
- RTSPREQ_PAUSE,
- RTSPREQ_TEARDOWN,
- RTSPREQ_GET_PARAMETER,
- RTSPREQ_SET_PARAMETER,
- RTSPREQ_RECORD,
- RTSPREQ_RECEIVE,
- RTSPREQ_LAST /* last in list */
-} Curl_RtspReq;
-
-struct auth {
- unsigned long want; /* Bitmask set to the authentication methods wanted by
- app (with CURLOPT_HTTPAUTH or CURLOPT_PROXYAUTH). */
- unsigned long picked;
- unsigned long avail; /* Bitmask for what the server reports to support for
- this resource */
+ HTTPREQ_PUT,
+ HTTPREQ_HEAD,
+ HTTPREQ_LAST /* last in list */
+} Curl_HttpReq;
+
+typedef enum {
+ RTSPREQ_NONE, /* first in list */
+ RTSPREQ_OPTIONS,
+ RTSPREQ_DESCRIBE,
+ RTSPREQ_ANNOUNCE,
+ RTSPREQ_SETUP,
+ RTSPREQ_PLAY,
+ RTSPREQ_PAUSE,
+ RTSPREQ_TEARDOWN,
+ RTSPREQ_GET_PARAMETER,
+ RTSPREQ_SET_PARAMETER,
+ RTSPREQ_RECORD,
+ RTSPREQ_RECEIVE,
+ RTSPREQ_LAST /* last in list */
+} Curl_RtspReq;
+
+struct auth {
+ unsigned long want; /* Bitmask set to the authentication methods wanted by
+ app (with CURLOPT_HTTPAUTH or CURLOPT_PROXYAUTH). */
+ unsigned long picked;
+ unsigned long avail; /* Bitmask for what the server reports to support for
+ this resource */
BIT(done); /* TRUE when the auth phase is done and ready to do the
actual request */
BIT(multipass); /* TRUE if this is not yet authenticated but within the
auth multipass negotiation */
BIT(iestyle); /* TRUE if digest should be done IE-style or FALSE if it
should be RFC compliant */
-};
-
+};
+
struct Curl_http2_dep {
struct Curl_http2_dep *next;
struct Curl_easy *data;
@@ -1311,79 +1311,79 @@ struct urlpieces {
char *query;
};
-struct UrlState {
- /* Points to the connection cache */
- struct conncache *conn_cache;
-
+struct UrlState {
+ /* Points to the connection cache */
+ struct conncache *conn_cache;
+
int retrycount; /* number of retries on a new connection */
- /* buffers to store authentication data in, as parsed from input options */
+ /* buffers to store authentication data in, as parsed from input options */
struct curltime keeps_speed; /* for the progress meter really */
-
+
long lastconnect_id; /* The last connection, -1 if undefined */
struct dynbuf headerb; /* buffer to store headers in */
-
+
char *buffer; /* download buffer */
char *ulbuf; /* allocated upload buffer or NULL */
curl_off_t current_speed; /* the ProgressShow() function sets this,
- bytes / second */
+ bytes / second */
char *first_host; /* host name of the first (not followed) request.
if set, this should be the host name that we will
- sent authorization to, no else. Used to make Location:
- following not keep sending user+password... This is
- strdup() data.
- */
+ sent authorization to, no else. Used to make Location:
+ following not keep sending user+password... This is
+ strdup() data.
+ */
int first_remote_port; /* remote port of the first (not followed) request */
struct Curl_ssl_session *session; /* array of 'max_ssl_sessions' size */
- long sessionage; /* number of the most recent session */
+ long sessionage; /* number of the most recent session */
unsigned int tempcount; /* number of entries in use in tempwrite, 0 - 3 */
struct tempbuf tempwrite[3]; /* BOTH, HEADER, BODY */
char *scratch; /* huge buffer[set.buffer_size*2] for upload CRLF replacing */
- int os_errno; /* filled in with errno whenever an error occurs */
-#ifdef HAVE_SIGNAL
- /* storage for the previous bag^H^H^HSIGPIPE signal handler :-) */
- void (*prev_signal)(int sig);
-#endif
- struct digestdata digest; /* state data for host Digest auth */
- struct digestdata proxydigest; /* state data for proxy Digest auth */
-
- struct auth authhost; /* auth details for host */
- struct auth authproxy; /* auth details for proxy */
- void *resolver; /* resolver state, if it is used in the URL state -
- ares_channel f.e. */
-
+ int os_errno; /* filled in with errno whenever an error occurs */
+#ifdef HAVE_SIGNAL
+ /* storage for the previous bag^H^H^HSIGPIPE signal handler :-) */
+ void (*prev_signal)(int sig);
+#endif
+ struct digestdata digest; /* state data for host Digest auth */
+ struct digestdata proxydigest; /* state data for proxy Digest auth */
+
+ struct auth authhost; /* auth details for host */
+ struct auth authproxy; /* auth details for proxy */
+ void *resolver; /* resolver state, if it is used in the URL state -
+ ares_channel f.e. */
+
#if defined(USE_OPENSSL)
/* void instead of ENGINE to avoid bleeding OpenSSL into this header */
void *engine;
#endif /* USE_OPENSSL */
struct curltime expiretime; /* set this with Curl_expire() only */
- struct Curl_tree timenode; /* for the splay stuff */
+ struct Curl_tree timenode; /* for the splay stuff */
struct Curl_llist timeoutlist; /* list of pending timeouts */
struct time_node expires[EXPIRE_LAST]; /* nodes for each expire type */
-
- /* a place to store the most recently set FTP entrypath */
- char *most_recent_ftp_entrypath;
-
- int httpversion; /* the lowest HTTP version*10 reported by any server
- involved in this request */
-
+
+ /* a place to store the most recently set FTP entrypath */
+ char *most_recent_ftp_entrypath;
+
+ int httpversion; /* the lowest HTTP version*10 reported by any server
+ involved in this request */
+
#if !defined(WIN32) && !defined(MSDOS) && !defined(__EMX__)
-/* do FTP line-end conversions on most platforms */
-#define CURL_DO_LINEEND_CONV
- /* for FTP downloads: track CRLF sequences that span blocks */
+/* do FTP line-end conversions on most platforms */
+#define CURL_DO_LINEEND_CONV
+ /* for FTP downloads: track CRLF sequences that span blocks */
BIT(prev_block_had_trailing_cr);
- /* for FTP downloads: how many CRLFs did we converted to LFs? */
- curl_off_t crlf_conversions;
-#endif
- char *range; /* range, if used. See README for detailed specification on
- this syntax. */
- curl_off_t resume_from; /* continue [ftp] transfer from here */
-
- /* This RTSP state information survives requests and connections */
- long rtsp_next_client_CSeq; /* the session's next client CSeq */
- long rtsp_next_server_CSeq; /* the session's next server CSeq */
- long rtsp_CSeq_recv; /* most recent CSeq received */
-
+ /* for FTP downloads: how many CRLFs did we converted to LFs? */
+ curl_off_t crlf_conversions;
+#endif
+ char *range; /* range, if used. See README for detailed specification on
+ this syntax. */
+ curl_off_t resume_from; /* continue [ftp] transfer from here */
+
+ /* This RTSP state information survives requests and connections */
+ long rtsp_next_client_CSeq; /* the session's next client CSeq */
+ long rtsp_next_server_CSeq; /* the session's next server CSeq */
+ long rtsp_CSeq_recv; /* most recent CSeq received */
+
curl_off_t infilesize; /* size of file to upload, -1 means unknown.
Copied from set.filesize at start of operation */
@@ -1452,40 +1452,40 @@ struct UrlState {
BIT(stream_depends_e); /* set or don't set the Exclusive bit */
BIT(previouslypending); /* this transfer WAS in the multi->pending queue */
BIT(cookie_engine);
-};
-
-
-/*
- * This 'DynamicStatic' struct defines dynamic states that actually change
- * values in the 'UserDefined' area, which MUST be taken into consideration
- * if the UserDefined struct is cloned or similar. You can probably just
- * copy these, but each one indicate a special action on other data.
- */
-
-struct DynamicStatic {
- char *url; /* work URL, copied from UserDefined */
- char *referer; /* referer string */
- struct curl_slist *cookielist; /* list of cookie files set by
- curl_easy_setopt(COOKIEFILE) calls */
- struct curl_slist *resolve; /* set to point to the set.resolve list when
- this should be dealt with in pretransfer */
+};
+
+
+/*
+ * This 'DynamicStatic' struct defines dynamic states that actually change
+ * values in the 'UserDefined' area, which MUST be taken into consideration
+ * if the UserDefined struct is cloned or similar. You can probably just
+ * copy these, but each one indicate a special action on other data.
+ */
+
+struct DynamicStatic {
+ char *url; /* work URL, copied from UserDefined */
+ char *referer; /* referer string */
+ struct curl_slist *cookielist; /* list of cookie files set by
+ curl_easy_setopt(COOKIEFILE) calls */
+ struct curl_slist *resolve; /* set to point to the set.resolve list when
+ this should be dealt with in pretransfer */
BIT(url_alloc); /* URL string is malloc()'ed */
BIT(referer_alloc); /* referer string is malloc()ed */
BIT(wildcard_resolve); /* Set to true if any resolve change is a
wildcard */
-};
-
-/*
- * This 'UserDefined' struct must only contain data that is set once to go
- * for many (perhaps) independent connections. Values that are generated or
- * calculated internally for the "session handle" MUST be defined within the
- * 'struct UrlState' instead. The only exceptions MUST note the changes in
- * the 'DynamicStatic' struct.
- * Character pointer fields point to dynamic storage, unless otherwise stated.
- */
-
-struct Curl_multi; /* declared and used only in multi.c */
-
+};
+
+/*
+ * This 'UserDefined' struct must only contain data that is set once to go
+ * for many (perhaps) independent connections. Values that are generated or
+ * calculated internally for the "session handle" MUST be defined within the
+ * 'struct UrlState' instead. The only exceptions MUST note the changes in
+ * the 'DynamicStatic' struct.
+ * Character pointer fields point to dynamic storage, unless otherwise stated.
+ */
+
+struct Curl_multi; /* declared and used only in multi.c */
+
/*
* This enumeration MUST not use conditional directives (#ifdefs), new
* null terminated strings MUST be added to the enumeration immediately
@@ -1494,34 +1494,34 @@ struct Curl_multi; /* declared and used only in multi.c */
* test is updated and applicable changes for EBCDIC to ASCII conversion
* are catered for in curl_easy_setopt_ccsid()
*/
-enum dupstring {
+enum dupstring {
STRING_CERT_ORIG, /* client certificate file name */
STRING_CERT_PROXY, /* client certificate file name */
STRING_CERT_TYPE_ORIG, /* format for certificate (default: PEM)*/
STRING_CERT_TYPE_PROXY, /* format for certificate (default: PEM)*/
- STRING_COOKIE, /* HTTP cookie string to send */
- STRING_COOKIEJAR, /* dump all cookies to this file */
- STRING_CUSTOMREQUEST, /* HTTP/FTP/RTSP request/method to use */
+ STRING_COOKIE, /* HTTP cookie string to send */
+ STRING_COOKIEJAR, /* dump all cookies to this file */
+ STRING_CUSTOMREQUEST, /* HTTP/FTP/RTSP request/method to use */
STRING_DEFAULT_PROTOCOL, /* Protocol to use when the URL doesn't specify */
- STRING_DEVICE, /* local network interface/address to use */
- STRING_ENCODING, /* Accept-Encoding string */
- STRING_FTP_ACCOUNT, /* ftp account data */
- STRING_FTP_ALTERNATIVE_TO_USER, /* command to send if USER/PASS fails */
- STRING_FTPPORT, /* port to send with the FTP PORT command */
+ STRING_DEVICE, /* local network interface/address to use */
+ STRING_ENCODING, /* Accept-Encoding string */
+ STRING_FTP_ACCOUNT, /* ftp account data */
+ STRING_FTP_ALTERNATIVE_TO_USER, /* command to send if USER/PASS fails */
+ STRING_FTPPORT, /* port to send with the FTP PORT command */
STRING_KEY_ORIG, /* private key file name */
STRING_KEY_PROXY, /* private key file name */
STRING_KEY_PASSWD_ORIG, /* plain text private key password */
STRING_KEY_PASSWD_PROXY, /* plain text private key password */
STRING_KEY_TYPE_ORIG, /* format for private key (default: PEM) */
STRING_KEY_TYPE_PROXY, /* format for private key (default: PEM) */
- STRING_KRB_LEVEL, /* krb security level */
- STRING_NETRC_FILE, /* if not NULL, use this instead of trying to find
- $HOME/.netrc */
- STRING_PROXY, /* proxy to use */
+ STRING_KRB_LEVEL, /* krb security level */
+ STRING_NETRC_FILE, /* if not NULL, use this instead of trying to find
+ $HOME/.netrc */
+ STRING_PROXY, /* proxy to use */
STRING_PRE_PROXY, /* pre socks proxy to use */
- STRING_SET_RANGE, /* range, if used */
- STRING_SET_REFERER, /* custom string for the HTTP referer field */
- STRING_SET_URL, /* what original URL to work on */
+ STRING_SET_RANGE, /* range, if used */
+ STRING_SET_REFERER, /* custom string for the HTTP referer field */
+ STRING_SET_URL, /* what original URL to work on */
STRING_SSL_CAPATH_ORIG, /* CA directory name (doesn't work on windows) */
STRING_SSL_CAPATH_PROXY, /* CA directory name (doesn't work on windows) */
STRING_SSL_CAFILE_ORIG, /* certificate file to verify peer against */
@@ -1532,32 +1532,32 @@ enum dupstring {
STRING_SSL_CIPHER_LIST_PROXY, /* list of ciphers to use */
STRING_SSL_CIPHER13_LIST_ORIG, /* list of TLS 1.3 ciphers to use */
STRING_SSL_CIPHER13_LIST_PROXY, /* list of TLS 1.3 ciphers to use */
- STRING_SSL_EGDSOCKET, /* path to file containing the EGD daemon socket */
- STRING_SSL_RANDOM_FILE, /* path to file containing "random" data */
- STRING_USERAGENT, /* User-Agent string */
+ STRING_SSL_EGDSOCKET, /* path to file containing the EGD daemon socket */
+ STRING_SSL_RANDOM_FILE, /* path to file containing "random" data */
+ STRING_USERAGENT, /* User-Agent string */
STRING_SSL_CRLFILE_ORIG, /* crl file to check certificate */
STRING_SSL_CRLFILE_PROXY, /* crl file to check certificate */
STRING_SSL_ISSUERCERT_ORIG, /* issuer cert file to check certificate */
STRING_SSL_ISSUERCERT_PROXY, /* issuer cert file to check certificate */
STRING_SSL_ENGINE, /* name of ssl engine */
- STRING_USERNAME, /* <username>, if used */
- STRING_PASSWORD, /* <password>, if used */
- STRING_OPTIONS, /* <options>, if used */
- STRING_PROXYUSERNAME, /* Proxy <username>, if used */
- STRING_PROXYPASSWORD, /* Proxy <password>, if used */
- STRING_NOPROXY, /* List of hosts which should not use the proxy, if
- used */
- STRING_RTSP_SESSION_ID, /* Session ID to use */
- STRING_RTSP_STREAM_URI, /* Stream URI for this request */
- STRING_RTSP_TRANSPORT, /* Transport for this session */
- STRING_SSH_PRIVATE_KEY, /* path to the private key file for auth */
- STRING_SSH_PUBLIC_KEY, /* path to the public key file for auth */
- STRING_SSH_HOST_PUBLIC_KEY_MD5, /* md5 of host public key in ascii hex */
- STRING_SSH_KNOWNHOSTS, /* file name of knownhosts file */
+ STRING_USERNAME, /* <username>, if used */
+ STRING_PASSWORD, /* <password>, if used */
+ STRING_OPTIONS, /* <options>, if used */
+ STRING_PROXYUSERNAME, /* Proxy <username>, if used */
+ STRING_PROXYPASSWORD, /* Proxy <password>, if used */
+ STRING_NOPROXY, /* List of hosts which should not use the proxy, if
+ used */
+ STRING_RTSP_SESSION_ID, /* Session ID to use */
+ STRING_RTSP_STREAM_URI, /* Stream URI for this request */
+ STRING_RTSP_TRANSPORT, /* Transport for this session */
+ STRING_SSH_PRIVATE_KEY, /* path to the private key file for auth */
+ STRING_SSH_PUBLIC_KEY, /* path to the public key file for auth */
+ STRING_SSH_HOST_PUBLIC_KEY_MD5, /* md5 of host public key in ascii hex */
+ STRING_SSH_KNOWNHOSTS, /* file name of knownhosts file */
STRING_PROXY_SERVICE_NAME, /* Proxy service name */
STRING_SERVICE_NAME, /* Service name */
- STRING_MAIL_FROM,
- STRING_MAIL_AUTH,
+ STRING_MAIL_FROM,
+ STRING_MAIL_AUTH,
STRING_TLSAUTH_USERNAME_ORIG, /* TLS auth <username> */
STRING_TLSAUTH_USERNAME_PROXY, /* TLS auth <username> */
STRING_TLSAUTH_PASSWORD_ORIG, /* TLS auth <password> */
@@ -1575,19 +1575,19 @@ enum dupstring {
STRING_DNS_LOCAL_IP4,
STRING_DNS_LOCAL_IP6,
STRING_SSL_EC_CURVES,
-
+
/* -- end of null-terminated strings -- */
STRING_LASTZEROTERMINATED,
-
+
/* -- below this are pointers to binary data that cannot be strdup'ed. --- */
STRING_COPYPOSTFIELDS, /* if POST, set the fields' values here */
- STRING_LAST /* not used, just an end-of-list marker */
-};
-
+ STRING_LAST /* not used, just an end-of-list marker */
+};
+
enum dupblob {
BLOB_CERT_ORIG,
BLOB_CERT_PROXY,
@@ -1603,161 +1603,161 @@ enum dupblob {
DoH. */
typedef int (*multidone_func)(struct Curl_easy *easy, CURLcode result);
-struct UserDefined {
- FILE *err; /* the stderr user data goes here */
- void *debugdata; /* the data that will be passed to fdebug */
- char *errorbuffer; /* (Static) store failure messages in here */
- long proxyport; /* If non-zero, use this port number by default. If the
- proxy string features a ":[port]" that one will override
- this. */
+struct UserDefined {
+ FILE *err; /* the stderr user data goes here */
+ void *debugdata; /* the data that will be passed to fdebug */
+ char *errorbuffer; /* (Static) store failure messages in here */
+ long proxyport; /* If non-zero, use this port number by default. If the
+ proxy string features a ":[port]" that one will override
+ this. */
void *out; /* CURLOPT_WRITEDATA */
void *in_set; /* CURLOPT_READDATA */
- void *writeheader; /* write the header to this if non-NULL */
- void *rtp_out; /* write RTP to this if non-NULL */
- long use_port; /* which port to use (when not using default) */
- unsigned long httpauth; /* kind of HTTP authentication to use (bitmask) */
- unsigned long proxyauth; /* kind of proxy authentication to use (bitmask) */
+ void *writeheader; /* write the header to this if non-NULL */
+ void *rtp_out; /* write RTP to this if non-NULL */
+ long use_port; /* which port to use (when not using default) */
+ unsigned long httpauth; /* kind of HTTP authentication to use (bitmask) */
+ unsigned long proxyauth; /* kind of proxy authentication to use (bitmask) */
unsigned long socks5auth;/* kind of SOCKS5 authentication to use (bitmask) */
- long followlocation; /* as in HTTP Location: */
- long maxredirs; /* maximum no. of http(s) redirects to follow, set to -1
- for infinity */
-
- int keep_post; /* keep POSTs as POSTs after a 30x request; each
- bit represents a request, from 301 to 303 */
- void *postfields; /* if POST, set the fields' values here */
- curl_seek_callback seek_func; /* function that seeks the input */
- curl_off_t postfieldsize; /* if POST, this might have a size to use instead
- of strlen(), and then the data *may* be binary
- (contain zero bytes) */
- unsigned short localport; /* local port number to bind to */
- int localportrange; /* number of additional port numbers to test in case the
- 'localport' one can't be bind()ed */
- curl_write_callback fwrite_func; /* function that stores the output */
- curl_write_callback fwrite_header; /* function that stores headers */
- curl_write_callback fwrite_rtp; /* function that stores interleaved RTP */
+ long followlocation; /* as in HTTP Location: */
+ long maxredirs; /* maximum no. of http(s) redirects to follow, set to -1
+ for infinity */
+
+ int keep_post; /* keep POSTs as POSTs after a 30x request; each
+ bit represents a request, from 301 to 303 */
+ void *postfields; /* if POST, set the fields' values here */
+ curl_seek_callback seek_func; /* function that seeks the input */
+ curl_off_t postfieldsize; /* if POST, this might have a size to use instead
+ of strlen(), and then the data *may* be binary
+ (contain zero bytes) */
+ unsigned short localport; /* local port number to bind to */
+ int localportrange; /* number of additional port numbers to test in case the
+ 'localport' one can't be bind()ed */
+ curl_write_callback fwrite_func; /* function that stores the output */
+ curl_write_callback fwrite_header; /* function that stores headers */
+ curl_write_callback fwrite_rtp; /* function that stores interleaved RTP */
curl_read_callback fread_func_set; /* function that reads the input */
- curl_progress_callback fprogress; /* OLD and deprecated progress callback */
- curl_xferinfo_callback fxferinfo; /* progress callback */
- curl_debug_callback fdebug; /* function that write informational data */
- curl_ioctl_callback ioctl_func; /* function for I/O control */
- curl_sockopt_callback fsockopt; /* function for setting socket options */
- void *sockopt_client; /* pointer to pass to the socket options callback */
- curl_opensocket_callback fopensocket; /* function for checking/translating
- the address and opening the
- socket */
+ curl_progress_callback fprogress; /* OLD and deprecated progress callback */
+ curl_xferinfo_callback fxferinfo; /* progress callback */
+ curl_debug_callback fdebug; /* function that write informational data */
+ curl_ioctl_callback ioctl_func; /* function for I/O control */
+ curl_sockopt_callback fsockopt; /* function for setting socket options */
+ void *sockopt_client; /* pointer to pass to the socket options callback */
+ curl_opensocket_callback fopensocket; /* function for checking/translating
+ the address and opening the
+ socket */
void *opensocket_client;
- curl_closesocket_callback fclosesocket; /* function for closing the
- socket */
+ curl_closesocket_callback fclosesocket; /* function for closing the
+ socket */
void *closesocket_client;
-
- void *seek_client; /* pointer to pass to the seek callback */
- /* the 3 curl_conv_callback functions below are used on non-ASCII hosts */
- /* function to convert from the network encoding: */
- curl_conv_callback convfromnetwork;
- /* function to convert to the network encoding: */
- curl_conv_callback convtonetwork;
- /* function to convert from UTF-8 encoding: */
- curl_conv_callback convfromutf8;
+
+ void *seek_client; /* pointer to pass to the seek callback */
+ /* the 3 curl_conv_callback functions below are used on non-ASCII hosts */
+ /* function to convert from the network encoding: */
+ curl_conv_callback convfromnetwork;
+ /* function to convert to the network encoding: */
+ curl_conv_callback convtonetwork;
+ /* function to convert from UTF-8 encoding: */
+ curl_conv_callback convfromutf8;
#ifdef USE_HSTS
curl_hstsread_callback hsts_read;
void *hsts_read_userp;
curl_hstswrite_callback hsts_write;
void *hsts_write_userp;
#endif
- void *progress_client; /* pointer to pass to the progress callback */
- void *ioctl_client; /* pointer to pass to the ioctl callback */
- long timeout; /* in milliseconds, 0 means no timeout */
- long connecttimeout; /* in milliseconds, 0 means no timeout */
- long accepttimeout; /* in milliseconds, 0 means no timeout */
+ void *progress_client; /* pointer to pass to the progress callback */
+ void *ioctl_client; /* pointer to pass to the ioctl callback */
+ long timeout; /* in milliseconds, 0 means no timeout */
+ long connecttimeout; /* in milliseconds, 0 means no timeout */
+ long accepttimeout; /* in milliseconds, 0 means no timeout */
long happy_eyeballs_timeout; /* in milliseconds, 0 is a valid value */
- long server_response_timeout; /* in milliseconds, 0 means no timeout */
+ long server_response_timeout; /* in milliseconds, 0 means no timeout */
long maxage_conn; /* in seconds, max idle time to allow a connection that
is to be reused */
long tftp_blksize; /* in bytes, 0 means use default */
curl_off_t filesize; /* size of file to upload, -1 means unknown */
- long low_speed_limit; /* bytes/second */
- long low_speed_time; /* number of seconds */
- curl_off_t max_send_speed; /* high speed limit in bytes/second for upload */
- curl_off_t max_recv_speed; /* high speed limit in bytes/second for
- download */
- curl_off_t set_resume_from; /* continue [ftp] transfer from here */
- struct curl_slist *headers; /* linked list of extra headers */
+ long low_speed_limit; /* bytes/second */
+ long low_speed_time; /* number of seconds */
+ curl_off_t max_send_speed; /* high speed limit in bytes/second for upload */
+ curl_off_t max_recv_speed; /* high speed limit in bytes/second for
+ download */
+ curl_off_t set_resume_from; /* continue [ftp] transfer from here */
+ struct curl_slist *headers; /* linked list of extra headers */
struct curl_slist *proxyheaders; /* linked list of extra CONNECT headers */
struct curl_httppost *httppost; /* linked list of old POST data */
curl_mimepart mimepost; /* MIME/POST data. */
- struct curl_slist *quote; /* after connection is established */
- struct curl_slist *postquote; /* after the transfer */
- struct curl_slist *prequote; /* before the transfer, after type */
- struct curl_slist *source_quote; /* 3rd party quote */
- struct curl_slist *source_prequote; /* in 3rd party transfer mode - before
- the transfer on source host */
- struct curl_slist *source_postquote; /* in 3rd party transfer mode - after
- the transfer on source host */
- struct curl_slist *telnet_options; /* linked list of telnet options */
- struct curl_slist *resolve; /* list of names to add/remove from
- DNS cache */
+ struct curl_slist *quote; /* after connection is established */
+ struct curl_slist *postquote; /* after the transfer */
+ struct curl_slist *prequote; /* before the transfer, after type */
+ struct curl_slist *source_quote; /* 3rd party quote */
+ struct curl_slist *source_prequote; /* in 3rd party transfer mode - before
+ the transfer on source host */
+ struct curl_slist *source_postquote; /* in 3rd party transfer mode - after
+ the transfer on source host */
+ struct curl_slist *telnet_options; /* linked list of telnet options */
+ struct curl_slist *resolve; /* list of names to add/remove from
+ DNS cache */
struct curl_slist *connect_to; /* list of host:port mappings to override
the hostname and port to connect to */
- curl_TimeCond timecondition; /* kind of time/date comparison */
- time_t timevalue; /* what time to compare with */
+ curl_TimeCond timecondition; /* kind of time/date comparison */
+ time_t timevalue; /* what time to compare with */
Curl_HttpReq method; /* what kind of HTTP request (if any) is this */
- long httpversion; /* when non-zero, a specific HTTP version requested to
- be used in the library's request(s) */
- struct ssl_config_data ssl; /* user defined SSL stuff */
+ long httpversion; /* when non-zero, a specific HTTP version requested to
+ be used in the library's request(s) */
+ struct ssl_config_data ssl; /* user defined SSL stuff */
#ifndef CURL_DISABLE_PROXY
struct ssl_config_data proxy_ssl; /* user defined SSL stuff for proxy */
#endif
struct ssl_general_config general_ssl; /* general user defined SSL stuff */
- curl_proxytype proxytype; /* what kind of proxy that is in use */
- long dns_cache_timeout; /* DNS cache timeout */
- long buffer_size; /* size of receive buffer to use */
+ curl_proxytype proxytype; /* what kind of proxy that is in use */
+ long dns_cache_timeout; /* DNS cache timeout */
+ long buffer_size; /* size of receive buffer to use */
size_t upload_buffer_size; /* size of upload buffer to use,
keep it >= CURL_MAX_WRITE_SIZE */
- void *private_data; /* application-private data */
- struct curl_slist *http200aliases; /* linked list of aliases for http200 */
- long ipver; /* the CURL_IPRESOLVE_* defines in the public header file
- 0 - whatever, 1 - v2, 2 - v6 */
- curl_off_t max_filesize; /* Maximum file size to download */
+ void *private_data; /* application-private data */
+ struct curl_slist *http200aliases; /* linked list of aliases for http200 */
+ long ipver; /* the CURL_IPRESOLVE_* defines in the public header file
+ 0 - whatever, 1 - v2, 2 - v6 */
+ curl_off_t max_filesize; /* Maximum file size to download */
#ifndef CURL_DISABLE_FTP
- curl_ftpfile ftp_filemethod; /* how to get to a file when FTP is used */
+ curl_ftpfile ftp_filemethod; /* how to get to a file when FTP is used */
curl_ftpauth ftpsslauth; /* what AUTH XXX to be attempted */
curl_ftpccc ftp_ccc; /* FTP CCC options */
#endif
- int ftp_create_missing_dirs; /* 1 - create directories that don't exist
- 2 - the same but also allow MKD to fail once
- */
- curl_sshkeycallback ssh_keyfunc; /* key matching callback */
- void *ssh_keyfunc_userp; /* custom pointer to callback */
- enum CURL_NETRC_OPTION
- use_netrc; /* defined in include/curl.h */
- curl_usessl use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or
- IMAP or POP3 or others! */
- long new_file_perms; /* Permissions to use when creating remote files */
- long new_directory_perms; /* Permissions to use when creating remote dirs */
+ int ftp_create_missing_dirs; /* 1 - create directories that don't exist
+ 2 - the same but also allow MKD to fail once
+ */
+ curl_sshkeycallback ssh_keyfunc; /* key matching callback */
+ void *ssh_keyfunc_userp; /* custom pointer to callback */
+ enum CURL_NETRC_OPTION
+ use_netrc; /* defined in include/curl.h */
+ curl_usessl use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or
+ IMAP or POP3 or others! */
+ long new_file_perms; /* Permissions to use when creating remote files */
+ long new_directory_perms; /* Permissions to use when creating remote dirs */
long ssh_auth_types; /* allowed SSH auth types */
- char *str[STRING_LAST]; /* array of strings, pointing to allocated memory */
+ char *str[STRING_LAST]; /* array of strings, pointing to allocated memory */
struct curl_blob *blobs[BLOB_LAST];
unsigned int scope_id; /* Scope id for IPv6 */
- long allowed_protocols;
- long redir_protocols;
- struct curl_slist *mail_rcpt; /* linked list of mail recipients */
- /* Common RTSP header options */
- Curl_RtspReq rtspreq; /* RTSP request type */
- long rtspversion; /* like httpversion, for RTSP */
- curl_chunk_bgn_callback chunk_bgn; /* called before part of transfer
- starts */
- curl_chunk_end_callback chunk_end; /* called after part transferring
- stopped */
- curl_fnmatch_callback fnmatch; /* callback to decide which file corresponds
- to pattern (e.g. if WILDCARDMATCH is on) */
- void *fnmatch_data;
-
+ long allowed_protocols;
+ long redir_protocols;
+ struct curl_slist *mail_rcpt; /* linked list of mail recipients */
+ /* Common RTSP header options */
+ Curl_RtspReq rtspreq; /* RTSP request type */
+ long rtspversion; /* like httpversion, for RTSP */
+ curl_chunk_bgn_callback chunk_bgn; /* called before part of transfer
+ starts */
+ curl_chunk_end_callback chunk_end; /* called after part transferring
+ stopped */
+ curl_fnmatch_callback fnmatch; /* callback to decide which file corresponds
+ to pattern (e.g. if WILDCARDMATCH is on) */
+ void *fnmatch_data;
+
long gssapi_delegation; /* GSS-API credential delegation, see the
- documentation of CURLOPT_GSSAPI_DELEGATION */
-
- long tcp_keepidle; /* seconds in idle before sending keepalive probe */
- long tcp_keepintvl; /* seconds between TCP keepalive probes */
-
+ documentation of CURLOPT_GSSAPI_DELEGATION */
+
+ long tcp_keepidle; /* seconds in idle before sending keepalive probe */
+ long tcp_keepintvl; /* seconds between TCP keepalive probes */
+
size_t maxconnects; /* Max idle connections in the connection cache */
long expect_100_timeout; /* in milliseconds */
@@ -1852,91 +1852,91 @@ struct UserDefined {
BIT(http09_allowed); /* allow HTTP/0.9 responses */
BIT(mail_rcpt_allowfails); /* allow RCPT TO command to fail for some
recipients */
-};
-
-struct Names {
+};
+
+struct Names {
struct Curl_hash *hostcache;
- enum {
- HCACHE_NONE, /* not pointing to anything */
- HCACHE_MULTI, /* points to a shared one in the multi handle */
- HCACHE_SHARED /* points to a shared one in a shared object */
- } hostcachetype;
-};
-
-/*
- * The 'connectdata' struct MUST have all the connection oriented stuff as we
- * may have several simultaneous connections and connection structs in memory.
- *
- * The 'struct UserDefined' must only contain data that is set once to go for
- * many (perhaps) independent connections. Values that are generated or
- * calculated internally for the "session handle" must be defined within the
- * 'struct UrlState' instead.
- */
-
+ enum {
+ HCACHE_NONE, /* not pointing to anything */
+ HCACHE_MULTI, /* points to a shared one in the multi handle */
+ HCACHE_SHARED /* points to a shared one in a shared object */
+ } hostcachetype;
+};
+
+/*
+ * The 'connectdata' struct MUST have all the connection oriented stuff as we
+ * may have several simultaneous connections and connection structs in memory.
+ *
+ * The 'struct UserDefined' must only contain data that is set once to go for
+ * many (perhaps) independent connections. Values that are generated or
+ * calculated internally for the "session handle" must be defined within the
+ * 'struct UrlState' instead.
+ */
+
struct Curl_easy {
- /* first, two fields for the linked list of these */
+ /* first, two fields for the linked list of these */
struct Curl_easy *next;
struct Curl_easy *prev;
-
+
struct connectdata *conn;
struct Curl_llist_element connect_queue;
struct Curl_llist_element conn_queue; /* list per connectdata */
-
- CURLMstate mstate; /* the handle's state */
- CURLcode result; /* previous result */
-
- struct Curl_message msg; /* A single posted message. */
-
- /* Array with the plain socket numbers this handle takes care of, in no
- particular order. Note that all sockets are added to the sockhash, where
- the state etc are also kept. This array is mostly used to detect when a
- socket is to be removed from the hash. See singlesocket(). */
- curl_socket_t sockets[MAX_SOCKSPEREASYHANDLE];
+
+ CURLMstate mstate; /* the handle's state */
+ CURLcode result; /* previous result */
+
+ struct Curl_message msg; /* A single posted message. */
+
+ /* Array with the plain socket numbers this handle takes care of, in no
+ particular order. Note that all sockets are added to the sockhash, where
+ the state etc are also kept. This array is mostly used to detect when a
+ socket is to be removed from the hash. See singlesocket(). */
+ curl_socket_t sockets[MAX_SOCKSPEREASYHANDLE];
int actions[MAX_SOCKSPEREASYHANDLE]; /* action for each socket in
sockets[] */
- int numsocks;
-
- struct Names dns;
- struct Curl_multi *multi; /* if non-NULL, points to the multi handle
- struct to which this "belongs" when used by
- the multi interface */
- struct Curl_multi *multi_easy; /* if non-NULL, points to the multi handle
- struct to which this "belongs" when used
- by the easy interface */
- struct Curl_share *share; /* Share, handles global variable mutexing */
+ int numsocks;
+
+ struct Names dns;
+ struct Curl_multi *multi; /* if non-NULL, points to the multi handle
+ struct to which this "belongs" when used by
+ the multi interface */
+ struct Curl_multi *multi_easy; /* if non-NULL, points to the multi handle
+ struct to which this "belongs" when used
+ by the easy interface */
+ struct Curl_share *share; /* Share, handles global variable mutexing */
#ifdef USE_LIBPSL
struct PslCache *psl; /* The associated PSL cache. */
#endif
- struct SingleRequest req; /* Request-specific data */
- struct UserDefined set; /* values set by the libcurl user */
- struct DynamicStatic change; /* possibly modified userdefined data */
- struct CookieInfo *cookies; /* the cookies, read from files and servers.
- NOTE that the 'cookie' field in the
- UserDefined struct defines if the "engine"
- is to be used or not. */
+ struct SingleRequest req; /* Request-specific data */
+ struct UserDefined set; /* values set by the libcurl user */
+ struct DynamicStatic change; /* possibly modified userdefined data */
+ struct CookieInfo *cookies; /* the cookies, read from files and servers.
+ NOTE that the 'cookie' field in the
+ UserDefined struct defines if the "engine"
+ is to be used or not. */
#ifdef USE_HSTS
struct hsts *hsts;
#endif
#ifndef CURL_DISABLE_ALTSVC
struct altsvcinfo *asi; /* the alt-svc cache */
#endif
- struct Progress progress; /* for all the progress meter data */
- struct UrlState state; /* struct for fields used for state info and
- other dynamic purposes */
+ struct Progress progress; /* for all the progress meter data */
+ struct UrlState state; /* struct for fields used for state info and
+ other dynamic purposes */
#ifndef CURL_DISABLE_FTP
- struct WildcardData wildcard; /* wildcard download state info */
+ struct WildcardData wildcard; /* wildcard download state info */
#endif
- struct PureInfo info; /* stats, reports and info data */
+ struct PureInfo info; /* stats, reports and info data */
struct curl_tlssessioninfo tsi; /* Information about the TLS session, only
valid after a client has asked for it */
-#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
- iconv_t outbound_cd; /* for translating to the network encoding */
- iconv_t inbound_cd; /* for translating from the network encoding */
- iconv_t utf8_cd; /* for translating to UTF8 */
-#endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
- unsigned int magic; /* set to a CURLEASY_MAGIC_NUMBER */
-};
-
-#define LIBCURL_NAME "libcurl"
-
-#endif /* HEADER_CURL_URLDATA_H */
+#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
+ iconv_t outbound_cd; /* for translating to the network encoding */
+ iconv_t inbound_cd; /* for translating from the network encoding */
+ iconv_t utf8_cd; /* for translating to UTF8 */
+#endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
+ unsigned int magic; /* set to a CURLEASY_MAGIC_NUMBER */
+};
+
+#define LIBCURL_NAME "libcurl"
+
+#endif /* HEADER_CURL_URLDATA_H */
diff --git a/contrib/libs/curl/lib/version.c b/contrib/libs/curl/lib/version.c
index d1f1e770ba..5e8512ef05 100644
--- a/contrib/libs/curl/lib/version.c
+++ b/contrib/libs/curl/lib/version.c
@@ -1,59 +1,59 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include <curl/curl.h>
-#include "urldata.h"
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+#include "urldata.h"
#include "vtls/vtls.h"
-#include "http2.h"
+#include "http2.h"
#include "vssh/ssh.h"
#include "quic.h"
#include "curl_printf.h"
-
-#ifdef USE_ARES
+
+#ifdef USE_ARES
# if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \
defined(WIN32)
-# define CARES_STATICLIB
-# endif
-# include <ares.h>
-#endif
-
+# define CARES_STATICLIB
+# endif
+# include <ares.h>
+#endif
+
#ifdef USE_LIBIDN2
#error #include <idn2.h>
-#endif
-
+#endif
+
#ifdef USE_LIBPSL
#error #include <libpsl.h>
#endif
-#if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS)
-#include <iconv.h>
-#endif
-
-#ifdef USE_LIBRTMP
-#include <librtmp/rtmp.h>
-#endif
-
+#if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS)
+#include <iconv.h>
+#endif
+
+#ifdef USE_LIBRTMP
+#include <librtmp/rtmp.h>
+#endif
+
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
@@ -80,14 +80,14 @@ static size_t brotli_version(char *buf, size_t bufsz)
#ifdef HAVE_ZSTD
static size_t zstd_version(char *buf, size_t bufsz)
-{
+{
unsigned long zstd_version = (unsigned long)ZSTD_versionNumber();
unsigned int major = (unsigned int)(zstd_version / (100 * 100));
unsigned int minor = (unsigned int)((zstd_version -
(major * 100 * 100)) / 100);
unsigned int patch = (unsigned int)(zstd_version -
(major * 100 * 100) - (minor * 100));
-
+
return msnprintf(buf, bufsz, "%u.%u.%u", major, minor, patch);
}
#endif
@@ -99,9 +99,9 @@ static size_t zstd_version(char *buf, size_t bufsz)
* generate the exact same string and never write any temporary data like
* zeros in the data.
*/
-
+
#define VERSION_PARTS 14 /* number of substrings we can concatenate */
-
+
char *curl_version(void)
{
static char out[300];
@@ -154,18 +154,18 @@ char *curl_version(void)
strncpy(out, debugversion, sizeof(out)-1);
out[sizeof(out)-1] = '\0';
return out;
- }
+ }
#endif
-
+
src[i++] = LIBCURL_NAME "/" LIBCURL_VERSION;
#ifdef USE_SSL
Curl_ssl_version(ssl_version, sizeof(ssl_version));
src[i++] = ssl_version;
#endif
-#ifdef HAVE_LIBZ
+#ifdef HAVE_LIBZ
msnprintf(z_version, sizeof(z_version), "zlib/%s", zlibVersion());
src[i++] = z_version;
-#endif
+#endif
#ifdef HAVE_BROTLI
brotli_version(&br_version[7], sizeof(br_version) - 7);
src[i++] = br_version;
@@ -174,36 +174,36 @@ char *curl_version(void)
zstd_version(&zst_version[5], sizeof(zst_version) - 5);
src[i++] = zst_version;
#endif
-#ifdef USE_ARES
+#ifdef USE_ARES
msnprintf(cares_version, sizeof(cares_version),
"c-ares/%s", ares_version(NULL));
src[i++] = cares_version;
-#endif
+#endif
#ifdef USE_LIBIDN2
msnprintf(idn_version, sizeof(idn_version),
"libidn2/%s", idn2_check_version(NULL));
src[i++] = idn_version;
#elif defined(USE_WIN32_IDN)
src[i++] = (char *)"WinIDN";
-#endif
+#endif
#ifdef USE_LIBPSL
msnprintf(psl_version, sizeof(psl_version), "libpsl/%s", psl_get_version());
src[i++] = psl_version;
#endif
-#if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS)
-#ifdef _LIBICONV_VERSION
+#if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS)
+#ifdef _LIBICONV_VERSION
msnprintf(iconv_version, sizeof(iconv_version), "iconv/%d.%d",
_LIBICONV_VERSION >> 8, _LIBICONV_VERSION & 255);
-#else
+#else
/* version unknown, let the default stand */
-#endif /* _LIBICONV_VERSION */
+#endif /* _LIBICONV_VERSION */
src[i++] = iconv_version;
-#endif
+#endif
#ifdef USE_SSH
Curl_ssh_version(ssh_version, sizeof(ssh_version));
src[i++] = ssh_version;
-#endif
+#endif
#ifdef USE_NGHTTP2
Curl_http2_ver(h2_version, sizeof(h2_version));
src[i++] = h2_version;
@@ -211,26 +211,26 @@ char *curl_version(void)
#ifdef ENABLE_QUIC
Curl_quic_ver(h3_version, sizeof(h3_version));
src[i++] = h3_version;
-#endif
-#ifdef USE_LIBRTMP
- {
- char suff[2];
- if(RTMP_LIB_VERSION & 0xff) {
- suff[0] = (RTMP_LIB_VERSION & 0xff) + 'a' - 1;
- suff[1] = '\0';
- }
- else
- suff[0] = '\0';
-
+#endif
+#ifdef USE_LIBRTMP
+ {
+ char suff[2];
+ if(RTMP_LIB_VERSION & 0xff) {
+ suff[0] = (RTMP_LIB_VERSION & 0xff) + 'a' - 1;
+ suff[1] = '\0';
+ }
+ else
+ suff[0] = '\0';
+
msnprintf(rtmp_version, sizeof(rtmp_version), "librtmp/%d.%d%s",
RTMP_LIB_VERSION >> 16, (RTMP_LIB_VERSION >> 8) & 0xff,
suff);
src[i++] = rtmp_version;
}
#endif
-
+
DEBUGASSERT(i <= VERSION_PARTS);
-
+
outp = &out[0];
outlen = sizeof(out);
for(j = 0; j < i; j++) {
@@ -246,75 +246,75 @@ char *curl_version(void)
memcpy(outp, src[j], n);
outp += n;
outlen -= n;
- }
+ }
*outp = 0;
-
+
return out;
-}
-
-/* data for curl_version_info
-
- Keep the list sorted alphabetically. It is also written so that each
- protocol line has its own #if line to make things easier on the eye.
- */
-
-static const char * const protocols[] = {
-#ifndef CURL_DISABLE_DICT
- "dict",
-#endif
-#ifndef CURL_DISABLE_FILE
- "file",
-#endif
-#ifndef CURL_DISABLE_FTP
- "ftp",
-#endif
-#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
- "ftps",
-#endif
-#ifndef CURL_DISABLE_GOPHER
- "gopher",
-#endif
-#ifndef CURL_DISABLE_HTTP
- "http",
-#endif
-#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
- "https",
-#endif
-#ifndef CURL_DISABLE_IMAP
- "imap",
-#endif
-#if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP)
- "imaps",
-#endif
-#ifndef CURL_DISABLE_LDAP
- "ldap",
-#if !defined(CURL_DISABLE_LDAPS) && \
- ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
- (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
- "ldaps",
-#endif
-#endif
+}
+
+/* data for curl_version_info
+
+ Keep the list sorted alphabetically. It is also written so that each
+ protocol line has its own #if line to make things easier on the eye.
+ */
+
+static const char * const protocols[] = {
+#ifndef CURL_DISABLE_DICT
+ "dict",
+#endif
+#ifndef CURL_DISABLE_FILE
+ "file",
+#endif
+#ifndef CURL_DISABLE_FTP
+ "ftp",
+#endif
+#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
+ "ftps",
+#endif
+#ifndef CURL_DISABLE_GOPHER
+ "gopher",
+#endif
+#ifndef CURL_DISABLE_HTTP
+ "http",
+#endif
+#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
+ "https",
+#endif
+#ifndef CURL_DISABLE_IMAP
+ "imap",
+#endif
+#if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP)
+ "imaps",
+#endif
+#ifndef CURL_DISABLE_LDAP
+ "ldap",
+#if !defined(CURL_DISABLE_LDAPS) && \
+ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
+ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
+ "ldaps",
+#endif
+#endif
#ifndef CURL_DISABLE_MQTT
"mqtt",
#endif
-#ifndef CURL_DISABLE_POP3
- "pop3",
-#endif
-#if defined(USE_SSL) && !defined(CURL_DISABLE_POP3)
- "pop3s",
-#endif
-#ifdef USE_LIBRTMP
- "rtmp",
-#endif
-#ifndef CURL_DISABLE_RTSP
- "rtsp",
-#endif
+#ifndef CURL_DISABLE_POP3
+ "pop3",
+#endif
+#if defined(USE_SSL) && !defined(CURL_DISABLE_POP3)
+ "pop3s",
+#endif
+#ifdef USE_LIBRTMP
+ "rtmp",
+#endif
+#ifndef CURL_DISABLE_RTSP
+ "rtsp",
+#endif
#if defined(USE_SSH) && !defined(USE_WOLFSSH)
- "scp",
+ "scp",
#endif
#ifdef USE_SSH
- "sftp",
-#endif
+ "sftp",
+#endif
#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \
(CURL_SIZEOF_CURL_OFF_T > 4)
"smb",
@@ -322,41 +322,41 @@ static const char * const protocols[] = {
"smbs",
# endif
#endif
-#ifndef CURL_DISABLE_SMTP
- "smtp",
-#endif
-#if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP)
- "smtps",
-#endif
-#ifndef CURL_DISABLE_TELNET
- "telnet",
-#endif
-#ifndef CURL_DISABLE_TFTP
- "tftp",
-#endif
-
- NULL
-};
-
-static curl_version_info_data version_info = {
- CURLVERSION_NOW,
- LIBCURL_VERSION,
- LIBCURL_VERSION_NUM,
- OS, /* as found by configure or set by hand at build-time */
- 0 /* features is 0 by default */
-#ifdef ENABLE_IPV6
- | CURL_VERSION_IPV6
-#endif
-#ifdef USE_SSL
- | CURL_VERSION_SSL
-#endif
-#ifdef USE_NTLM
- | CURL_VERSION_NTLM
-#endif
+#ifndef CURL_DISABLE_SMTP
+ "smtp",
+#endif
+#if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP)
+ "smtps",
+#endif
+#ifndef CURL_DISABLE_TELNET
+ "telnet",
+#endif
+#ifndef CURL_DISABLE_TFTP
+ "tftp",
+#endif
+
+ NULL
+};
+
+static curl_version_info_data version_info = {
+ CURLVERSION_NOW,
+ LIBCURL_VERSION,
+ LIBCURL_VERSION_NUM,
+ OS, /* as found by configure or set by hand at build-time */
+ 0 /* features is 0 by default */
+#ifdef ENABLE_IPV6
+ | CURL_VERSION_IPV6
+#endif
+#ifdef USE_SSL
+ | CURL_VERSION_SSL
+#endif
+#ifdef USE_NTLM
+ | CURL_VERSION_NTLM
+#endif
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
- | CURL_VERSION_NTLM_WB
-#endif
+ | CURL_VERSION_NTLM_WB
+#endif
#ifdef USE_SPNEGO
| CURL_VERSION_SPNEGO
#endif
@@ -366,37 +366,37 @@ static curl_version_info_data version_info = {
#ifdef HAVE_GSSAPI
| CURL_VERSION_GSSAPI
#endif
-#ifdef USE_WINDOWS_SSPI
- | CURL_VERSION_SSPI
-#endif
-#ifdef HAVE_LIBZ
- | CURL_VERSION_LIBZ
-#endif
-#ifdef DEBUGBUILD
- | CURL_VERSION_DEBUG
-#endif
-#ifdef CURLDEBUG
- | CURL_VERSION_CURLDEBUG
-#endif
-#ifdef CURLRES_ASYNCH
- | CURL_VERSION_ASYNCHDNS
-#endif
-#if (CURL_SIZEOF_CURL_OFF_T > 4) && \
- ( (SIZEOF_OFF_T > 4) || defined(USE_WIN32_LARGE_FILES) )
- | CURL_VERSION_LARGEFILE
-#endif
+#ifdef USE_WINDOWS_SSPI
+ | CURL_VERSION_SSPI
+#endif
+#ifdef HAVE_LIBZ
+ | CURL_VERSION_LIBZ
+#endif
+#ifdef DEBUGBUILD
+ | CURL_VERSION_DEBUG
+#endif
+#ifdef CURLDEBUG
+ | CURL_VERSION_CURLDEBUG
+#endif
+#ifdef CURLRES_ASYNCH
+ | CURL_VERSION_ASYNCHDNS
+#endif
+#if (CURL_SIZEOF_CURL_OFF_T > 4) && \
+ ( (SIZEOF_OFF_T > 4) || defined(USE_WIN32_LARGE_FILES) )
+ | CURL_VERSION_LARGEFILE
+#endif
#if defined(WIN32) && defined(UNICODE) && defined(_UNICODE)
| CURL_VERSION_UNICODE
#endif
-#if defined(CURL_DOES_CONVERSIONS)
- | CURL_VERSION_CONV
-#endif
-#if defined(USE_TLS_SRP)
- | CURL_VERSION_TLSAUTH_SRP
-#endif
-#if defined(USE_NGHTTP2)
- | CURL_VERSION_HTTP2
-#endif
+#if defined(CURL_DOES_CONVERSIONS)
+ | CURL_VERSION_CONV
+#endif
+#if defined(USE_TLS_SRP)
+ | CURL_VERSION_TLSAUTH_SRP
+#endif
+#if defined(USE_NGHTTP2)
+ | CURL_VERSION_HTTP2
+#endif
#if defined(ENABLE_QUIC)
| CURL_VERSION_HTTP3
#endif
@@ -421,16 +421,16 @@ static curl_version_info_data version_info = {
#if defined(USE_HSTS)
| CURL_VERSION_HSTS
#endif
- ,
- NULL, /* ssl_version */
- 0, /* ssl_version_num, this is kept at zero */
- NULL, /* zlib_version */
- protocols,
- NULL, /* c-ares version */
- 0, /* c-ares version numerical */
- NULL, /* libidn version */
- 0, /* iconv version */
- NULL, /* ssh lib version */
+ ,
+ NULL, /* ssl_version */
+ 0, /* ssl_version_num, this is kept at zero */
+ NULL, /* zlib_version */
+ protocols,
+ NULL, /* c-ares version */
+ 0, /* c-ares version numerical */
+ NULL, /* libidn version */
+ 0, /* iconv version */
+ NULL, /* ssh lib version */
0, /* brotli_ver_num */
NULL, /* brotli version */
0, /* nghttp2 version number */
@@ -448,13 +448,13 @@ static curl_version_info_data version_info = {
#endif
0, /* zstd_ver_num */
NULL /* zstd version */
-};
-
-curl_version_info_data *curl_version_info(CURLversion stamp)
-{
+};
+
+curl_version_info_data *curl_version_info(CURLversion stamp)
+{
#if defined(USE_SSH)
- static char ssh_buffer[80];
-#endif
+ static char ssh_buffer[80];
+#endif
#ifdef USE_SSL
#ifdef CURL_WITH_MULTI_SSL
static char ssl_buffer[200];
@@ -468,54 +468,54 @@ curl_version_info_data *curl_version_info(CURLversion stamp)
#ifdef HAVE_ZSTD
static char zstd_buffer[80];
#endif
-
-#ifdef USE_SSL
- Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer));
- version_info.ssl_version = ssl_buffer;
+
+#ifdef USE_SSL
+ Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer));
+ version_info.ssl_version = ssl_buffer;
#ifndef CURL_DISABLE_PROXY
if(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY)
version_info.features |= CURL_VERSION_HTTPS_PROXY;
else
version_info.features &= ~CURL_VERSION_HTTPS_PROXY;
-#endif
-#endif
-
-#ifdef HAVE_LIBZ
- version_info.libz_version = zlibVersion();
- /* libz left NULL if non-existing */
-#endif
-#ifdef USE_ARES
- {
- int aresnum;
- version_info.ares = ares_version(&aresnum);
- version_info.ares_num = aresnum;
- }
-#endif
+#endif
+#endif
+
+#ifdef HAVE_LIBZ
+ version_info.libz_version = zlibVersion();
+ /* libz left NULL if non-existing */
+#endif
+#ifdef USE_ARES
+ {
+ int aresnum;
+ version_info.ares = ares_version(&aresnum);
+ version_info.ares_num = aresnum;
+ }
+#endif
#ifdef USE_LIBIDN2
- /* This returns a version string if we use the given version or later,
- otherwise it returns NULL */
+ /* This returns a version string if we use the given version or later,
+ otherwise it returns NULL */
version_info.libidn = idn2_check_version(IDN2_VERSION);
- if(version_info.libidn)
- version_info.features |= CURL_VERSION_IDN;
-#elif defined(USE_WIN32_IDN)
- version_info.features |= CURL_VERSION_IDN;
-#endif
-
-#if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS)
-#ifdef _LIBICONV_VERSION
- version_info.iconv_ver_num = _LIBICONV_VERSION;
-#else
- /* version unknown */
- version_info.iconv_ver_num = -1;
-#endif /* _LIBICONV_VERSION */
-#endif
-
+ if(version_info.libidn)
+ version_info.features |= CURL_VERSION_IDN;
+#elif defined(USE_WIN32_IDN)
+ version_info.features |= CURL_VERSION_IDN;
+#endif
+
+#if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS)
+#ifdef _LIBICONV_VERSION
+ version_info.iconv_ver_num = _LIBICONV_VERSION;
+#else
+ /* version unknown */
+ version_info.iconv_ver_num = -1;
+#endif /* _LIBICONV_VERSION */
+#endif
+
#if defined(USE_SSH)
Curl_ssh_version(ssh_buffer, sizeof(ssh_buffer));
- version_info.libssh_version = ssh_buffer;
-#endif
-
+ version_info.libssh_version = ssh_buffer;
+#endif
+
#ifdef HAVE_BROTLI
version_info.brotli_ver_num = BrotliDecoderVersion();
brotli_version(brotli_buffer, sizeof(brotli_buffer));
@@ -544,6 +544,6 @@ curl_version_info_data *curl_version_info(CURLversion stamp)
}
#endif
- (void)stamp; /* avoid compiler warnings, we don't use this */
- return &version_info;
-}
+ (void)stamp; /* avoid compiler warnings, we don't use this */
+ return &version_info;
+}
diff --git a/contrib/libs/curl/lib/warnless.c b/contrib/libs/curl/lib/warnless.c
index e5f9954f7f..908ee6cb70 100644
--- a/contrib/libs/curl/lib/warnless.c
+++ b/contrib/libs/curl/lib/warnless.c
@@ -1,180 +1,180 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#if defined(__INTEL_COMPILER) && defined(__unix__)
-
-#ifdef HAVE_NETINET_IN_H
-# include <netinet/in.h>
-#endif
-#ifdef HAVE_ARPA_INET_H
-# include <arpa/inet.h>
-#endif
-
-#endif /* __INTEL_COMPILER && __unix__ */
-
-#define BUILDING_WARNLESS_C 1
-
-#include "warnless.h"
-
-#define CURL_MASK_SCHAR 0x7F
-#define CURL_MASK_UCHAR 0xFF
-
-#if (SIZEOF_SHORT == 2)
-# define CURL_MASK_SSHORT 0x7FFF
-# define CURL_MASK_USHORT 0xFFFF
-#elif (SIZEOF_SHORT == 4)
-# define CURL_MASK_SSHORT 0x7FFFFFFF
-# define CURL_MASK_USHORT 0xFFFFFFFF
-#elif (SIZEOF_SHORT == 8)
-# define CURL_MASK_SSHORT 0x7FFFFFFFFFFFFFFF
-# define CURL_MASK_USHORT 0xFFFFFFFFFFFFFFFF
-#else
-# error "SIZEOF_SHORT not defined"
-#endif
-
-#if (SIZEOF_INT == 2)
-# define CURL_MASK_SINT 0x7FFF
-# define CURL_MASK_UINT 0xFFFF
-#elif (SIZEOF_INT == 4)
-# define CURL_MASK_SINT 0x7FFFFFFF
-# define CURL_MASK_UINT 0xFFFFFFFF
-#elif (SIZEOF_INT == 8)
-# define CURL_MASK_SINT 0x7FFFFFFFFFFFFFFF
-# define CURL_MASK_UINT 0xFFFFFFFFFFFFFFFF
-#elif (SIZEOF_INT == 16)
-# define CURL_MASK_SINT 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
-# define CURL_MASK_UINT 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
-#else
-# error "SIZEOF_INT not defined"
-#endif
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#if defined(__INTEL_COMPILER) && defined(__unix__)
+
+#ifdef HAVE_NETINET_IN_H
+# include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+# include <arpa/inet.h>
+#endif
+
+#endif /* __INTEL_COMPILER && __unix__ */
+
+#define BUILDING_WARNLESS_C 1
+
+#include "warnless.h"
+
+#define CURL_MASK_SCHAR 0x7F
+#define CURL_MASK_UCHAR 0xFF
+
+#if (SIZEOF_SHORT == 2)
+# define CURL_MASK_SSHORT 0x7FFF
+# define CURL_MASK_USHORT 0xFFFF
+#elif (SIZEOF_SHORT == 4)
+# define CURL_MASK_SSHORT 0x7FFFFFFF
+# define CURL_MASK_USHORT 0xFFFFFFFF
+#elif (SIZEOF_SHORT == 8)
+# define CURL_MASK_SSHORT 0x7FFFFFFFFFFFFFFF
+# define CURL_MASK_USHORT 0xFFFFFFFFFFFFFFFF
+#else
+# error "SIZEOF_SHORT not defined"
+#endif
+
+#if (SIZEOF_INT == 2)
+# define CURL_MASK_SINT 0x7FFF
+# define CURL_MASK_UINT 0xFFFF
+#elif (SIZEOF_INT == 4)
+# define CURL_MASK_SINT 0x7FFFFFFF
+# define CURL_MASK_UINT 0xFFFFFFFF
+#elif (SIZEOF_INT == 8)
+# define CURL_MASK_SINT 0x7FFFFFFFFFFFFFFF
+# define CURL_MASK_UINT 0xFFFFFFFFFFFFFFFF
+#elif (SIZEOF_INT == 16)
+# define CURL_MASK_SINT 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
+# define CURL_MASK_UINT 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
+#else
+# error "SIZEOF_INT not defined"
+#endif
+
#if (SIZEOF_LONG == 2)
-# define CURL_MASK_SLONG 0x7FFFL
-# define CURL_MASK_ULONG 0xFFFFUL
+# define CURL_MASK_SLONG 0x7FFFL
+# define CURL_MASK_ULONG 0xFFFFUL
#elif (SIZEOF_LONG == 4)
-# define CURL_MASK_SLONG 0x7FFFFFFFL
-# define CURL_MASK_ULONG 0xFFFFFFFFUL
+# define CURL_MASK_SLONG 0x7FFFFFFFL
+# define CURL_MASK_ULONG 0xFFFFFFFFUL
#elif (SIZEOF_LONG == 8)
-# define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFL
-# define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFUL
+# define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFL
+# define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFUL
#elif (SIZEOF_LONG == 16)
-# define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL
-# define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFUL
-#else
+# define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL
+# define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFUL
+#else
# error "SIZEOF_LONG not defined"
-#endif
-
+#endif
+
#if (SIZEOF_CURL_OFF_T == 2)
-# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFF)
-# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFF)
+# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFF)
+# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFF)
#elif (SIZEOF_CURL_OFF_T == 4)
-# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFF)
-# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFF)
+# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFF)
+# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFF)
#elif (SIZEOF_CURL_OFF_T == 8)
-# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF)
-# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFF)
+# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF)
+# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFF)
#elif (SIZEOF_CURL_OFF_T == 16)
-# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
-# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
-#else
+# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
+# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
+#else
# error "SIZEOF_CURL_OFF_T not defined"
-#endif
-
-#if (SIZEOF_SIZE_T == SIZEOF_SHORT)
-# define CURL_MASK_SSIZE_T CURL_MASK_SSHORT
-# define CURL_MASK_USIZE_T CURL_MASK_USHORT
-#elif (SIZEOF_SIZE_T == SIZEOF_INT)
-# define CURL_MASK_SSIZE_T CURL_MASK_SINT
-# define CURL_MASK_USIZE_T CURL_MASK_UINT
+#endif
+
+#if (SIZEOF_SIZE_T == SIZEOF_SHORT)
+# define CURL_MASK_SSIZE_T CURL_MASK_SSHORT
+# define CURL_MASK_USIZE_T CURL_MASK_USHORT
+#elif (SIZEOF_SIZE_T == SIZEOF_INT)
+# define CURL_MASK_SSIZE_T CURL_MASK_SINT
+# define CURL_MASK_USIZE_T CURL_MASK_UINT
#elif (SIZEOF_SIZE_T == SIZEOF_LONG)
-# define CURL_MASK_SSIZE_T CURL_MASK_SLONG
-# define CURL_MASK_USIZE_T CURL_MASK_ULONG
+# define CURL_MASK_SSIZE_T CURL_MASK_SLONG
+# define CURL_MASK_USIZE_T CURL_MASK_ULONG
#elif (SIZEOF_SIZE_T == SIZEOF_CURL_OFF_T)
-# define CURL_MASK_SSIZE_T CURL_MASK_SCOFFT
-# define CURL_MASK_USIZE_T CURL_MASK_UCOFFT
-#else
-# error "SIZEOF_SIZE_T not defined"
-#endif
-
-/*
-** unsigned long to unsigned short
-*/
-
-unsigned short curlx_ultous(unsigned long ulnum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_USHORT);
- return (unsigned short)(ulnum & (unsigned long) CURL_MASK_USHORT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** unsigned long to unsigned char
-*/
-
-unsigned char curlx_ultouc(unsigned long ulnum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_UCHAR);
- return (unsigned char)(ulnum & (unsigned long) CURL_MASK_UCHAR);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** unsigned long to signed int
-*/
-
-int curlx_ultosi(unsigned long ulnum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_SINT);
- return (int)(ulnum & (unsigned long) CURL_MASK_SINT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
+# define CURL_MASK_SSIZE_T CURL_MASK_SCOFFT
+# define CURL_MASK_USIZE_T CURL_MASK_UCOFFT
+#else
+# error "SIZEOF_SIZE_T not defined"
+#endif
+
+/*
+** unsigned long to unsigned short
+*/
+
+unsigned short curlx_ultous(unsigned long ulnum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_USHORT);
+ return (unsigned short)(ulnum & (unsigned long) CURL_MASK_USHORT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** unsigned long to unsigned char
+*/
+
+unsigned char curlx_ultouc(unsigned long ulnum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_UCHAR);
+ return (unsigned char)(ulnum & (unsigned long) CURL_MASK_UCHAR);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** unsigned long to signed int
+*/
+
+int curlx_ultosi(unsigned long ulnum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_SINT);
+ return (int)(ulnum & (unsigned long) CURL_MASK_SINT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
** unsigned size_t to signed curl_off_t
*/
@@ -197,191 +197,191 @@ curl_off_t curlx_uztoso(size_t uznum)
}
/*
-** unsigned size_t to signed int
-*/
-
-int curlx_uztosi(size_t uznum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(uznum <= (size_t) CURL_MASK_SINT);
- return (int)(uznum & (size_t) CURL_MASK_SINT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** unsigned size_t to unsigned long
-*/
-
-unsigned long curlx_uztoul(size_t uznum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
+** unsigned size_t to signed int
+*/
+
+int curlx_uztosi(size_t uznum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(uznum <= (size_t) CURL_MASK_SINT);
+ return (int)(uznum & (size_t) CURL_MASK_SINT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** unsigned size_t to unsigned long
+*/
+
+unsigned long curlx_uztoul(size_t uznum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
#if (SIZEOF_LONG < SIZEOF_SIZE_T)
- DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG);
-#endif
- return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** unsigned size_t to unsigned int
-*/
-
-unsigned int curlx_uztoui(size_t uznum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
-#if (SIZEOF_INT < SIZEOF_SIZE_T)
- DEBUGASSERT(uznum <= (size_t) CURL_MASK_UINT);
-#endif
- return (unsigned int)(uznum & (size_t) CURL_MASK_UINT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** signed long to signed int
-*/
-
-int curlx_sltosi(long slnum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(slnum >= 0);
+ DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG);
+#endif
+ return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** unsigned size_t to unsigned int
+*/
+
+unsigned int curlx_uztoui(size_t uznum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+#if (SIZEOF_INT < SIZEOF_SIZE_T)
+ DEBUGASSERT(uznum <= (size_t) CURL_MASK_UINT);
+#endif
+ return (unsigned int)(uznum & (size_t) CURL_MASK_UINT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** signed long to signed int
+*/
+
+int curlx_sltosi(long slnum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(slnum >= 0);
#if (SIZEOF_INT < SIZEOF_LONG)
- DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT);
-#endif
- return (int)(slnum & (long) CURL_MASK_SINT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** signed long to unsigned int
-*/
-
-unsigned int curlx_sltoui(long slnum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(slnum >= 0);
+ DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT);
+#endif
+ return (int)(slnum & (long) CURL_MASK_SINT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** signed long to unsigned int
+*/
+
+unsigned int curlx_sltoui(long slnum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(slnum >= 0);
#if (SIZEOF_INT < SIZEOF_LONG)
- DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT);
-#endif
- return (unsigned int)(slnum & (long) CURL_MASK_UINT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** signed long to unsigned short
-*/
-
-unsigned short curlx_sltous(long slnum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(slnum >= 0);
- DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_USHORT);
- return (unsigned short)(slnum & (long) CURL_MASK_USHORT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** unsigned size_t to signed ssize_t
-*/
-
-ssize_t curlx_uztosz(size_t uznum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(uznum <= (size_t) CURL_MASK_SSIZE_T);
- return (ssize_t)(uznum & (size_t) CURL_MASK_SSIZE_T);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** signed curl_off_t to unsigned size_t
-*/
-
-size_t curlx_sotouz(curl_off_t sonum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(sonum >= 0);
- return (size_t)(sonum & (curl_off_t) CURL_MASK_USIZE_T);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
-** signed ssize_t to signed int
-*/
-
-int curlx_sztosi(ssize_t sznum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(sznum >= 0);
-#if (SIZEOF_INT < SIZEOF_SIZE_T)
- DEBUGASSERT((size_t) sznum <= (size_t) CURL_MASK_SINT);
-#endif
- return (int)(sznum & (ssize_t) CURL_MASK_SINT);
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-/*
+ DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT);
+#endif
+ return (unsigned int)(slnum & (long) CURL_MASK_UINT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** signed long to unsigned short
+*/
+
+unsigned short curlx_sltous(long slnum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(slnum >= 0);
+ DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_USHORT);
+ return (unsigned short)(slnum & (long) CURL_MASK_USHORT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** unsigned size_t to signed ssize_t
+*/
+
+ssize_t curlx_uztosz(size_t uznum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(uznum <= (size_t) CURL_MASK_SSIZE_T);
+ return (ssize_t)(uznum & (size_t) CURL_MASK_SSIZE_T);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** signed curl_off_t to unsigned size_t
+*/
+
+size_t curlx_sotouz(curl_off_t sonum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(sonum >= 0);
+ return (size_t)(sonum & (curl_off_t) CURL_MASK_USIZE_T);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
+** signed ssize_t to signed int
+*/
+
+int curlx_sztosi(ssize_t sznum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(sznum >= 0);
+#if (SIZEOF_INT < SIZEOF_SIZE_T)
+ DEBUGASSERT((size_t) sznum <= (size_t) CURL_MASK_SINT);
+#endif
+ return (int)(sznum & (ssize_t) CURL_MASK_SINT);
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+/*
** unsigned int to unsigned short
*/
@@ -401,46 +401,46 @@ unsigned short curlx_uitous(unsigned int uinum)
}
/*
-** signed int to unsigned size_t
-*/
-
-size_t curlx_sitouz(int sinum)
-{
-#ifdef __INTEL_COMPILER
-# pragma warning(push)
-# pragma warning(disable:810) /* conversion may lose significant bits */
-#endif
-
- DEBUGASSERT(sinum >= 0);
- return (size_t) sinum;
-
-#ifdef __INTEL_COMPILER
-# pragma warning(pop)
-#endif
-}
-
-#ifdef USE_WINSOCK
-
-/*
-** curl_socket_t to signed int
-*/
-
-int curlx_sktosi(curl_socket_t s)
-{
- return (int)((ssize_t) s);
-}
-
-/*
-** signed int to curl_socket_t
-*/
-
-curl_socket_t curlx_sitosk(int i)
-{
- return (curl_socket_t)((ssize_t) i);
-}
-
-#endif /* USE_WINSOCK */
-
+** signed int to unsigned size_t
+*/
+
+size_t curlx_sitouz(int sinum)
+{
+#ifdef __INTEL_COMPILER
+# pragma warning(push)
+# pragma warning(disable:810) /* conversion may lose significant bits */
+#endif
+
+ DEBUGASSERT(sinum >= 0);
+ return (size_t) sinum;
+
+#ifdef __INTEL_COMPILER
+# pragma warning(pop)
+#endif
+}
+
+#ifdef USE_WINSOCK
+
+/*
+** curl_socket_t to signed int
+*/
+
+int curlx_sktosi(curl_socket_t s)
+{
+ return (int)((ssize_t) s);
+}
+
+/*
+** signed int to curl_socket_t
+*/
+
+curl_socket_t curlx_sitosk(int i)
+{
+ return (curl_socket_t)((ssize_t) i);
+}
+
+#endif /* USE_WINSOCK */
+
#if defined(WIN32) || defined(_WIN32)
ssize_t curlx_read(int fd, void *buf, size_t count)
@@ -455,54 +455,54 @@ ssize_t curlx_write(int fd, const void *buf, size_t count)
#endif /* WIN32 || _WIN32 */
-#if defined(__INTEL_COMPILER) && defined(__unix__)
-
-int curlx_FD_ISSET(int fd, fd_set *fdset)
-{
- #pragma warning(push)
- #pragma warning(disable:1469) /* clobber ignored */
- return FD_ISSET(fd, fdset);
- #pragma warning(pop)
-}
-
-void curlx_FD_SET(int fd, fd_set *fdset)
-{
- #pragma warning(push)
- #pragma warning(disable:1469) /* clobber ignored */
- FD_SET(fd, fdset);
- #pragma warning(pop)
-}
-
-void curlx_FD_ZERO(fd_set *fdset)
-{
- #pragma warning(push)
- #pragma warning(disable:593) /* variable was set but never used */
- FD_ZERO(fdset);
- #pragma warning(pop)
-}
-
-unsigned short curlx_htons(unsigned short usnum)
-{
-#if (__INTEL_COMPILER == 910) && defined(__i386__)
- return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF));
-#else
- #pragma warning(push)
- #pragma warning(disable:810) /* conversion may lose significant bits */
- return htons(usnum);
- #pragma warning(pop)
-#endif
-}
-
-unsigned short curlx_ntohs(unsigned short usnum)
-{
-#if (__INTEL_COMPILER == 910) && defined(__i386__)
- return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF));
-#else
- #pragma warning(push)
- #pragma warning(disable:810) /* conversion may lose significant bits */
- return ntohs(usnum);
- #pragma warning(pop)
-#endif
-}
-
-#endif /* __INTEL_COMPILER && __unix__ */
+#if defined(__INTEL_COMPILER) && defined(__unix__)
+
+int curlx_FD_ISSET(int fd, fd_set *fdset)
+{
+ #pragma warning(push)
+ #pragma warning(disable:1469) /* clobber ignored */
+ return FD_ISSET(fd, fdset);
+ #pragma warning(pop)
+}
+
+void curlx_FD_SET(int fd, fd_set *fdset)
+{
+ #pragma warning(push)
+ #pragma warning(disable:1469) /* clobber ignored */
+ FD_SET(fd, fdset);
+ #pragma warning(pop)
+}
+
+void curlx_FD_ZERO(fd_set *fdset)
+{
+ #pragma warning(push)
+ #pragma warning(disable:593) /* variable was set but never used */
+ FD_ZERO(fdset);
+ #pragma warning(pop)
+}
+
+unsigned short curlx_htons(unsigned short usnum)
+{
+#if (__INTEL_COMPILER == 910) && defined(__i386__)
+ return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF));
+#else
+ #pragma warning(push)
+ #pragma warning(disable:810) /* conversion may lose significant bits */
+ return htons(usnum);
+ #pragma warning(pop)
+#endif
+}
+
+unsigned short curlx_ntohs(unsigned short usnum)
+{
+#if (__INTEL_COMPILER == 910) && defined(__i386__)
+ return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF));
+#else
+ #pragma warning(push)
+ #pragma warning(disable:810) /* conversion may lose significant bits */
+ return ntohs(usnum);
+ #pragma warning(pop)
+#endif
+}
+
+#endif /* __INTEL_COMPILER && __unix__ */
diff --git a/contrib/libs/curl/lib/warnless.h b/contrib/libs/curl/lib/warnless.h
index 1bce6e8995..ca3737859b 100644
--- a/contrib/libs/curl/lib/warnless.h
+++ b/contrib/libs/curl/lib/warnless.h
@@ -1,72 +1,72 @@
-#ifndef HEADER_CURL_WARNLESS_H
-#define HEADER_CURL_WARNLESS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_WARNLESS_H
+#define HEADER_CURL_WARNLESS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#ifdef USE_WINSOCK
-#include <curl/curl.h> /* for curl_socket_t */
-#endif
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#ifdef USE_WINSOCK
+#include <curl/curl.h> /* for curl_socket_t */
+#endif
+
#define CURLX_FUNCTION_CAST(target_type, func) \
(target_type)(void (*) (void))(func)
-unsigned short curlx_ultous(unsigned long ulnum);
-
-unsigned char curlx_ultouc(unsigned long ulnum);
-
-int curlx_ultosi(unsigned long ulnum);
-
-int curlx_uztosi(size_t uznum);
-
+unsigned short curlx_ultous(unsigned long ulnum);
+
+unsigned char curlx_ultouc(unsigned long ulnum);
+
+int curlx_ultosi(unsigned long ulnum);
+
+int curlx_uztosi(size_t uznum);
+
curl_off_t curlx_uztoso(size_t uznum);
-unsigned long curlx_uztoul(size_t uznum);
-
-unsigned int curlx_uztoui(size_t uznum);
-
-int curlx_sltosi(long slnum);
-
-unsigned int curlx_sltoui(long slnum);
-
-unsigned short curlx_sltous(long slnum);
-
-ssize_t curlx_uztosz(size_t uznum);
-
-size_t curlx_sotouz(curl_off_t sonum);
-
-int curlx_sztosi(ssize_t sznum);
-
+unsigned long curlx_uztoul(size_t uznum);
+
+unsigned int curlx_uztoui(size_t uznum);
+
+int curlx_sltosi(long slnum);
+
+unsigned int curlx_sltoui(long slnum);
+
+unsigned short curlx_sltous(long slnum);
+
+ssize_t curlx_uztosz(size_t uznum);
+
+size_t curlx_sotouz(curl_off_t sonum);
+
+int curlx_sztosi(ssize_t sznum);
+
unsigned short curlx_uitous(unsigned int uinum);
-size_t curlx_sitouz(int sinum);
-
-#ifdef USE_WINSOCK
-
-int curlx_sktosi(curl_socket_t s);
-
-curl_socket_t curlx_sitosk(int i);
-
-#endif /* USE_WINSOCK */
-
+size_t curlx_sitouz(int sinum);
+
+#ifdef USE_WINSOCK
+
+int curlx_sktosi(curl_socket_t s);
+
+curl_socket_t curlx_sitosk(int i);
+
+#endif /* USE_WINSOCK */
+
#if defined(WIN32) || defined(_WIN32)
ssize_t curlx_read(int fd, void *buf, size_t count);
@@ -82,18 +82,18 @@ ssize_t curlx_write(int fd, const void *buf, size_t count);
#endif /* WIN32 || _WIN32 */
-#if defined(__INTEL_COMPILER) && defined(__unix__)
-
-int curlx_FD_ISSET(int fd, fd_set *fdset);
-
-void curlx_FD_SET(int fd, fd_set *fdset);
-
-void curlx_FD_ZERO(fd_set *fdset);
-
-unsigned short curlx_htons(unsigned short usnum);
-
-unsigned short curlx_ntohs(unsigned short usnum);
-
-#endif /* __INTEL_COMPILER && __unix__ */
-
-#endif /* HEADER_CURL_WARNLESS_H */
+#if defined(__INTEL_COMPILER) && defined(__unix__)
+
+int curlx_FD_ISSET(int fd, fd_set *fdset);
+
+void curlx_FD_SET(int fd, fd_set *fdset);
+
+void curlx_FD_ZERO(fd_set *fdset);
+
+unsigned short curlx_htons(unsigned short usnum);
+
+unsigned short curlx_ntohs(unsigned short usnum);
+
+#endif /* __INTEL_COMPILER && __unix__ */
+
+#endif /* HEADER_CURL_WARNLESS_H */
diff --git a/contrib/libs/curl/lib/wildcard.c b/contrib/libs/curl/lib/wildcard.c
index 23ee9a43e5..105bcce4ed 100644
--- a/contrib/libs/curl/lib/wildcard.c
+++ b/contrib/libs/curl/lib/wildcard.c
@@ -1,73 +1,73 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#ifndef CURL_DISABLE_FTP
-#include "wildcard.h"
-#include "llist.h"
-#include "fileinfo.h"
+#include "wildcard.h"
+#include "llist.h"
+#include "fileinfo.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
static void fileinfo_dtor(void *user, void *element)
{
(void)user;
Curl_fileinfo_cleanup(element);
}
-CURLcode Curl_wildcard_init(struct WildcardData *wc)
-{
+CURLcode Curl_wildcard_init(struct WildcardData *wc)
+{
Curl_llist_init(&wc->filelist, fileinfo_dtor);
wc->state = CURLWC_INIT;
- return CURLE_OK;
-}
-
-void Curl_wildcard_dtor(struct WildcardData *wc)
-{
- if(!wc)
- return;
-
+ return CURLE_OK;
+}
+
+void Curl_wildcard_dtor(struct WildcardData *wc)
+{
+ if(!wc)
+ return;
+
if(wc->dtor) {
wc->dtor(wc->protdata);
wc->dtor = ZERO_NULL;
wc->protdata = NULL;
- }
+ }
DEBUGASSERT(wc->protdata == NULL);
-
+
Curl_llist_destroy(&wc->filelist, NULL);
-
-
+
+
free(wc->path);
wc->path = NULL;
free(wc->pattern);
wc->pattern = NULL;
-
- wc->customptr = NULL;
- wc->state = CURLWC_INIT;
-}
+
+ wc->customptr = NULL;
+ wc->state = CURLWC_INIT;
+}
#endif /* if disabled */
diff --git a/contrib/libs/curl/lib/wildcard.h b/contrib/libs/curl/lib/wildcard.h
index e89925f084..081be9ed93 100644
--- a/contrib/libs/curl/lib/wildcard.h
+++ b/contrib/libs/curl/lib/wildcard.h
@@ -1,67 +1,67 @@
-#ifndef HEADER_CURL_WILDCARD_H
-#define HEADER_CURL_WILDCARD_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_WILDCARD_H
+#define HEADER_CURL_WILDCARD_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 2010 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
#include "curl_setup.h"
-
+
#ifndef CURL_DISABLE_FTP
#include "llist.h"
-/* list of wildcard process states */
-typedef enum {
+/* list of wildcard process states */
+typedef enum {
CURLWC_CLEAR = 0,
CURLWC_INIT = 1,
- CURLWC_MATCHING, /* library is trying to get list of addresses for
- downloading */
- CURLWC_DOWNLOADING,
- CURLWC_CLEAN, /* deallocate resources and reset settings */
- CURLWC_SKIP, /* skip over concrete file */
- CURLWC_ERROR, /* error cases */
- CURLWC_DONE /* if is wildcard->state == CURLWC_DONE wildcard loop
- will end */
+ CURLWC_MATCHING, /* library is trying to get list of addresses for
+ downloading */
+ CURLWC_DOWNLOADING,
+ CURLWC_CLEAN, /* deallocate resources and reset settings */
+ CURLWC_SKIP, /* skip over concrete file */
+ CURLWC_ERROR, /* error cases */
+ CURLWC_DONE /* if is wildcard->state == CURLWC_DONE wildcard loop
+ will end */
} wildcard_states;
-
+
typedef void (*wildcard_dtor)(void *ptr);
-
-/* struct keeping information about wildcard download process */
-struct WildcardData {
+
+/* struct keeping information about wildcard download process */
+struct WildcardData {
wildcard_states state;
- char *path; /* path to the directory, where we trying wildcard-match */
- char *pattern; /* wildcard pattern */
+ char *path; /* path to the directory, where we trying wildcard-match */
+ char *pattern; /* wildcard pattern */
struct Curl_llist filelist; /* llist with struct Curl_fileinfo */
void *protdata; /* pointer to protocol specific temporary data */
wildcard_dtor dtor;
- void *customptr; /* for CURLOPT_CHUNK_DATA pointer */
-};
-
-CURLcode Curl_wildcard_init(struct WildcardData *wc);
-void Curl_wildcard_dtor(struct WildcardData *wc);
-
+ void *customptr; /* for CURLOPT_CHUNK_DATA pointer */
+};
+
+CURLcode Curl_wildcard_init(struct WildcardData *wc);
+void Curl_wildcard_dtor(struct WildcardData *wc);
+
struct Curl_easy;
-
+
#else
/* FTP is disabled */
#define Curl_wildcard_dtor(x)
#endif
-#endif /* HEADER_CURL_WILDCARD_H */
+#endif /* HEADER_CURL_WILDCARD_H */
diff --git a/contrib/libs/curl/lib/x509asn1.c b/contrib/libs/curl/lib/x509asn1.c
index cba3bec135..d7cf9eb2af 100644
--- a/contrib/libs/curl/lib/x509asn1.c
+++ b/contrib/libs/curl/lib/x509asn1.c
@@ -1,191 +1,191 @@
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \
defined(USE_WOLFSSL) || defined(USE_SCHANNEL)
-
-#include <curl/curl.h>
-#include "urldata.h"
+
+#include <curl/curl.h>
+#include "urldata.h"
#include "strcase.h"
-#include "hostcheck.h"
+#include "hostcheck.h"
#include "vtls/vtls.h"
-#include "sendf.h"
-#include "inet_pton.h"
-#include "curl_base64.h"
-#include "x509asn1.h"
-
+#include "sendf.h"
+#include "inet_pton.h"
+#include "curl_base64.h"
+#include "x509asn1.h"
+
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
-#include "curl_memory.h"
-#include "memdebug.h"
-
-/* ASN.1 OIDs. */
-static const char cnOID[] = "2.5.4.3"; /* Common name. */
-static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */
-
+#include "curl_memory.h"
+#include "memdebug.h"
+
+/* ASN.1 OIDs. */
+static const char cnOID[] = "2.5.4.3"; /* Common name. */
+static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */
+
static const struct Curl_OID OIDtable[] = {
- { "1.2.840.10040.4.1", "dsa" },
- { "1.2.840.10040.4.3", "dsa-with-sha1" },
- { "1.2.840.10045.2.1", "ecPublicKey" },
- { "1.2.840.10045.3.0.1", "c2pnb163v1" },
- { "1.2.840.10045.4.1", "ecdsa-with-SHA1" },
- { "1.2.840.10046.2.1", "dhpublicnumber" },
- { "1.2.840.113549.1.1.1", "rsaEncryption" },
- { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" },
- { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" },
- { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" },
- { "1.2.840.113549.1.1.10", "RSASSA-PSS" },
- { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" },
- { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" },
- { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" },
- { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" },
- { "1.2.840.113549.2.2", "md2" },
- { "1.2.840.113549.2.5", "md5" },
- { "1.3.14.3.2.26", "sha1" },
- { cnOID, "CN" },
- { "2.5.4.4", "SN" },
- { "2.5.4.5", "serialNumber" },
- { "2.5.4.6", "C" },
- { "2.5.4.7", "L" },
- { "2.5.4.8", "ST" },
- { "2.5.4.9", "streetAddress" },
- { "2.5.4.10", "O" },
- { "2.5.4.11", "OU" },
- { "2.5.4.12", "title" },
- { "2.5.4.13", "description" },
- { "2.5.4.17", "postalCode" },
- { "2.5.4.41", "name" },
- { "2.5.4.42", "givenName" },
- { "2.5.4.43", "initials" },
- { "2.5.4.44", "generationQualifier" },
- { "2.5.4.45", "X500UniqueIdentifier" },
- { "2.5.4.46", "dnQualifier" },
- { "2.5.4.65", "pseudonym" },
- { "1.2.840.113549.1.9.1", "emailAddress" },
- { "2.5.4.72", "role" },
- { sanOID, "subjectAltName" },
- { "2.5.29.18", "issuerAltName" },
- { "2.5.29.19", "basicConstraints" },
- { "2.16.840.1.101.3.4.2.4", "sha224" },
- { "2.16.840.1.101.3.4.2.1", "sha256" },
- { "2.16.840.1.101.3.4.2.2", "sha384" },
- { "2.16.840.1.101.3.4.2.3", "sha512" },
- { (const char *) NULL, (const char *) NULL }
-};
-
-/*
- * Lightweight ASN.1 parser.
- * In particular, it does not check for syntactic/lexical errors.
- * It is intended to support certificate information gathering for SSL backends
- * that offer a mean to get certificates as a whole, but do not supply
- * entry points to get particular certificate sub-fields.
- * Please note there is no pretention here to rewrite a full SSL library.
- */
-
+ { "1.2.840.10040.4.1", "dsa" },
+ { "1.2.840.10040.4.3", "dsa-with-sha1" },
+ { "1.2.840.10045.2.1", "ecPublicKey" },
+ { "1.2.840.10045.3.0.1", "c2pnb163v1" },
+ { "1.2.840.10045.4.1", "ecdsa-with-SHA1" },
+ { "1.2.840.10046.2.1", "dhpublicnumber" },
+ { "1.2.840.113549.1.1.1", "rsaEncryption" },
+ { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" },
+ { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" },
+ { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" },
+ { "1.2.840.113549.1.1.10", "RSASSA-PSS" },
+ { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" },
+ { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" },
+ { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" },
+ { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" },
+ { "1.2.840.113549.2.2", "md2" },
+ { "1.2.840.113549.2.5", "md5" },
+ { "1.3.14.3.2.26", "sha1" },
+ { cnOID, "CN" },
+ { "2.5.4.4", "SN" },
+ { "2.5.4.5", "serialNumber" },
+ { "2.5.4.6", "C" },
+ { "2.5.4.7", "L" },
+ { "2.5.4.8", "ST" },
+ { "2.5.4.9", "streetAddress" },
+ { "2.5.4.10", "O" },
+ { "2.5.4.11", "OU" },
+ { "2.5.4.12", "title" },
+ { "2.5.4.13", "description" },
+ { "2.5.4.17", "postalCode" },
+ { "2.5.4.41", "name" },
+ { "2.5.4.42", "givenName" },
+ { "2.5.4.43", "initials" },
+ { "2.5.4.44", "generationQualifier" },
+ { "2.5.4.45", "X500UniqueIdentifier" },
+ { "2.5.4.46", "dnQualifier" },
+ { "2.5.4.65", "pseudonym" },
+ { "1.2.840.113549.1.9.1", "emailAddress" },
+ { "2.5.4.72", "role" },
+ { sanOID, "subjectAltName" },
+ { "2.5.29.18", "issuerAltName" },
+ { "2.5.29.19", "basicConstraints" },
+ { "2.16.840.1.101.3.4.2.4", "sha224" },
+ { "2.16.840.1.101.3.4.2.1", "sha256" },
+ { "2.16.840.1.101.3.4.2.2", "sha384" },
+ { "2.16.840.1.101.3.4.2.3", "sha512" },
+ { (const char *) NULL, (const char *) NULL }
+};
+
+/*
+ * Lightweight ASN.1 parser.
+ * In particular, it does not check for syntactic/lexical errors.
+ * It is intended to support certificate information gathering for SSL backends
+ * that offer a mean to get certificates as a whole, but do not supply
+ * entry points to get particular certificate sub-fields.
+ * Please note there is no pretention here to rewrite a full SSL library.
+ */
+
static const char *getASN1Element(struct Curl_asn1Element *elem,
const char *beg, const char *end)
WARN_UNUSED_RESULT;
-
+
static const char *getASN1Element(struct Curl_asn1Element *elem,
const char *beg, const char *end)
-{
- unsigned char b;
- unsigned long len;
+{
+ unsigned char b;
+ unsigned long len;
struct Curl_asn1Element lelem;
-
- /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg'
- ending at `end'.
- Returns a pointer in source string after the parsed element, or NULL
- if an error occurs. */
+
+ /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg'
+ ending at `end'.
+ Returns a pointer in source string after the parsed element, or NULL
+ if an error occurs. */
if(!beg || !end || beg >= end || !*beg ||
(size_t)(end - beg) > CURL_ASN1_MAX)
return NULL;
-
- /* Process header byte. */
+
+ /* Process header byte. */
elem->header = beg;
- b = (unsigned char) *beg++;
- elem->constructed = (b & 0x20) != 0;
- elem->class = (b >> 6) & 3;
- b &= 0x1F;
- if(b == 0x1F)
+ b = (unsigned char) *beg++;
+ elem->constructed = (b & 0x20) != 0;
+ elem->class = (b >> 6) & 3;
+ b &= 0x1F;
+ if(b == 0x1F)
return NULL; /* Long tag values not supported here. */
- elem->tag = b;
-
- /* Process length. */
- if(beg >= end)
+ elem->tag = b;
+
+ /* Process length. */
+ if(beg >= end)
return NULL;
- b = (unsigned char) *beg++;
- if(!(b & 0x80))
- len = b;
- else if(!(b &= 0x7F)) {
- /* Unspecified length. Since we have all the data, we can determine the
- effective length by skipping element until an end element is found. */
- if(!elem->constructed)
+ b = (unsigned char) *beg++;
+ if(!(b & 0x80))
+ len = b;
+ else if(!(b &= 0x7F)) {
+ /* Unspecified length. Since we have all the data, we can determine the
+ effective length by skipping element until an end element is found. */
+ if(!elem->constructed)
return NULL;
- elem->beg = beg;
- while(beg < end && *beg) {
+ elem->beg = beg;
+ while(beg < end && *beg) {
beg = getASN1Element(&lelem, beg, end);
- if(!beg)
+ if(!beg)
return NULL;
- }
- if(beg >= end)
+ }
+ if(beg >= end)
return NULL;
- elem->end = beg;
- return beg + 1;
- }
+ elem->end = beg;
+ return beg + 1;
+ }
else if((unsigned)b > (size_t)(end - beg))
return NULL; /* Does not fit in source. */
- else {
- /* Get long length. */
- len = 0;
- do {
- if(len & 0xFF000000L)
+ else {
+ /* Get long length. */
+ len = 0;
+ do {
+ if(len & 0xFF000000L)
return NULL; /* Lengths > 32 bits are not supported. */
- len = (len << 8) | (unsigned char) *beg++;
- } while(--b);
- }
+ len = (len << 8) | (unsigned char) *beg++;
+ } while(--b);
+ }
if(len > (size_t)(end - beg))
return NULL; /* Element data does not fit in source. */
- elem->beg = beg;
- elem->end = beg + len;
- return elem->end;
-}
-
+ elem->beg = beg;
+ elem->end = beg + len;
+ return elem->end;
+}
+
/*
* Search the null terminated OID or OID identifier in local table.
* Return the table entry pointer or NULL if not found.
*/
static const struct Curl_OID *searchOID(const char *oid)
-{
+{
const struct Curl_OID *op;
- for(op = OIDtable; op->numoid; op++)
+ for(op = OIDtable; op->numoid; op++)
if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid))
- return op;
-
+ return op;
+
return NULL;
-}
-
+}
+
/*
* Convert an ASN.1 Boolean value into its string representation. Return the
* dynamically allocated string, or NULL if source is not an ASN.1 Boolean
@@ -193,66 +193,66 @@ static const struct Curl_OID *searchOID(const char *oid)
*/
static const char *bool2str(const char *beg, const char *end)
-{
- if(end - beg != 1)
+{
+ if(end - beg != 1)
return NULL;
- return strdup(*beg? "TRUE": "FALSE");
-}
-
+ return strdup(*beg? "TRUE": "FALSE");
+}
+
/*
* Convert an ASN.1 octet string to a printable string.
* Return the dynamically allocated string, or NULL if an error occurs.
*/
static const char *octet2str(const char *beg, const char *end)
-{
- size_t n = end - beg;
+{
+ size_t n = end - beg;
char *buf = NULL;
-
+
if(n <= (SIZE_T_MAX - 1) / 3) {
buf = malloc(3 * n + 1);
if(buf)
for(n = 0; beg < end; n += 3)
msnprintf(buf + n, 4, "%02x:", *(const unsigned char *) beg++);
}
- return buf;
-}
-
+ return buf;
+}
+
static const char *bit2str(const char *beg, const char *end)
-{
- /* Convert an ASN.1 bit string to a printable string.
- Return the dynamically allocated string, or NULL if an error occurs. */
-
- if(++beg > end)
+{
+ /* Convert an ASN.1 bit string to a printable string.
+ Return the dynamically allocated string, or NULL if an error occurs. */
+
+ if(++beg > end)
return NULL;
- return octet2str(beg, end);
-}
-
+ return octet2str(beg, end);
+}
+
/*
* Convert an ASN.1 integer value into its string representation.
* Return the dynamically allocated string, or NULL if source is not an
* ASN.1 integer value.
*/
static const char *int2str(const char *beg, const char *end)
-{
+{
unsigned long val = 0;
- size_t n = end - beg;
-
- if(!n)
+ size_t n = end - beg;
+
+ if(!n)
return NULL;
-
- if(n > 4)
- return octet2str(beg, end);
-
- /* Represent integers <= 32-bit as a single value. */
- if(*beg & 0x80)
- val = ~val;
-
- do
- val = (val << 8) | *(const unsigned char *) beg++;
- while(beg < end);
+
+ if(n > 4)
+ return octet2str(beg, end);
+
+ /* Represent integers <= 32-bit as a single value. */
+ if(*beg & 0x80)
+ val = ~val;
+
+ do
+ val = (val << 8) | *(const unsigned char *) beg++;
+ while(beg < end);
return curl_maprintf("%s%lx", val >= 10? "0x": "", val);
-}
-
+}
+
/*
* Perform a lazy conversion from an ASN.1 typed string to UTF8. Allocate the
* destination buffer dynamically. The allocation size will normally be too
@@ -260,127 +260,127 @@ static const char *int2str(const char *beg, const char *end)
* Terminate the string with a nul byte and return the converted
* string length.
*/
-static ssize_t
+static ssize_t
utf8asn1str(char **to, int type, const char *from, const char *end)
-{
- size_t inlength = end - from;
- int size = 1;
- size_t outlength;
+{
+ size_t inlength = end - from;
+ int size = 1;
+ size_t outlength;
char *buf;
-
+
*to = NULL;
switch(type) {
- case CURL_ASN1_BMP_STRING:
- size = 2;
- break;
- case CURL_ASN1_UNIVERSAL_STRING:
- size = 4;
- break;
- case CURL_ASN1_NUMERIC_STRING:
- case CURL_ASN1_PRINTABLE_STRING:
- case CURL_ASN1_TELETEX_STRING:
- case CURL_ASN1_IA5_STRING:
- case CURL_ASN1_VISIBLE_STRING:
- case CURL_ASN1_UTF8_STRING:
- break;
- default:
- return -1; /* Conversion not supported. */
- }
-
- if(inlength % size)
- return -1; /* Length inconsistent with character size. */
+ case CURL_ASN1_BMP_STRING:
+ size = 2;
+ break;
+ case CURL_ASN1_UNIVERSAL_STRING:
+ size = 4;
+ break;
+ case CURL_ASN1_NUMERIC_STRING:
+ case CURL_ASN1_PRINTABLE_STRING:
+ case CURL_ASN1_TELETEX_STRING:
+ case CURL_ASN1_IA5_STRING:
+ case CURL_ASN1_VISIBLE_STRING:
+ case CURL_ASN1_UTF8_STRING:
+ break;
+ default:
+ return -1; /* Conversion not supported. */
+ }
+
+ if(inlength % size)
+ return -1; /* Length inconsistent with character size. */
if(inlength / size > (SIZE_T_MAX - 1) / 4)
return -1; /* Too big. */
- buf = malloc(4 * (inlength / size) + 1);
- if(!buf)
- return -1; /* Not enough memory. */
-
- if(type == CURL_ASN1_UTF8_STRING) {
- /* Just copy. */
- outlength = inlength;
- if(outlength)
- memcpy(buf, from, outlength);
- }
- else {
- for(outlength = 0; from < end;) {
+ buf = malloc(4 * (inlength / size) + 1);
+ if(!buf)
+ return -1; /* Not enough memory. */
+
+ if(type == CURL_ASN1_UTF8_STRING) {
+ /* Just copy. */
+ outlength = inlength;
+ if(outlength)
+ memcpy(buf, from, outlength);
+ }
+ else {
+ for(outlength = 0; from < end;) {
int charsize;
unsigned int wc;
- wc = 0;
+ wc = 0;
switch(size) {
- case 4:
- wc = (wc << 8) | *(const unsigned char *) from++;
- wc = (wc << 8) | *(const unsigned char *) from++;
+ case 4:
+ wc = (wc << 8) | *(const unsigned char *) from++;
+ wc = (wc << 8) | *(const unsigned char *) from++;
/* FALLTHROUGH */
- case 2:
- wc = (wc << 8) | *(const unsigned char *) from++;
+ case 2:
+ wc = (wc << 8) | *(const unsigned char *) from++;
/* FALLTHROUGH */
- default: /* case 1: */
- wc = (wc << 8) | *(const unsigned char *) from++;
- }
+ default: /* case 1: */
+ wc = (wc << 8) | *(const unsigned char *) from++;
+ }
charsize = 1;
- if(wc >= 0x00000080) {
- if(wc >= 0x00000800) {
- if(wc >= 0x00010000) {
- if(wc >= 0x00200000) {
- free(buf);
- return -1; /* Invalid char. size for target encoding. */
- }
- buf[outlength + 3] = (char) (0x80 | (wc & 0x3F));
- wc = (wc >> 6) | 0x00010000;
+ if(wc >= 0x00000080) {
+ if(wc >= 0x00000800) {
+ if(wc >= 0x00010000) {
+ if(wc >= 0x00200000) {
+ free(buf);
+ return -1; /* Invalid char. size for target encoding. */
+ }
+ buf[outlength + 3] = (char) (0x80 | (wc & 0x3F));
+ wc = (wc >> 6) | 0x00010000;
charsize++;
- }
- buf[outlength + 2] = (char) (0x80 | (wc & 0x3F));
- wc = (wc >> 6) | 0x00000800;
+ }
+ buf[outlength + 2] = (char) (0x80 | (wc & 0x3F));
+ wc = (wc >> 6) | 0x00000800;
charsize++;
- }
- buf[outlength + 1] = (char) (0x80 | (wc & 0x3F));
- wc = (wc >> 6) | 0x000000C0;
+ }
+ buf[outlength + 1] = (char) (0x80 | (wc & 0x3F));
+ wc = (wc >> 6) | 0x000000C0;
charsize++;
- }
- buf[outlength] = (char) wc;
+ }
+ buf[outlength] = (char) wc;
outlength += charsize;
- }
- }
- buf[outlength] = '\0';
- *to = buf;
- return outlength;
-}
-
+ }
+ }
+ buf[outlength] = '\0';
+ *to = buf;
+ return outlength;
+}
+
/*
* Convert an ASN.1 String into its UTF-8 string representation.
* Return the dynamically allocated string, or NULL if an error occurs.
*/
static const char *string2str(int type, const char *beg, const char *end)
-{
+{
char *buf;
- if(utf8asn1str(&buf, type, beg, end) < 0)
+ if(utf8asn1str(&buf, type, beg, end) < 0)
return NULL;
- return buf;
-}
-
+ return buf;
+}
+
/*
* Decimal ASCII encode unsigned integer `x' into the buflen sized buffer at
* buf. Return the total number of encoded digits, even if larger than
* `buflen'.
*/
static size_t encodeUint(char *buf, size_t buflen, unsigned int x)
-{
+{
size_t i = 0;
- unsigned int y = x / 10;
-
- if(y) {
+ unsigned int y = x / 10;
+
+ if(y) {
i = encodeUint(buf, buflen, y);
- x -= y * 10;
- }
+ x -= y * 10;
+ }
if(i < buflen)
- buf[i] = (char) ('0' + x);
- i++;
+ buf[i] = (char) ('0' + x);
+ i++;
if(i < buflen)
- buf[i] = '\0'; /* Store a terminator if possible. */
- return i;
-}
-
+ buf[i] = '\0'; /* Store a terminator if possible. */
+ return i;
+}
+
/*
* Convert an ASN.1 OID into its dotted string representation.
* Store the result in th `n'-byte buffer at `buf'.
@@ -388,244 +388,244 @@ static size_t encodeUint(char *buf, size_t buflen, unsigned int x)
*/
static size_t encodeOID(char *buf, size_t buflen,
const char *beg, const char *end)
-{
+{
size_t i;
- unsigned int x;
- unsigned int y;
-
- /* Process the first two numbers. */
- y = *(const unsigned char *) beg++;
- x = y / 40;
- y -= x * 40;
+ unsigned int x;
+ unsigned int y;
+
+ /* Process the first two numbers. */
+ y = *(const unsigned char *) beg++;
+ x = y / 40;
+ y -= x * 40;
i = encodeUint(buf, buflen, x);
if(i < buflen)
- buf[i] = '.';
- i++;
+ buf[i] = '.';
+ i++;
if(i >= buflen)
i += encodeUint(NULL, 0, y);
else
i += encodeUint(buf + i, buflen - i, y);
-
- /* Process the trailing numbers. */
- while(beg < end) {
+
+ /* Process the trailing numbers. */
+ while(beg < end) {
if(i < buflen)
- buf[i] = '.';
- i++;
- x = 0;
- do {
- if(x & 0xFF000000)
+ buf[i] = '.';
+ i++;
+ x = 0;
+ do {
+ if(x & 0xFF000000)
return 0;
- y = *(const unsigned char *) beg++;
- x = (x << 7) | (y & 0x7F);
- } while(y & 0x80);
+ y = *(const unsigned char *) beg++;
+ x = (x << 7) | (y & 0x7F);
+ } while(y & 0x80);
if(i >= buflen)
i += encodeUint(NULL, 0, x);
else
i += encodeUint(buf + i, buflen - i, x);
- }
+ }
if(i < buflen)
- buf[i] = '\0';
- return i;
-}
-
+ buf[i] = '\0';
+ return i;
+}
+
/*
* Convert an ASN.1 OID into its dotted or symbolic string representation.
* Return the dynamically allocated string, or NULL if an error occurs.
*/
static const char *OID2str(const char *beg, const char *end, bool symbolic)
-{
+{
char *buf = NULL;
- if(beg < end) {
+ if(beg < end) {
size_t buflen = encodeOID(NULL, 0, beg, end);
if(buflen) {
buf = malloc(buflen + 1); /* one extra for the zero byte */
- if(buf) {
+ if(buf) {
encodeOID(buf, buflen, beg, end);
buf[buflen] = '\0';
-
- if(symbolic) {
+
+ if(symbolic) {
const struct Curl_OID *op = searchOID(buf);
- if(op) {
- free(buf);
- buf = strdup(op->textoid);
- }
- }
- }
- }
- }
- return buf;
-}
-
+ if(op) {
+ free(buf);
+ buf = strdup(op->textoid);
+ }
+ }
+ }
+ }
+ }
+ return buf;
+}
+
static const char *GTime2str(const char *beg, const char *end)
-{
+{
const char *tzp;
const char *fracp;
- char sec1, sec2;
- size_t fracl;
- size_t tzl;
+ char sec1, sec2;
+ size_t fracl;
+ size_t tzl;
const char *sep = "";
-
- /* Convert an ASN.1 Generalized time to a printable string.
- Return the dynamically allocated string, or NULL if an error occurs. */
-
- for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++)
- ;
-
- /* Get seconds digits. */
- sec1 = '0';
+
+ /* Convert an ASN.1 Generalized time to a printable string.
+ Return the dynamically allocated string, or NULL if an error occurs. */
+
+ for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++)
+ ;
+
+ /* Get seconds digits. */
+ sec1 = '0';
switch(fracp - beg - 12) {
- case 0:
- sec2 = '0';
- break;
- case 2:
- sec1 = fracp[-2];
+ case 0:
+ sec2 = '0';
+ break;
+ case 2:
+ sec1 = fracp[-2];
/* FALLTHROUGH */
- case 1:
- sec2 = fracp[-1];
- break;
- default:
+ case 1:
+ sec2 = fracp[-1];
+ break;
+ default:
return NULL;
- }
-
- /* Scan for timezone, measure fractional seconds. */
- tzp = fracp;
- fracl = 0;
- if(fracp < end && (*fracp == '.' || *fracp == ',')) {
- fracp++;
- do
- tzp++;
- while(tzp < end && *tzp >= '0' && *tzp <= '9');
- /* Strip leading zeroes in fractional seconds. */
- for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--)
- ;
- }
-
- /* Process timezone. */
- if(tzp >= end)
- ; /* Nothing to do. */
- else if(*tzp == 'Z') {
- tzp = " GMT";
- end = tzp + 4;
- }
- else {
- sep = " ";
- tzp++;
- }
-
- tzl = end - tzp;
- return curl_maprintf("%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s",
- beg, beg + 4, beg + 6,
- beg + 8, beg + 10, sec1, sec2,
- fracl? ".": "", fracl, fracp,
- sep, tzl, tzp);
-}
-
+ }
+
+ /* Scan for timezone, measure fractional seconds. */
+ tzp = fracp;
+ fracl = 0;
+ if(fracp < end && (*fracp == '.' || *fracp == ',')) {
+ fracp++;
+ do
+ tzp++;
+ while(tzp < end && *tzp >= '0' && *tzp <= '9');
+ /* Strip leading zeroes in fractional seconds. */
+ for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--)
+ ;
+ }
+
+ /* Process timezone. */
+ if(tzp >= end)
+ ; /* Nothing to do. */
+ else if(*tzp == 'Z') {
+ tzp = " GMT";
+ end = tzp + 4;
+ }
+ else {
+ sep = " ";
+ tzp++;
+ }
+
+ tzl = end - tzp;
+ return curl_maprintf("%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s",
+ beg, beg + 4, beg + 6,
+ beg + 8, beg + 10, sec1, sec2,
+ fracl? ".": "", fracl, fracp,
+ sep, tzl, tzp);
+}
+
/*
* Convert an ASN.1 UTC time to a printable string.
* Return the dynamically allocated string, or NULL if an error occurs.
*/
static const char *UTime2str(const char *beg, const char *end)
-{
+{
const char *tzp;
- size_t tzl;
+ size_t tzl;
const char *sec;
-
- for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++)
- ;
- /* Get the seconds. */
- sec = beg + 10;
+
+ for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++)
+ ;
+ /* Get the seconds. */
+ sec = beg + 10;
switch(tzp - sec) {
- case 0:
- sec = "00";
- case 2:
- break;
- default:
+ case 0:
+ sec = "00";
+ case 2:
+ break;
+ default:
return NULL;
- }
-
- /* Process timezone. */
- if(tzp >= end)
+ }
+
+ /* Process timezone. */
+ if(tzp >= end)
return NULL;
- if(*tzp == 'Z') {
- tzp = "GMT";
- end = tzp + 3;
- }
- else
- tzp++;
-
- tzl = end - tzp;
- return curl_maprintf("%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s",
- 20 - (*beg >= '5'), beg, beg + 2, beg + 4,
- beg + 6, beg + 8, sec,
- tzl, tzp);
-}
-
+ if(*tzp == 'Z') {
+ tzp = "GMT";
+ end = tzp + 3;
+ }
+ else
+ tzp++;
+
+ tzl = end - tzp;
+ return curl_maprintf("%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s",
+ 20 - (*beg >= '5'), beg, beg + 2, beg + 4,
+ beg + 6, beg + 8, sec,
+ tzl, tzp);
+}
+
/*
* Convert an ASN.1 element to a printable string.
* Return the dynamically allocated string, or NULL if an error occurs.
*/
static const char *ASN1tostr(struct Curl_asn1Element *elem, int type)
-{
- if(elem->constructed)
+{
+ if(elem->constructed)
return NULL; /* No conversion of structured elements. */
-
- if(!type)
- type = elem->tag; /* Type not forced: use element tag as type. */
-
+
+ if(!type)
+ type = elem->tag; /* Type not forced: use element tag as type. */
+
switch(type) {
- case CURL_ASN1_BOOLEAN:
- return bool2str(elem->beg, elem->end);
- case CURL_ASN1_INTEGER:
- case CURL_ASN1_ENUMERATED:
- return int2str(elem->beg, elem->end);
- case CURL_ASN1_BIT_STRING:
- return bit2str(elem->beg, elem->end);
- case CURL_ASN1_OCTET_STRING:
- return octet2str(elem->beg, elem->end);
- case CURL_ASN1_NULL:
+ case CURL_ASN1_BOOLEAN:
+ return bool2str(elem->beg, elem->end);
+ case CURL_ASN1_INTEGER:
+ case CURL_ASN1_ENUMERATED:
+ return int2str(elem->beg, elem->end);
+ case CURL_ASN1_BIT_STRING:
+ return bit2str(elem->beg, elem->end);
+ case CURL_ASN1_OCTET_STRING:
+ return octet2str(elem->beg, elem->end);
+ case CURL_ASN1_NULL:
return strdup("");
- case CURL_ASN1_OBJECT_IDENTIFIER:
- return OID2str(elem->beg, elem->end, TRUE);
- case CURL_ASN1_UTC_TIME:
- return UTime2str(elem->beg, elem->end);
- case CURL_ASN1_GENERALIZED_TIME:
- return GTime2str(elem->beg, elem->end);
- case CURL_ASN1_UTF8_STRING:
- case CURL_ASN1_NUMERIC_STRING:
- case CURL_ASN1_PRINTABLE_STRING:
- case CURL_ASN1_TELETEX_STRING:
- case CURL_ASN1_IA5_STRING:
- case CURL_ASN1_VISIBLE_STRING:
- case CURL_ASN1_UNIVERSAL_STRING:
- case CURL_ASN1_BMP_STRING:
- return string2str(type, elem->beg, elem->end);
- }
-
+ case CURL_ASN1_OBJECT_IDENTIFIER:
+ return OID2str(elem->beg, elem->end, TRUE);
+ case CURL_ASN1_UTC_TIME:
+ return UTime2str(elem->beg, elem->end);
+ case CURL_ASN1_GENERALIZED_TIME:
+ return GTime2str(elem->beg, elem->end);
+ case CURL_ASN1_UTF8_STRING:
+ case CURL_ASN1_NUMERIC_STRING:
+ case CURL_ASN1_PRINTABLE_STRING:
+ case CURL_ASN1_TELETEX_STRING:
+ case CURL_ASN1_IA5_STRING:
+ case CURL_ASN1_VISIBLE_STRING:
+ case CURL_ASN1_UNIVERSAL_STRING:
+ case CURL_ASN1_BMP_STRING:
+ return string2str(type, elem->beg, elem->end);
+ }
+
return NULL; /* Unsupported. */
-}
-
+}
+
/*
* ASCII encode distinguished name at `dn' into the `buflen'-sized buffer at
* `buf'. Return the total string length, even if larger than `buflen'.
*/
static ssize_t encodeDN(char *buf, size_t buflen, struct Curl_asn1Element *dn)
-{
+{
struct Curl_asn1Element rdn;
struct Curl_asn1Element atv;
struct Curl_asn1Element oid;
struct Curl_asn1Element value;
- size_t l = 0;
+ size_t l = 0;
const char *p1;
const char *p2;
const char *p3;
const char *str;
-
- for(p1 = dn->beg; p1 < dn->end;) {
+
+ for(p1 = dn->beg; p1 < dn->end;) {
p1 = getASN1Element(&rdn, p1, dn->end);
if(!p1)
return -1;
- for(p2 = rdn.beg; p2 < rdn.end;) {
+ for(p2 = rdn.beg; p2 < rdn.end;) {
p2 = getASN1Element(&atv, p2, rdn.end);
if(!p2)
return -1;
@@ -635,129 +635,129 @@ static ssize_t encodeDN(char *buf, size_t buflen, struct Curl_asn1Element *dn)
if(!getASN1Element(&value, p3, atv.end))
return -1;
str = ASN1tostr(&oid, 0);
- if(!str)
- return -1;
-
- /* Encode delimiter.
- If attribute has a short uppercase name, delimiter is ", ". */
- if(l) {
- for(p3 = str; isupper(*p3); p3++)
- ;
- for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) {
+ if(!str)
+ return -1;
+
+ /* Encode delimiter.
+ If attribute has a short uppercase name, delimiter is ", ". */
+ if(l) {
+ for(p3 = str; isupper(*p3); p3++)
+ ;
+ for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) {
if(l < buflen)
- buf[l] = *p3;
- l++;
- }
- }
-
- /* Encode attribute name. */
- for(p3 = str; *p3; p3++) {
+ buf[l] = *p3;
+ l++;
+ }
+ }
+
+ /* Encode attribute name. */
+ for(p3 = str; *p3; p3++) {
if(l < buflen)
- buf[l] = *p3;
- l++;
- }
- free((char *) str);
-
- /* Generate equal sign. */
+ buf[l] = *p3;
+ l++;
+ }
+ free((char *) str);
+
+ /* Generate equal sign. */
if(l < buflen)
- buf[l] = '=';
- l++;
-
- /* Generate value. */
+ buf[l] = '=';
+ l++;
+
+ /* Generate value. */
str = ASN1tostr(&value, 0);
- if(!str)
- return -1;
- for(p3 = str; *p3; p3++) {
+ if(!str)
+ return -1;
+ for(p3 = str; *p3; p3++) {
if(l < buflen)
- buf[l] = *p3;
- l++;
- }
- free((char *) str);
- }
- }
-
- return l;
-}
-
+ buf[l] = *p3;
+ l++;
+ }
+ free((char *) str);
+ }
+ }
+
+ return l;
+}
+
/*
* Convert an ASN.1 distinguished name into a printable string.
* Return the dynamically allocated string, or NULL if an error occurs.
*/
static const char *DNtostr(struct Curl_asn1Element *dn)
-{
+{
char *buf = NULL;
ssize_t buflen = encodeDN(NULL, 0, dn);
-
+
if(buflen >= 0) {
buf = malloc(buflen + 1);
- if(buf) {
+ if(buf) {
encodeDN(buf, buflen + 1, dn);
buf[buflen] = '\0';
- }
- }
+ }
+ }
return buf;
-}
-
-/*
+}
+
+/*
* ASN.1 parse an X509 certificate into structure subfields.
* Syntax is assumed to have already been checked by the SSL backend.
* See RFC 5280.
- */
+ */
int Curl_parseX509(struct Curl_X509certificate *cert,
const char *beg, const char *end)
-{
+{
struct Curl_asn1Element elem;
struct Curl_asn1Element tbsCertificate;
const char *ccp;
- static const char defaultVersion = 0; /* v1. */
-
+ static const char defaultVersion = 0; /* v1. */
+
cert->certificate.header = NULL;
- cert->certificate.beg = beg;
- cert->certificate.end = end;
-
- /* Get the sequence content. */
+ cert->certificate.beg = beg;
+ cert->certificate.end = end;
+
+ /* Get the sequence content. */
if(!getASN1Element(&elem, beg, end))
return -1; /* Invalid bounds/size. */
- beg = elem.beg;
- end = elem.end;
-
- /* Get tbsCertificate. */
+ beg = elem.beg;
+ end = elem.end;
+
+ /* Get tbsCertificate. */
beg = getASN1Element(&tbsCertificate, beg, end);
if(!beg)
return -1;
- /* Skip the signatureAlgorithm. */
+ /* Skip the signatureAlgorithm. */
beg = getASN1Element(&cert->signatureAlgorithm, beg, end);
if(!beg)
return -1;
- /* Get the signatureValue. */
+ /* Get the signatureValue. */
if(!getASN1Element(&cert->signature, beg, end))
return -1;
-
- /* Parse TBSCertificate. */
- beg = tbsCertificate.beg;
- end = tbsCertificate.end;
- /* Get optional version, get serialNumber. */
+
+ /* Parse TBSCertificate. */
+ beg = tbsCertificate.beg;
+ end = tbsCertificate.end;
+ /* Get optional version, get serialNumber. */
cert->version.header = NULL;
- cert->version.beg = &defaultVersion;
+ cert->version.beg = &defaultVersion;
cert->version.end = &defaultVersion + sizeof(defaultVersion);
beg = getASN1Element(&elem, beg, end);
if(!beg)
return -1;
- if(elem.tag == 0) {
+ if(elem.tag == 0) {
if(!getASN1Element(&cert->version, elem.beg, elem.end))
return -1;
beg = getASN1Element(&elem, beg, end);
if(!beg)
return -1;
- }
- cert->serialNumber = elem;
- /* Get signature algorithm. */
+ }
+ cert->serialNumber = elem;
+ /* Get signature algorithm. */
beg = getASN1Element(&cert->signatureAlgorithm, beg, end);
- /* Get issuer. */
+ /* Get issuer. */
beg = getASN1Element(&cert->issuer, beg, end);
if(!beg)
return -1;
- /* Get notBefore and notAfter. */
+ /* Get notBefore and notAfter. */
beg = getASN1Element(&elem, beg, end);
if(!beg)
return -1;
@@ -766,11 +766,11 @@ int Curl_parseX509(struct Curl_X509certificate *cert,
return -1;
if(!getASN1Element(&cert->notAfter, ccp, elem.end))
return -1;
- /* Get subject. */
+ /* Get subject. */
beg = getASN1Element(&cert->subject, beg, end);
if(!beg)
return -1;
- /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
+ /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */
beg = getASN1Element(&cert->subjectPublicKeyInfo, beg, end);
if(!beg)
return -1;
@@ -782,109 +782,109 @@ int Curl_parseX509(struct Curl_X509certificate *cert,
if(!getASN1Element(&cert->subjectPublicKey, ccp,
cert->subjectPublicKeyInfo.end))
return -1;
- /* Get optional issuerUiqueID, subjectUniqueID and extensions. */
- cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0;
- cert->extensions.tag = elem.tag = 0;
+ /* Get optional issuerUiqueID, subjectUniqueID and extensions. */
+ cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0;
+ cert->extensions.tag = elem.tag = 0;
cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL;
- cert->issuerUniqueID.beg = cert->issuerUniqueID.end = "";
- cert->subjectUniqueID.beg = cert->subjectUniqueID.end = "";
+ cert->issuerUniqueID.beg = cert->issuerUniqueID.end = "";
+ cert->subjectUniqueID.beg = cert->subjectUniqueID.end = "";
cert->extensions.header = NULL;
- cert->extensions.beg = cert->extensions.end = "";
+ cert->extensions.beg = cert->extensions.end = "";
if(beg < end) {
beg = getASN1Element(&elem, beg, end);
if(!beg)
return -1;
}
- if(elem.tag == 1) {
- cert->issuerUniqueID = elem;
+ if(elem.tag == 1) {
+ cert->issuerUniqueID = elem;
if(beg < end) {
beg = getASN1Element(&elem, beg, end);
if(!beg)
return -1;
}
- }
- if(elem.tag == 2) {
- cert->subjectUniqueID = elem;
+ }
+ if(elem.tag == 2) {
+ cert->subjectUniqueID = elem;
if(beg < end) {
beg = getASN1Element(&elem, beg, end);
if(!beg)
return -1;
}
- }
- if(elem.tag == 3)
+ }
+ if(elem.tag == 3)
if(!getASN1Element(&cert->extensions, elem.beg, elem.end))
return -1;
return 0;
-}
-
+}
+
/*
* Copy at most 64-characters, terminate with a newline and returns the
* effective number of stored characters.
*/
static size_t copySubstring(char *to, const char *from)
-{
- size_t i;
- for(i = 0; i < 64; i++) {
- to[i] = *from;
- if(!*from++)
- break;
- }
-
- to[i++] = '\n';
- return i;
-}
-
+{
+ size_t i;
+ for(i = 0; i < 64; i++) {
+ to[i] = *from;
+ if(!*from++)
+ break;
+ }
+
+ to[i++] = '\n';
+ return i;
+}
+
static const char *dumpAlgo(struct Curl_asn1Element *param,
const char *beg, const char *end)
-{
+{
struct Curl_asn1Element oid;
-
- /* Get algorithm parameters and return algorithm name. */
-
+
+ /* Get algorithm parameters and return algorithm name. */
+
beg = getASN1Element(&oid, beg, end);
if(!beg)
return NULL;
param->header = NULL;
- param->tag = 0;
- param->beg = param->end = end;
- if(beg < end)
+ param->tag = 0;
+ param->beg = param->end = end;
+ if(beg < end)
if(!getASN1Element(param, beg, end))
return NULL;
- return OID2str(oid.beg, oid.end, TRUE);
-}
-
+ return OID2str(oid.beg, oid.end, TRUE);
+}
+
static void do_pubkey_field(struct Curl_easy *data, int certnum,
const char *label, struct Curl_asn1Element *elem)
-{
+{
const char *output;
-
- /* Generate a certificate information record for the public key. */
-
+
+ /* Generate a certificate information record for the public key. */
+
output = ASN1tostr(elem, 0);
- if(output) {
+ if(output) {
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, label, output);
if(!certnum)
infof(data, " %s: %s\n", label, output);
- free((char *) output);
- }
-}
-
+ free((char *) output);
+ }
+}
+
static void do_pubkey(struct Curl_easy *data, int certnum,
const char *algo, struct Curl_asn1Element *param,
struct Curl_asn1Element *pubkey)
-{
+{
struct Curl_asn1Element elem;
struct Curl_asn1Element pk;
const char *p;
-
- /* Generate all information records for the public key. */
-
- /* Get the public key (single element). */
+
+ /* Generate all information records for the public key. */
+
+ /* Get the public key (single element). */
if(!getASN1Element(&pk, pubkey->beg + 1, pubkey->end))
return;
-
+
if(strcasecompare(algo, "rsaEncryption")) {
const char *q;
unsigned long len;
@@ -893,17 +893,17 @@ static void do_pubkey(struct Curl_easy *data, int certnum,
if(!p)
return;
- /* Compute key length. */
- for(q = elem.beg; !*q && q < elem.end; q++)
- ;
+ /* Compute key length. */
+ for(q = elem.beg; !*q && q < elem.end; q++)
+ ;
len = (unsigned long)((elem.end - q) * 8);
if(len) {
unsigned int i;
- for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
- len--;
+ for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1)
+ len--;
}
- if(len > 32)
- elem.beg = q; /* Strip leading zero bytes. */
+ if(len > 32)
+ elem.beg = q; /* Strip leading zero bytes. */
if(!certnum)
infof(data, " RSA Public Key (%lu bits)\n", len);
if(data->set.ssl.certinfo) {
@@ -912,13 +912,13 @@ static void do_pubkey(struct Curl_easy *data, int certnum,
Curl_ssl_push_certinfo(data, certnum, "RSA Public Key", q);
free((char *) q);
}
- }
- /* Generate coefficients. */
- do_pubkey_field(data, certnum, "rsa(n)", &elem);
+ }
+ /* Generate coefficients. */
+ do_pubkey_field(data, certnum, "rsa(n)", &elem);
if(!getASN1Element(&elem, p, pk.end))
return;
- do_pubkey_field(data, certnum, "rsa(e)", &elem);
- }
+ do_pubkey_field(data, certnum, "rsa(e)", &elem);
+ }
else if(strcasecompare(algo, "dsa")) {
p = getASN1Element(&elem, param->beg, param->end);
if(p) {
@@ -932,7 +932,7 @@ static void do_pubkey(struct Curl_easy *data, int certnum,
}
}
}
- }
+ }
else if(strcasecompare(algo, "dhpublicnumber")) {
p = getASN1Element(&elem, param->beg, param->end);
if(p) {
@@ -942,60 +942,60 @@ static void do_pubkey(struct Curl_easy *data, int certnum,
do_pubkey_field(data, certnum, "dh(pub_key)", &pk);
}
}
- }
-}
-
+ }
+}
+
CURLcode Curl_extract_certinfo(struct connectdata *conn,
- int certnum,
+ int certnum,
const char *beg,
const char *end)
-{
+{
struct Curl_X509certificate cert;
struct Curl_easy *data = conn->data;
struct Curl_asn1Element param;
const char *ccp;
char *cp1;
- size_t cl1;
+ size_t cl1;
char *cp2;
CURLcode result;
- unsigned long version;
- size_t i;
- size_t j;
-
+ unsigned long version;
+ size_t i;
+ size_t j;
+
if(!data->set.ssl.certinfo)
if(certnum)
return CURLE_OK;
- /* Prepare the certificate information for curl_easy_getinfo(). */
-
- /* Extract the certificate ASN.1 elements. */
+ /* Prepare the certificate information for curl_easy_getinfo(). */
+
+ /* Extract the certificate ASN.1 elements. */
if(Curl_parseX509(&cert, beg, end))
return CURLE_PEER_FAILED_VERIFICATION;
-
- /* Subject. */
+
+ /* Subject. */
ccp = DNtostr(&cert.subject);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Subject", ccp);
if(!certnum)
infof(data, "%2d Subject: %s\n", certnum, ccp);
- free((char *) ccp);
-
- /* Issuer. */
+ free((char *) ccp);
+
+ /* Issuer. */
ccp = DNtostr(&cert.issuer);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp);
if(!certnum)
infof(data, " Issuer: %s\n", ccp);
- free((char *) ccp);
-
- /* Version (always fits in less than 32 bits). */
- version = 0;
- for(ccp = cert.version.beg; ccp < cert.version.end; ccp++)
- version = (version << 8) | *(const unsigned char *) ccp;
+ free((char *) ccp);
+
+ /* Version (always fits in less than 32 bits). */
+ version = 0;
+ for(ccp = cert.version.beg; ccp < cert.version.end; ccp++)
+ version = (version << 8) | *(const unsigned char *) ccp;
if(data->set.ssl.certinfo) {
ccp = curl_maprintf("%lx", version);
if(!ccp)
@@ -1005,112 +1005,112 @@ CURLcode Curl_extract_certinfo(struct connectdata *conn,
}
if(!certnum)
infof(data, " Version: %lu (0x%lx)\n", version + 1, version);
-
- /* Serial number. */
+
+ /* Serial number. */
ccp = ASN1tostr(&cert.serialNumber, 0);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp);
if(!certnum)
infof(data, " Serial Number: %s\n", ccp);
- free((char *) ccp);
-
- /* Signature algorithm .*/
- ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg,
- cert.signatureAlgorithm.end);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ free((char *) ccp);
+
+ /* Signature algorithm .*/
+ ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg,
+ cert.signatureAlgorithm.end);
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp);
if(!certnum)
infof(data, " Signature Algorithm: %s\n", ccp);
- free((char *) ccp);
-
- /* Start Date. */
+ free((char *) ccp);
+
+ /* Start Date. */
ccp = ASN1tostr(&cert.notBefore, 0);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp);
if(!certnum)
infof(data, " Start Date: %s\n", ccp);
- free((char *) ccp);
-
- /* Expire Date. */
+ free((char *) ccp);
+
+ /* Expire Date. */
ccp = ASN1tostr(&cert.notAfter, 0);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp);
if(!certnum)
infof(data, " Expire Date: %s\n", ccp);
- free((char *) ccp);
-
- /* Public Key Algorithm. */
- ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg,
- cert.subjectPublicKeyAlgorithm.end);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ free((char *) ccp);
+
+ /* Public Key Algorithm. */
+ ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg,
+ cert.subjectPublicKeyAlgorithm.end);
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm", ccp);
if(!certnum)
infof(data, " Public Key Algorithm: %s\n", ccp);
- do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey);
- free((char *) ccp);
-
- /* Signature. */
+ do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey);
+ free((char *) ccp);
+
+ /* Signature. */
ccp = ASN1tostr(&cert.signature, 0);
- if(!ccp)
- return CURLE_OUT_OF_MEMORY;
+ if(!ccp)
+ return CURLE_OUT_OF_MEMORY;
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Signature", ccp);
if(!certnum)
infof(data, " Signature: %s\n", ccp);
- free((char *) ccp);
-
- /* Generate PEM certificate. */
+ free((char *) ccp);
+
+ /* Generate PEM certificate. */
result = Curl_base64_encode(data, cert.certificate.beg,
cert.certificate.end - cert.certificate.beg,
&cp1, &cl1);
if(result)
return result;
/* Compute the number of characters in final certificate string. Format is:
- -----BEGIN CERTIFICATE-----\n
- <max 64 base64 characters>\n
- .
- .
- .
- -----END CERTIFICATE-----\n
- */
- i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26;
- cp2 = malloc(i + 1);
- if(!cp2) {
- free(cp1);
- return CURLE_OUT_OF_MEMORY;
- }
- /* Build the certificate string. */
- i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----");
- for(j = 0; j < cl1; j += 64)
- i += copySubstring(cp2 + i, cp1 + j);
- i += copySubstring(cp2 + i, "-----END CERTIFICATE-----");
- cp2[i] = '\0';
- free(cp1);
+ -----BEGIN CERTIFICATE-----\n
+ <max 64 base64 characters>\n
+ .
+ .
+ .
+ -----END CERTIFICATE-----\n
+ */
+ i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26;
+ cp2 = malloc(i + 1);
+ if(!cp2) {
+ free(cp1);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ /* Build the certificate string. */
+ i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----");
+ for(j = 0; j < cl1; j += 64)
+ i += copySubstring(cp2 + i, cp1 + j);
+ i += copySubstring(cp2 + i, "-----END CERTIFICATE-----");
+ cp2[i] = '\0';
+ free(cp1);
if(data->set.ssl.certinfo)
Curl_ssl_push_certinfo(data, certnum, "Cert", cp2);
if(!certnum)
infof(data, "%s\n", cp2);
- free(cp2);
- return CURLE_OK;
-}
-
+ free(cp2);
+ return CURLE_OK;
+}
+
#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL */
-
+
#if defined(USE_GSKIT)
static const char *checkOID(const char *beg, const char *end,
const char *oid)
-{
+{
struct Curl_asn1Element e;
const char *ccp;
const char *p;
@@ -1144,139 +1144,139 @@ CURLcode Curl_verifyhost(struct connectdata *conn,
const char *p;
const char *q;
char *dnsname;
- int matched = -1;
- size_t addrlen = (size_t) -1;
- ssize_t len;
+ int matched = -1;
+ size_t addrlen = (size_t) -1;
+ ssize_t len;
const char *const hostname = SSL_IS_PROXY()?
conn->http_proxy.host.name : conn->host.name;
const char *const dispname = SSL_IS_PROXY()?
conn->http_proxy.host.dispname : conn->host.dispname;
-#ifdef ENABLE_IPV6
- struct in6_addr addr;
-#else
- struct in_addr addr;
-#endif
-
- /* Verify that connection server matches info in X509 certificate at
- `beg'..`end'. */
-
+#ifdef ENABLE_IPV6
+ struct in6_addr addr;
+#else
+ struct in_addr addr;
+#endif
+
+ /* Verify that connection server matches info in X509 certificate at
+ `beg'..`end'. */
+
if(!SSL_CONN_CONFIG(verifyhost))
- return CURLE_OK;
-
+ return CURLE_OK;
+
if(Curl_parseX509(&cert, beg, end))
- return CURLE_PEER_FAILED_VERIFICATION;
-
- /* Get the server IP address. */
-#ifdef ENABLE_IPV6
+ return CURLE_PEER_FAILED_VERIFICATION;
+
+ /* Get the server IP address. */
+#ifdef ENABLE_IPV6
if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, hostname, &addr))
- addrlen = sizeof(struct in6_addr);
- else
-#endif
+ addrlen = sizeof(struct in6_addr);
+ else
+#endif
if(Curl_inet_pton(AF_INET, hostname, &addr))
- addrlen = sizeof(struct in_addr);
-
- /* Process extensions. */
- for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) {
+ addrlen = sizeof(struct in_addr);
+
+ /* Process extensions. */
+ for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) {
p = getASN1Element(&ext, p, cert.extensions.end);
if(!p)
return CURLE_PEER_FAILED_VERIFICATION;
- /* Check if extension is a subjectAlternativeName. */
- ext.beg = checkOID(ext.beg, ext.end, sanOID);
- if(ext.beg) {
+ /* Check if extension is a subjectAlternativeName. */
+ ext.beg = checkOID(ext.beg, ext.end, sanOID);
+ if(ext.beg) {
ext.beg = getASN1Element(&elem, ext.beg, ext.end);
if(!ext.beg)
return CURLE_PEER_FAILED_VERIFICATION;
- /* Skip critical if present. */
+ /* Skip critical if present. */
if(elem.tag == CURL_ASN1_BOOLEAN) {
ext.beg = getASN1Element(&elem, ext.beg, ext.end);
if(!ext.beg)
return CURLE_PEER_FAILED_VERIFICATION;
}
- /* Parse the octet string contents: is a single sequence. */
+ /* Parse the octet string contents: is a single sequence. */
if(!getASN1Element(&elem, elem.beg, elem.end))
return CURLE_PEER_FAILED_VERIFICATION;
- /* Check all GeneralNames. */
- for(q = elem.beg; matched != 1 && q < elem.end;) {
+ /* Check all GeneralNames. */
+ for(q = elem.beg; matched != 1 && q < elem.end;) {
q = getASN1Element(&name, q, elem.end);
if(!q)
break;
switch(name.tag) {
- case 2: /* DNS name. */
- len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING,
- name.beg, name.end);
+ case 2: /* DNS name. */
+ len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING,
+ name.beg, name.end);
if(len > 0 && (size_t)len == strlen(dnsname))
matched = Curl_cert_hostcheck(dnsname, hostname);
else
matched = 0;
free(dnsname);
- break;
-
- case 7: /* IP address. */
+ break;
+
+ case 7: /* IP address. */
matched = (size_t) (name.end - name.beg) == addrlen &&
!memcmp(&addr, name.beg, addrlen);
- break;
- }
- }
- }
- }
-
+ break;
+ }
+ }
+ }
+ }
+
switch(matched) {
- case 1:
- /* an alternative name matched the server hostname */
+ case 1:
+ /* an alternative name matched the server hostname */
infof(data, "\t subjectAltName: %s matched\n", dispname);
- return CURLE_OK;
- case 0:
- /* an alternative name field existed, but didn't match and then
- we MUST fail */
+ return CURLE_OK;
+ case 0:
+ /* an alternative name field existed, but didn't match and then
+ we MUST fail */
infof(data, "\t subjectAltName does not match %s\n", dispname);
- return CURLE_PEER_FAILED_VERIFICATION;
- }
-
- /* Process subject. */
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+
+ /* Process subject. */
name.header = NULL;
- name.beg = name.end = "";
- q = cert.subject.beg;
- /* we have to look to the last occurrence of a commonName in the
- distinguished one to get the most significant one. */
- while(q < cert.subject.end) {
+ name.beg = name.end = "";
+ q = cert.subject.beg;
+ /* we have to look to the last occurrence of a commonName in the
+ distinguished one to get the most significant one. */
+ while(q < cert.subject.end) {
q = getASN1Element(&dn, q, cert.subject.end);
if(!q)
break;
- for(p = dn.beg; p < dn.end;) {
+ for(p = dn.beg; p < dn.end;) {
p = getASN1Element(&elem, p, dn.end);
if(!p)
return CURLE_PEER_FAILED_VERIFICATION;
- /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */
- elem.beg = checkOID(elem.beg, elem.end, cnOID);
- if(elem.beg)
- name = elem; /* Latch CN. */
- }
- }
-
- /* Check the CN if found. */
+ /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */
+ elem.beg = checkOID(elem.beg, elem.end, cnOID);
+ if(elem.beg)
+ name = elem; /* Latch CN. */
+ }
+ }
+
+ /* Check the CN if found. */
if(!getASN1Element(&elem, name.beg, name.end))
- failf(data, "SSL: unable to obtain common name from peer certificate");
- else {
- len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end);
- if(len < 0) {
- free(dnsname);
- return CURLE_OUT_OF_MEMORY;
- }
- if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */
- failf(data, "SSL: illegal cert name field");
+ failf(data, "SSL: unable to obtain common name from peer certificate");
+ else {
+ len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end);
+ if(len < 0) {
+ free(dnsname);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */
+ failf(data, "SSL: illegal cert name field");
else if(Curl_cert_hostcheck((const char *) dnsname, hostname)) {
- infof(data, "\t common name: %s (matched)\n", dnsname);
- free(dnsname);
- return CURLE_OK;
- }
- else
- failf(data, "SSL: certificate subject name '%s' does not match "
+ infof(data, "\t common name: %s (matched)\n", dnsname);
+ free(dnsname);
+ return CURLE_OK;
+ }
+ else
+ failf(data, "SSL: certificate subject name '%s' does not match "
"target host name '%s'", dnsname, dispname);
- free(dnsname);
- }
-
- return CURLE_PEER_FAILED_VERIFICATION;
-}
-
+ free(dnsname);
+ }
+
+ return CURLE_PEER_FAILED_VERIFICATION;
+}
+
#endif /* USE_GSKIT */
diff --git a/contrib/libs/curl/lib/x509asn1.h b/contrib/libs/curl/lib/x509asn1.h
index c507caa159..849714492d 100644
--- a/contrib/libs/curl/lib/x509asn1.h
+++ b/contrib/libs/curl/lib/x509asn1.h
@@ -1,84 +1,84 @@
-#ifndef HEADER_CURL_X509ASN1_H
-#define HEADER_CURL_X509ASN1_H
-
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
+#ifndef HEADER_CURL_X509ASN1_H
+#define HEADER_CURL_X509ASN1_H
+
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
* Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
#if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \
defined(USE_WOLFSSL) || defined(USE_SCHANNEL)
-
-#include "urldata.h"
-
-/*
- * Constants.
- */
-
+
+#include "urldata.h"
+
+/*
+ * Constants.
+ */
+
/* Largest supported ASN.1 structure. */
#define CURL_ASN1_MAX ((size_t) 0x40000) /* 256K */
-/* ASN.1 classes. */
-#define CURL_ASN1_UNIVERSAL 0
-#define CURL_ASN1_APPLICATION 1
-#define CURL_ASN1_CONTEXT_SPECIFIC 2
-#define CURL_ASN1_PRIVATE 3
-
-/* ASN.1 types. */
-#define CURL_ASN1_BOOLEAN 1
-#define CURL_ASN1_INTEGER 2
-#define CURL_ASN1_BIT_STRING 3
-#define CURL_ASN1_OCTET_STRING 4
-#define CURL_ASN1_NULL 5
-#define CURL_ASN1_OBJECT_IDENTIFIER 6
-#define CURL_ASN1_OBJECT_DESCRIPTOR 7
-#define CURL_ASN1_INSTANCE_OF 8
-#define CURL_ASN1_REAL 9
-#define CURL_ASN1_ENUMERATED 10
-#define CURL_ASN1_EMBEDDED 11
-#define CURL_ASN1_UTF8_STRING 12
-#define CURL_ASN1_RELATIVE_OID 13
-#define CURL_ASN1_SEQUENCE 16
-#define CURL_ASN1_SET 17
-#define CURL_ASN1_NUMERIC_STRING 18
-#define CURL_ASN1_PRINTABLE_STRING 19
-#define CURL_ASN1_TELETEX_STRING 20
-#define CURL_ASN1_VIDEOTEX_STRING 21
-#define CURL_ASN1_IA5_STRING 22
-#define CURL_ASN1_UTC_TIME 23
-#define CURL_ASN1_GENERALIZED_TIME 24
-#define CURL_ASN1_GRAPHIC_STRING 25
-#define CURL_ASN1_VISIBLE_STRING 26
-#define CURL_ASN1_GENERAL_STRING 27
-#define CURL_ASN1_UNIVERSAL_STRING 28
-#define CURL_ASN1_CHARACTER_STRING 29
-#define CURL_ASN1_BMP_STRING 30
-
-
-/*
- * Types.
- */
-
-/* ASN.1 parsed element. */
+/* ASN.1 classes. */
+#define CURL_ASN1_UNIVERSAL 0
+#define CURL_ASN1_APPLICATION 1
+#define CURL_ASN1_CONTEXT_SPECIFIC 2
+#define CURL_ASN1_PRIVATE 3
+
+/* ASN.1 types. */
+#define CURL_ASN1_BOOLEAN 1
+#define CURL_ASN1_INTEGER 2
+#define CURL_ASN1_BIT_STRING 3
+#define CURL_ASN1_OCTET_STRING 4
+#define CURL_ASN1_NULL 5
+#define CURL_ASN1_OBJECT_IDENTIFIER 6
+#define CURL_ASN1_OBJECT_DESCRIPTOR 7
+#define CURL_ASN1_INSTANCE_OF 8
+#define CURL_ASN1_REAL 9
+#define CURL_ASN1_ENUMERATED 10
+#define CURL_ASN1_EMBEDDED 11
+#define CURL_ASN1_UTF8_STRING 12
+#define CURL_ASN1_RELATIVE_OID 13
+#define CURL_ASN1_SEQUENCE 16
+#define CURL_ASN1_SET 17
+#define CURL_ASN1_NUMERIC_STRING 18
+#define CURL_ASN1_PRINTABLE_STRING 19
+#define CURL_ASN1_TELETEX_STRING 20
+#define CURL_ASN1_VIDEOTEX_STRING 21
+#define CURL_ASN1_IA5_STRING 22
+#define CURL_ASN1_UTC_TIME 23
+#define CURL_ASN1_GENERALIZED_TIME 24
+#define CURL_ASN1_GRAPHIC_STRING 25
+#define CURL_ASN1_VISIBLE_STRING 26
+#define CURL_ASN1_GENERAL_STRING 27
+#define CURL_ASN1_UNIVERSAL_STRING 28
+#define CURL_ASN1_CHARACTER_STRING 29
+#define CURL_ASN1_BMP_STRING 30
+
+
+/*
+ * Types.
+ */
+
+/* ASN.1 parsed element. */
struct Curl_asn1Element {
const char *header; /* Pointer to header byte. */
const char *beg; /* Pointer to element data. */
@@ -87,16 +87,16 @@ struct Curl_asn1Element {
unsigned char tag; /* ASN.1 element tag. */
bool constructed; /* Element is constructed. */
};
-
-
-/* ASN.1 OID table entry. */
+
+
+/* ASN.1 OID table entry. */
struct Curl_OID {
const char *numoid; /* Dotted-numeric OID. */
const char *textoid; /* OID name. */
};
-
-
-/* X509 certificate: RFC 5280. */
+
+
+/* X509 certificate: RFC 5280. */
struct Curl_X509certificate {
struct Curl_asn1Element certificate;
struct Curl_asn1Element version;
@@ -114,11 +114,11 @@ struct Curl_X509certificate {
struct Curl_asn1Element subjectUniqueID;
struct Curl_asn1Element extensions;
};
-
-/*
- * Prototypes.
- */
-
+
+/*
+ * Prototypes.
+ */
+
const char *Curl_getASN1Element(struct Curl_asn1Element *elem,
const char *beg, const char *end);
const char *Curl_ASN1tostr(struct Curl_asn1Element *elem, int type);
@@ -130,4 +130,4 @@ CURLcode Curl_extract_certinfo(struct connectdata *conn, int certnum,
CURLcode Curl_verifyhost(struct connectdata *conn,
const char *beg, const char *end);
#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL */
-#endif /* HEADER_CURL_X509ASN1_H */
+#endif /* HEADER_CURL_X509ASN1_H */
diff --git a/contrib/libs/curl/ya.make b/contrib/libs/curl/ya.make
index a8494ec631..00027df424 100644
--- a/contrib/libs/curl/ya.make
+++ b/contrib/libs/curl/ya.make
@@ -1,14 +1,14 @@
# Generated by devtools/yamaker from nixpkgs 980c4c3c2f664ccc5002f7fd6e08059cf1f00e75.
-LIBRARY()
-
+LIBRARY()
+
OWNER(
g:cpp-contrib
g:geoapps_infra
)
-
+
VERSION(7.74.0)
-
+
ORIGINAL_SOURCE(https://curl.haxx.se/download/curl-7.74.0.tar.bz2)
LICENSE(
@@ -24,14 +24,14 @@ PEERDIR(
contrib/libs/libc_compat
contrib/libs/openssl
contrib/libs/zlib
-)
-
-ADDINCL(
+)
+
+ADDINCL(
GLOBAL contrib/libs/curl/include
contrib/libs/c-ares
contrib/libs/curl/lib
-)
-
+)
+
IF (NOT OS_WINDOWS)
PEERDIR(
contrib/libs/nghttp2
@@ -64,16 +64,16 @@ IF (ARCADIA_CURL_DNS_RESOLVER == ARES)
)
ENDIF()
-SRCS(
+SRCS(
lib/altsvc.c
lib/amigaos.c
lib/asyn-ares.c
lib/asyn-thread.c
- lib/base64.c
+ lib/base64.c
lib/conncache.c
lib/connect.c
lib/content_encoding.c
- lib/cookie.c
+ lib/cookie.c
lib/curl_addrinfo.c
lib/curl_ctype.c
lib/curl_des.c
@@ -92,30 +92,30 @@ SRCS(
lib/curl_sasl.c
lib/curl_sspi.c
lib/curl_threads.c
- lib/dict.c
+ lib/dict.c
lib/doh.c
lib/dotdot.c
lib/dynbuf.c
lib/easy.c
lib/easygetopt.c
lib/easyoptions.c
- lib/escape.c
+ lib/escape.c
lib/file.c
- lib/fileinfo.c
+ lib/fileinfo.c
lib/formdata.c
lib/ftp.c
- lib/ftplistparser.c
+ lib/ftplistparser.c
lib/getenv.c
lib/getinfo.c
lib/gopher.c
- lib/hash.c
+ lib/hash.c
lib/hmac.c
- lib/hostasyn.c
+ lib/hostasyn.c
lib/hostcheck.c
lib/hostip.c
- lib/hostip4.c
- lib/hostip6.c
- lib/hostsyn.c
+ lib/hostip4.c
+ lib/hostip6.c
+ lib/hostsyn.c
lib/hsts.c
lib/http.c
lib/http2.c
@@ -127,7 +127,7 @@ SRCS(
lib/idn_win32.c
lib/if2ip.c
lib/imap.c
- lib/inet_ntop.c
+ lib/inet_ntop.c
lib/inet_pton.c
lib/krb5.c
lib/ldap.c
@@ -143,7 +143,7 @@ SRCS(
lib/non-ascii.c
lib/nonblock.c
lib/openldap.c
- lib/parsedate.c
+ lib/parsedate.c
lib/pingpong.c
lib/pop3.c
lib/progress.c
@@ -151,7 +151,7 @@ SRCS(
lib/rand.c
lib/rename.c
lib/rtsp.c
- lib/select.c
+ lib/select.c
lib/sendf.c
lib/setopt.c
lib/sha256.c
@@ -160,9 +160,9 @@ SRCS(
lib/smb.c
lib/smtp.c
lib/socketpair.c
- lib/socks.c
- lib/socks_gssapi.c
- lib/socks_sspi.c
+ lib/socks.c
+ lib/socks_gssapi.c
+ lib/socks_sspi.c
lib/speedcheck.c
lib/splay.c
lib/strcase.c
@@ -204,9 +204,9 @@ SRCS(
lib/vtls/sectransp.c
lib/vtls/vtls.c
lib/vtls/wolfssl.c
- lib/warnless.c
+ lib/warnless.c
lib/wildcard.c
- lib/x509asn1.c
-)
-
-END()
+ lib/x509asn1.c
+)
+
+END()
diff --git a/contrib/libs/jemalloc/src/zone.c b/contrib/libs/jemalloc/src/zone.c
index 9caa125fc6..23dfdd04a9 100644
--- a/contrib/libs/jemalloc/src/zone.c
+++ b/contrib/libs/jemalloc/src/zone.c
@@ -368,34 +368,34 @@ zone_init(void) {
static malloc_zone_t *
zone_default_get(void) {
- malloc_zone_t **zones = NULL;
- unsigned int num_zones = 0;
-
- /*
- * On OSX 10.12, malloc_default_zone returns a special zone that is not
- * present in the list of registered zones. That zone uses a "lite zone"
- * if one is present (apparently enabled when malloc stack logging is
- * enabled), or the first registered zone otherwise. In practice this
- * means unless malloc stack logging is enabled, the first registered
+ malloc_zone_t **zones = NULL;
+ unsigned int num_zones = 0;
+
+ /*
+ * On OSX 10.12, malloc_default_zone returns a special zone that is not
+ * present in the list of registered zones. That zone uses a "lite zone"
+ * if one is present (apparently enabled when malloc stack logging is
+ * enabled), or the first registered zone otherwise. In practice this
+ * means unless malloc stack logging is enabled, the first registered
* zone is the default. So get the list of zones to get the first one,
* instead of relying on malloc_default_zone.
- */
+ */
if (KERN_SUCCESS != malloc_get_all_zones(0, NULL,
(vm_address_t**)&zones, &num_zones)) {
/*
* Reset the value in case the failure happened after it was
* set.
*/
- num_zones = 0;
- }
-
+ num_zones = 0;
+ }
+
if (num_zones) {
- return zones[0];
+ return zones[0];
}
-
- return malloc_default_zone();
-}
-
+
+ return malloc_default_zone();
+}
+
/* As written, this function can only promote jemalloc_zone. */
static void
zone_promote(void) {
diff --git a/contrib/libs/jemalloc/ya.make b/contrib/libs/jemalloc/ya.make
index f249f02c5e..586de30ab0 100644
--- a/contrib/libs/jemalloc/ya.make
+++ b/contrib/libs/jemalloc/ya.make
@@ -15,7 +15,7 @@ LICENSE(
BSD-2-Clause AND
Public-Domain
)
-
+
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
ADDINCL(
diff --git a/contrib/libs/ya.make b/contrib/libs/ya.make
index 096df4cd87..9c4640fdcf 100644
--- a/contrib/libs/ya.make
+++ b/contrib/libs/ya.make
@@ -45,7 +45,7 @@ RECURSE(
crfsuite
croaring
ctemplate
- curl
+ curl
cxxsupp/libcxx
cxxsupp/libcxxabi-parts
djvulibre
@@ -287,12 +287,12 @@ RECURSE(
pycxx
python
python/ut
- qhull
+ qhull
quicklz
r-lang
re2
- regional-units/library
- regional-units/library/ut
+ regional-units/library
+ regional-units/library/ut
rocksdb
rocksdb/tools/ldb
rocksdb/tools/sst_dump
@@ -315,7 +315,7 @@ RECURSE(
stan-math
stan/stan/command
stxxl
- subversion
+ subversion
sundials
svm
svt-hevc
@@ -391,12 +391,12 @@ ENDIF()
IF (OS_LINUX)
RECURSE(
ibdrv
- ibdrv/ut
+ ibdrv/ut
proc
luajit
luajit_21
libaio
- libcap
+ libcap
libmnl
libnfnetlink
libnetfilter_log
@@ -430,7 +430,7 @@ ENDIF()
IF (OS_ANDROID)
RECURSE(
- android_cpufeatures
+ android_cpufeatures
android_crazy_linker
)
ENDIF()
diff --git a/contrib/python/PyYAML/py2/ya.make b/contrib/python/PyYAML/py2/ya.make
index 372005867d..1ec5c0c301 100644
--- a/contrib/python/PyYAML/py2/ya.make
+++ b/contrib/python/PyYAML/py2/ya.make
@@ -3,7 +3,7 @@ PY2_LIBRARY()
LICENSE(MIT)
VERSION(5.4.1)
-
+
OWNER(g:python-contrib borman g:testenv)
PEERDIR(
diff --git a/contrib/python/PyYAML/py3/ya.make b/contrib/python/PyYAML/py3/ya.make
index ff032997c8..0401c04651 100644
--- a/contrib/python/PyYAML/py3/ya.make
+++ b/contrib/python/PyYAML/py3/ya.make
@@ -3,7 +3,7 @@ PY3_LIBRARY()
LICENSE(MIT)
VERSION(5.4.1)
-
+
OWNER(g:python-contrib borman g:testenv)
PEERDIR(
diff --git a/contrib/python/PyYAML/ya.make b/contrib/python/PyYAML/ya.make
index 80a68a1512..a604fce51f 100644
--- a/contrib/python/PyYAML/ya.make
+++ b/contrib/python/PyYAML/ya.make
@@ -1,9 +1,9 @@
-PY23_LIBRARY()
+PY23_LIBRARY()
LICENSE(MIT)
OWNER(g:python-contrib)
-
+
IF (PYTHON2)
PEERDIR(
contrib/python/PyYAML/py2
diff --git a/contrib/python/cryptography/.dist-info/METADATA b/contrib/python/cryptography/.dist-info/METADATA
index 6984988c85..7abd5f9465 100644
--- a/contrib/python/cryptography/.dist-info/METADATA
+++ b/contrib/python/cryptography/.dist-info/METADATA
@@ -1,131 +1,131 @@
-Metadata-Version: 2.1
-Name: cryptography
+Metadata-Version: 2.1
+Name: cryptography
Version: 3.3.2
-Summary: cryptography is a package which provides cryptographic recipes and primitives to Python developers.
-Home-page: https://github.com/pyca/cryptography
-Author: The cryptography developers
-Author-email: cryptography-dev@python.org
-License: BSD or Apache License, Version 2.0
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: Apache Software License
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Natural Language :: English
-Classifier: Operating System :: MacOS :: MacOS X
-Classifier: Operating System :: POSIX
-Classifier: Operating System :: POSIX :: BSD
-Classifier: Operating System :: POSIX :: Linux
-Classifier: Operating System :: Microsoft :: Windows
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
+Summary: cryptography is a package which provides cryptographic recipes and primitives to Python developers.
+Home-page: https://github.com/pyca/cryptography
+Author: The cryptography developers
+Author-email: cryptography-dev@python.org
+License: BSD or Apache License, Version 2.0
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Natural Language :: English
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: POSIX
+Classifier: Operating System :: POSIX :: BSD
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-Classifier: Topic :: Security :: Cryptography
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Security :: Cryptography
Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*
Description-Content-Type: text/x-rst
-Requires-Dist: six (>=1.4.1)
+Requires-Dist: six (>=1.4.1)
Requires-Dist: cffi (>=1.12)
Requires-Dist: enum34 ; python_version < '3'
Requires-Dist: ipaddress ; python_version < '3'
-Provides-Extra: docs
+Provides-Extra: docs
Requires-Dist: sphinx (!=1.8.0,!=3.1.0,!=3.1.1,>=1.6.5) ; extra == 'docs'
Requires-Dist: sphinx-rtd-theme ; extra == 'docs'
-Provides-Extra: docstest
+Provides-Extra: docstest
Requires-Dist: doc8 ; extra == 'docstest'
Requires-Dist: pyenchant (>=1.6.11) ; extra == 'docstest'
Requires-Dist: twine (>=1.12.0) ; extra == 'docstest'
Requires-Dist: sphinxcontrib-spelling (>=4.0.1) ; extra == 'docstest'
-Provides-Extra: pep8test
+Provides-Extra: pep8test
Requires-Dist: black ; extra == 'pep8test'
Requires-Dist: flake8 ; extra == 'pep8test'
Requires-Dist: flake8-import-order ; extra == 'pep8test'
Requires-Dist: pep8-naming ; extra == 'pep8test'
Provides-Extra: ssh
Requires-Dist: bcrypt (>=3.1.5) ; extra == 'ssh'
-Provides-Extra: test
+Provides-Extra: test
Requires-Dist: pytest (!=3.9.0,!=3.9.1,!=3.9.2,>=3.6.0) ; extra == 'test'
Requires-Dist: pretend ; extra == 'test'
Requires-Dist: iso8601 ; extra == 'test'
Requires-Dist: pytz ; extra == 'test'
Requires-Dist: hypothesis (!=3.79.2,>=1.11.4) ; extra == 'test'
-
-pyca/cryptography
-=================
-
-.. image:: https://img.shields.io/pypi/v/cryptography.svg
- :target: https://pypi.org/project/cryptography/
- :alt: Latest Version
-
-.. image:: https://readthedocs.org/projects/cryptography/badge/?version=latest
- :target: https://cryptography.io
- :alt: Latest Docs
-
+
+pyca/cryptography
+=================
+
+.. image:: https://img.shields.io/pypi/v/cryptography.svg
+ :target: https://pypi.org/project/cryptography/
+ :alt: Latest Version
+
+.. image:: https://readthedocs.org/projects/cryptography/badge/?version=latest
+ :target: https://cryptography.io
+ :alt: Latest Docs
+
.. image:: https://github.com/pyca/cryptography/workflows/CI/badge.svg?branch=master
:target: https://github.com/pyca/cryptography/actions?query=workflow%3ACI+branch%3Amaster
-
-.. image:: https://codecov.io/github/pyca/cryptography/coverage.svg?branch=master
- :target: https://codecov.io/github/pyca/cryptography?branch=master
-
-
-``cryptography`` is a package which provides cryptographic recipes and
-primitives to Python developers. Our goal is for it to be your "cryptographic
+
+.. image:: https://codecov.io/github/pyca/cryptography/coverage.svg?branch=master
+ :target: https://codecov.io/github/pyca/cryptography?branch=master
+
+
+``cryptography`` is a package which provides cryptographic recipes and
+primitives to Python developers. Our goal is for it to be your "cryptographic
standard library". It supports Python 2.7, Python 3.6+, and PyPy 5.4+.
-
-``cryptography`` includes both high level recipes and low level interfaces to
-common cryptographic algorithms such as symmetric ciphers, message digests, and
-key derivation functions. For example, to encrypt something with
-``cryptography``'s high level symmetric encryption recipe:
-
-.. code-block:: pycon
-
- >>> from cryptography.fernet import Fernet
- >>> # Put this somewhere safe!
- >>> key = Fernet.generate_key()
- >>> f = Fernet(key)
- >>> token = f.encrypt(b"A really secret message. Not for prying eyes.")
- >>> token
- '...'
- >>> f.decrypt(token)
- 'A really secret message. Not for prying eyes.'
-
-You can find more information in the `documentation`_.
-
-You can install ``cryptography`` with:
-
-.. code-block:: console
-
- $ pip install cryptography
-
-For full details see `the installation documentation`_.
-
-Discussion
-~~~~~~~~~~
-
-If you run into bugs, you can file them in our `issue tracker`_.
-
-We maintain a `cryptography-dev`_ mailing list for development discussion.
-
-You can also join ``#cryptography-dev`` on Freenode to ask questions or get
-involved.
-
-Security
-~~~~~~~~
-
-Need to report a security issue? Please consult our `security reporting`_
-documentation.
-
-
-.. _`documentation`: https://cryptography.io/
+
+``cryptography`` includes both high level recipes and low level interfaces to
+common cryptographic algorithms such as symmetric ciphers, message digests, and
+key derivation functions. For example, to encrypt something with
+``cryptography``'s high level symmetric encryption recipe:
+
+.. code-block:: pycon
+
+ >>> from cryptography.fernet import Fernet
+ >>> # Put this somewhere safe!
+ >>> key = Fernet.generate_key()
+ >>> f = Fernet(key)
+ >>> token = f.encrypt(b"A really secret message. Not for prying eyes.")
+ >>> token
+ '...'
+ >>> f.decrypt(token)
+ 'A really secret message. Not for prying eyes.'
+
+You can find more information in the `documentation`_.
+
+You can install ``cryptography`` with:
+
+.. code-block:: console
+
+ $ pip install cryptography
+
+For full details see `the installation documentation`_.
+
+Discussion
+~~~~~~~~~~
+
+If you run into bugs, you can file them in our `issue tracker`_.
+
+We maintain a `cryptography-dev`_ mailing list for development discussion.
+
+You can also join ``#cryptography-dev`` on Freenode to ask questions or get
+involved.
+
+Security
+~~~~~~~~
+
+Need to report a security issue? Please consult our `security reporting`_
+documentation.
+
+
+.. _`documentation`: https://cryptography.io/
.. _`the installation documentation`: https://cryptography.io/en/latest/installation.html
-.. _`issue tracker`: https://github.com/pyca/cryptography/issues
-.. _`cryptography-dev`: https://mail.python.org/mailman/listinfo/cryptography-dev
+.. _`issue tracker`: https://github.com/pyca/cryptography/issues
+.. _`cryptography-dev`: https://mail.python.org/mailman/listinfo/cryptography-dev
.. _`security reporting`: https://cryptography.io/en/latest/security.html
-
-
+
+
diff --git a/contrib/python/cryptography/.dist-info/top_level.txt b/contrib/python/cryptography/.dist-info/top_level.txt
index cb0afcc11d..52ccfc6e37 100644
--- a/contrib/python/cryptography/.dist-info/top_level.txt
+++ b/contrib/python/cryptography/.dist-info/top_level.txt
@@ -1,3 +1,3 @@
_openssl
_padding
-cryptography
+cryptography
diff --git a/contrib/python/cryptography/ya.make b/contrib/python/cryptography/ya.make
index 7d6b5ba94c..d63bb62f6a 100644
--- a/contrib/python/cryptography/ya.make
+++ b/contrib/python/cryptography/ya.make
@@ -25,12 +25,12 @@ PEERDIR(
NO_COMPILER_WARNINGS()
NO_LINT()
-RESOURCE_FILES(
- PREFIX contrib/python/cryptography/
- .dist-info/METADATA
- .dist-info/top_level.txt
-)
-
+RESOURCE_FILES(
+ PREFIX contrib/python/cryptography/
+ .dist-info/METADATA
+ .dist-info/top_level.txt
+)
+
SRCS(
build/temp.linux-x86_64-2.7/_openssl.c
build/temp.linux-x86_64-2.7/_padding.c
diff --git a/contrib/python/ipython/py2/IPython/core/alias.py b/contrib/python/ipython/py2/IPython/core/alias.py
index be4e7eebed..28a9ccb00d 100644
--- a/contrib/python/ipython/py2/IPython/core/alias.py
+++ b/contrib/python/ipython/py2/IPython/core/alias.py
@@ -29,7 +29,7 @@ from IPython.core.error import UsageError
from IPython.utils.py3compat import string_types
from traitlets import List, Instance
-from logging import error
+from logging import error
#-----------------------------------------------------------------------------
# Utilities
@@ -192,8 +192,8 @@ class Alias(object):
class AliasManager(Configurable):
- default_aliases = List(default_aliases()).tag(config=True)
- user_aliases = List(default_value=[]).tag(config=True)
+ default_aliases = List(default_aliases()).tag(config=True)
+ user_aliases = List(default_value=[]).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs):
diff --git a/contrib/python/ipython/py2/IPython/core/application.py b/contrib/python/ipython/py2/IPython/core/application.py
index 32983540e7..af28133945 100644
--- a/contrib/python/ipython/py2/IPython/core/application.py
+++ b/contrib/python/ipython/py2/IPython/core/application.py
@@ -13,7 +13,7 @@ object and then create the configurable objects, passing the config to them.
# Distributed under the terms of the Modified BSD License.
import atexit
-from copy import deepcopy
+from copy import deepcopy
import glob
import logging
import os
@@ -27,10 +27,10 @@ from IPython.core.profiledir import ProfileDir, ProfileDirError
from IPython.paths import get_ipython_dir, get_ipython_package_dir
from IPython.utils.path import ensure_dir_exists
from IPython.utils import py3compat
-from traitlets import (
- List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
- default, observe,
-)
+from traitlets import (
+ List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
+ default, observe,
+)
if os.name == 'nt':
programdata = os.environ.get('PROGRAMDATA', None)
@@ -52,16 +52,16 @@ if _env_config_dir not in SYSTEM_CONFIG_DIRS:
ENV_CONFIG_DIRS.append(_env_config_dir)
-_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
-if _envvar in {None, ''}:
- IPYTHON_SUPPRESS_CONFIG_ERRORS = None
-else:
- if _envvar.lower() in {'1','true'}:
- IPYTHON_SUPPRESS_CONFIG_ERRORS = True
- elif _envvar.lower() in {'0','false'} :
- IPYTHON_SUPPRESS_CONFIG_ERRORS = False
- else:
- sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
+_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
+if _envvar in {None, ''}:
+ IPYTHON_SUPPRESS_CONFIG_ERRORS = None
+else:
+ if _envvar.lower() in {'1','true'}:
+ IPYTHON_SUPPRESS_CONFIG_ERRORS = True
+ elif _envvar.lower() in {'0','false'} :
+ IPYTHON_SUPPRESS_CONFIG_ERRORS = False
+ else:
+ sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
# aliases and flags
@@ -118,13 +118,13 @@ class BaseIPythonApplication(Application):
config_file_specified = Set()
config_file_name = Unicode()
- @default('config_file_name')
+ @default('config_file_name')
def _config_file_name_default(self):
return self.name.replace('-','_') + u'_config.py'
- @observe('config_file_name')
- def _config_file_name_changed(self, change):
- if change['new'] != change['old']:
- self.config_file_specified.add(change['new'])
+ @observe('config_file_name')
+ def _config_file_name_changed(self, change):
+ if change['new'] != change['old']:
+ self.config_file_specified.add(change['new'])
# The directory that contains IPython's builtin profiles.
builtin_profile_dir = Unicode(
@@ -132,19 +132,19 @@ class BaseIPythonApplication(Application):
)
config_file_paths = List(Unicode())
- @default('config_file_paths')
+ @default('config_file_paths')
def _config_file_paths_default(self):
return [py3compat.getcwd()]
- extra_config_file = Unicode(
+ extra_config_file = Unicode(
help="""Path to an extra config file to load.
If specified, load this config file in addition to any other IPython config.
- """).tag(config=True)
- @observe('extra_config_file')
- def _extra_config_file_changed(self, change):
- old = change['old']
- new = change['new']
+ """).tag(config=True)
+ @observe('extra_config_file')
+ def _extra_config_file_changed(self, change):
+ old = change['old']
+ new = change['new']
try:
self.config_files.remove(old)
except ValueError:
@@ -152,37 +152,37 @@ class BaseIPythonApplication(Application):
self.config_file_specified.add(new)
self.config_files.append(new)
- profile = Unicode(u'default',
+ profile = Unicode(u'default',
help="""The IPython profile to use."""
- ).tag(config=True)
-
- @observe('profile')
- def _profile_changed(self, change):
+ ).tag(config=True)
+
+ @observe('profile')
+ def _profile_changed(self, change):
self.builtin_profile_dir = os.path.join(
- get_ipython_package_dir(), u'config', u'profile', change['new']
+ get_ipython_package_dir(), u'config', u'profile', change['new']
)
- ipython_dir = Unicode(
+ ipython_dir = Unicode(
help="""
The name of the IPython directory. This directory is used for logging
configuration (through profiles), history storage, etc. The default
is usually $HOME/.ipython. This option can also be specified through
the environment variable IPYTHONDIR.
"""
- ).tag(config=True)
- @default('ipython_dir')
+ ).tag(config=True)
+ @default('ipython_dir')
def _ipython_dir_default(self):
d = get_ipython_dir()
- self._ipython_dir_changed({
- 'name': 'ipython_dir',
- 'old': d,
- 'new': d,
- })
+ self._ipython_dir_changed({
+ 'name': 'ipython_dir',
+ 'old': d,
+ 'new': d,
+ })
return d
_in_init_profile_dir = False
profile_dir = Instance(ProfileDir, allow_none=True)
- @default('profile_dir')
+ @default('profile_dir')
def _profile_dir_default(self):
# avoid recursion
if self._in_init_profile_dir:
@@ -191,29 +191,29 @@ class BaseIPythonApplication(Application):
self.init_profile_dir()
return self.profile_dir
- overwrite = Bool(False,
- help="""Whether to overwrite existing config files when copying"""
- ).tag(config=True)
- auto_create = Bool(False,
- help="""Whether to create profile dir if it doesn't exist"""
- ).tag(config=True)
+ overwrite = Bool(False,
+ help="""Whether to overwrite existing config files when copying"""
+ ).tag(config=True)
+ auto_create = Bool(False,
+ help="""Whether to create profile dir if it doesn't exist"""
+ ).tag(config=True)
config_files = List(Unicode())
- @default('config_files')
+ @default('config_files')
def _config_files_default(self):
return [self.config_file_name]
- copy_config_files = Bool(False,
+ copy_config_files = Bool(False,
help="""Whether to install the default config files into the profile dir.
If a new profile is being created, and IPython contains config files for that
profile, then they will be staged into the new directory. Otherwise,
default config files will be automatically generated.
- """).tag(config=True)
+ """).tag(config=True)
- verbose_crash = Bool(False,
+ verbose_crash = Bool(False,
help="""Create a massive crash report when IPython encounters what may be an
internal error. The default is to append a short message to the
- usual traceback""").tag(config=True)
+ usual traceback""").tag(config=True)
# The class to use as the crash handler.
crash_handler_class = Type(crashhandler.CrashHandler)
@@ -239,8 +239,8 @@ class BaseIPythonApplication(Application):
if subc in self.deprecated_subcommands:
self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
"in future versions.".format(sub=subc))
- self.log.warning("You likely want to use `jupyter {sub}` in the "
- "future".format(sub=subc))
+ self.log.warning("You likely want to use `jupyter {sub}` in the "
+ "future".format(sub=subc))
return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
def init_crash_handler(self):
@@ -262,11 +262,11 @@ class BaseIPythonApplication(Application):
return self.crash_handler(etype, evalue, tb)
else:
return crashhandler.crash_handler_lite(etype, evalue, tb)
-
- @observe('ipython_dir')
- def _ipython_dir_changed(self, change):
- old = change['old']
- new = change['new']
+
+ @observe('ipython_dir')
+ def _ipython_dir_changed(self, change):
+ old = change['old']
+ new = change['new']
if old is not Undefined:
str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
sys.getfilesystemencoding()
@@ -291,33 +291,33 @@ class BaseIPythonApplication(Application):
self.log.error("couldn't create path %s: %s", path, e)
self.log.debug("IPYTHONDIR set to: %s" % new)
- def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
+ def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
"""Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
-
- `supress_errors` default value is to be `None` in which case the
- behavior default to the one of `traitlets.Application`.
-
- The default value can be set :
- - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
- - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
- - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
-
- Any other value are invalid, and will make IPython exit with a non-zero return code.
+
+ `supress_errors` default value is to be `None` in which case the
+ behavior default to the one of `traitlets.Application`.
+
+ The default value can be set :
+ - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
+ - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
+ - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
+
+ Any other value are invalid, and will make IPython exit with a non-zero return code.
"""
-
-
+
+
self.log.debug("Searching path %s for config files", self.config_file_paths)
base_config = 'ipython_config.py'
self.log.debug("Attempting to load config file: %s" %
base_config)
try:
- if suppress_errors is not None:
- old_value = Application.raise_config_file_errors
- Application.raise_config_file_errors = not suppress_errors;
+ if suppress_errors is not None:
+ old_value = Application.raise_config_file_errors
+ Application.raise_config_file_errors = not suppress_errors;
Application.load_config_file(
self,
base_config,
@@ -327,8 +327,8 @@ class BaseIPythonApplication(Application):
# ignore errors loading parent
self.log.debug("Config file %s not found", base_config)
pass
- if suppress_errors is not None:
- Application.raise_config_file_errors = old_value
+ if suppress_errors is not None:
+ Application.raise_config_file_errors = old_value
for config_file_name in self.config_files:
if not config_file_name or config_file_name == base_config:
@@ -457,9 +457,9 @@ class BaseIPythonApplication(Application):
if self.subapp is not None:
# stop here if subapp is taking over
return
- # save a copy of CLI config to re-load after config files
- # so that it has highest priority
- cl_config = deepcopy(self.config)
+ # save a copy of CLI config to re-load after config files
+ # so that it has highest priority
+ cl_config = deepcopy(self.config)
self.init_profile_dir()
self.init_config_files()
self.load_config_file()
diff --git a/contrib/python/ipython/py2/IPython/core/builtin_trap.py b/contrib/python/ipython/py2/IPython/core/builtin_trap.py
index ff857be949..909a555c73 100644
--- a/contrib/python/ipython/py2/IPython/core/builtin_trap.py
+++ b/contrib/python/ipython/py2/IPython/core/builtin_trap.py
@@ -57,7 +57,7 @@ class BuiltinTrap(Configurable):
from IPython.lib import deepreload
if self.shell.deep_reload:
from warnings import warn
- warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning)
+ warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning)
self.auto_builtins['reload'] = deepreload._dreload
else:
self.auto_builtins['dreload']= deepreload._dreload
diff --git a/contrib/python/ipython/py2/IPython/core/completer.py b/contrib/python/ipython/py2/IPython/core/completer.py
index 70bdee80ed..b386945e54 100644
--- a/contrib/python/ipython/py2/IPython/core/completer.py
+++ b/contrib/python/ipython/py2/IPython/core/completer.py
@@ -1,9 +1,9 @@
# encoding: utf-8
"""Word completion for IPython.
-This module started as fork of the rlcompleter module in the Python standard
+This module started as fork of the rlcompleter module in the Python standard
library. The original enhancements made to rlcompleter have been sent
-upstream and were accepted as of Python 2.3,
+upstream and were accepted as of Python 2.3,
"""
@@ -13,8 +13,8 @@ upstream and were accepted as of Python 2.3,
# Some of this code originated from rlcompleter in the Python standard library
# Copyright (C) 2001 Python Software Foundation, www.python.org
-from __future__ import print_function
-
+from __future__ import print_function
+
import __main__
import glob
import inspect
@@ -27,18 +27,18 @@ import unicodedata
import string
import warnings
-from traitlets.config.configurable import Configurable
+from traitlets.config.configurable import Configurable
from IPython.core.error import TryNext
from IPython.core.inputsplitter import ESC_MAGIC
from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
from IPython.utils import generics
from IPython.utils.decorators import undoc
-from IPython.utils.dir2 import dir2, get_real_method
+from IPython.utils.dir2 import dir2, get_real_method
from IPython.utils.process import arg_split
-from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
-from traitlets import Bool, Enum, observe
+from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
+from traitlets import Bool, Enum, observe
+
-
# Public API
__all__ = ['Completer','IPCompleter']
@@ -74,13 +74,13 @@ def has_open_quotes(s):
def protect_filename(s):
"""Escape a string to protect certain characters."""
- if set(s) & set(PROTECTABLES):
- if sys.platform == "win32":
- return '"' + s + '"'
- else:
- return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
- else:
- return s
+ if set(s) & set(PROTECTABLES):
+ if sys.platform == "win32":
+ return '"' + s + '"'
+ else:
+ return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
+ else:
+ return s
def expand_user(path):
@@ -132,52 +132,52 @@ def compress_user(path, tilde_expand, tilde_val):
return path
-def completions_sorting_key(word):
- """key for sorting completions
+def completions_sorting_key(word):
+ """key for sorting completions
- This does several things:
+ This does several things:
- - Lowercase all completions, so they are sorted alphabetically with
- upper and lower case words mingled
- - Demote any completions starting with underscores to the end
- - Insert any %magic and %%cellmagic completions in the alphabetical order
- by their name
- """
- # Case insensitive sort
- word = word.lower()
+ - Lowercase all completions, so they are sorted alphabetically with
+ upper and lower case words mingled
+ - Demote any completions starting with underscores to the end
+ - Insert any %magic and %%cellmagic completions in the alphabetical order
+ by their name
+ """
+ # Case insensitive sort
+ word = word.lower()
- prio1, prio2 = 0, 0
+ prio1, prio2 = 0, 0
- if word.startswith('__'):
- prio1 = 2
- elif word.startswith('_'):
- prio1 = 1
+ if word.startswith('__'):
+ prio1 = 2
+ elif word.startswith('_'):
+ prio1 = 1
- if word.endswith('='):
- prio1 = -1
+ if word.endswith('='):
+ prio1 = -1
- if word.startswith('%%'):
- # If there's another % in there, this is something else, so leave it alone
+ if word.startswith('%%'):
+ # If there's another % in there, this is something else, so leave it alone
if not "%" in word[2:]:
- word = word[2:]
- prio2 = 2
- elif word.startswith('%'):
+ word = word[2:]
+ prio2 = 2
+ elif word.startswith('%'):
if not "%" in word[1:]:
- word = word[1:]
- prio2 = 1
+ word = word[1:]
+ prio2 = 1
+
+ return prio1, word, prio2
- return prio1, word, prio2
-
@undoc
class Bunch(object): pass
-if sys.platform == 'win32':
- DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
-else:
- DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
-
+if sys.platform == 'win32':
+ DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
+else:
+ DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
+
GREEDY_DELIMS = ' =\r\n'
@@ -234,14 +234,14 @@ class CompletionSplitter(object):
class Completer(Configurable):
- greedy = Bool(False,
+ greedy = Bool(False,
help="""Activate greedy completion
- PENDING DEPRECTION. this is now mostly taken care of with Jedi.
+ PENDING DEPRECTION. this is now mostly taken care of with Jedi.
This will enable completion on elements of lists, results of function calls, etc.,
but can be unsafe because the code is actually evaluated on TAB.
"""
- ).tag(config=True)
+ ).tag(config=True)
backslash_combining_completions = Bool(True,
help="Enable unicode completions, e.g. \\alpha<tab> . "
@@ -251,7 +251,7 @@ class Completer(Configurable):
def __init__(self, namespace=None, global_namespace=None, **kwargs):
"""Create a new completer for the command line.
- Completer(namespace=ns, global_namespace=ns2) -> completer instance.
+ Completer(namespace=ns, global_namespace=ns2) -> completer instance.
If unspecified, the default namespace where completions are performed
is __main__ (technically, __main__.__dict__). Namespaces should be
@@ -321,7 +321,7 @@ class Completer(Configurable):
for word in lst:
if word[:n] == text and word != "__builtins__":
match_append(word)
- return [cast_unicode_py2(m) for m in matches]
+ return [cast_unicode_py2(m) for m in matches]
def attr_matches(self, text):
"""Compute matches when text contains a dot.
@@ -373,7 +373,7 @@ class Completer(Configurable):
pass
# Build match list to return
n = len(attr)
- return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
+ return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
def get__all__entries(obj):
@@ -383,7 +383,7 @@ def get__all__entries(obj):
except:
return []
- return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
+ return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
def match_dict_keys(keys, prefix, delims):
@@ -470,7 +470,7 @@ def back_unicode_name_matches(text):
try :
unic = unicodedata.name(char)
return '\\'+char,['\\'+unic]
- except KeyError:
+ except KeyError:
pass
return u'', ()
@@ -497,18 +497,18 @@ def back_latex_name_matches(text):
latex = reverse_latex_symbol[char]
# '\\' replace the \ as well
return '\\'+char,[latex]
- except KeyError:
+ except KeyError:
pass
return u'', ()
class IPCompleter(Completer):
"""Extension of the completer class with IPython-specific features"""
-
- @observe('greedy')
- def _greedy_changed(self, change):
+
+ @observe('greedy')
+ def _greedy_changed(self, change):
"""update the splitter and readline delims when greedy is changed"""
- if change['new']:
+ if change['new']:
self.splitter.delims = GREEDY_DELIMS
else:
self.splitter.delims = DELIMS
@@ -516,14 +516,14 @@ class IPCompleter(Completer):
if self.readline:
self.readline.set_completer_delims(self.splitter.delims)
- merge_completions = Bool(True,
+ merge_completions = Bool(True,
help="""Whether to merge completion results into a single list
If False, only the completion results from the first non-empty
completer will be returned.
"""
- ).tag(config=True)
- omit__names = Enum((0,1,2), default_value=2,
+ ).tag(config=True)
+ omit__names = Enum((0,1,2), default_value=2,
help="""Instruct the completer to omit private method names
Specifically, when completing on ``object.<tab>``.
@@ -534,20 +534,20 @@ class IPCompleter(Completer):
When 0: nothing will be excluded.
"""
- ).tag(config=True)
- limit_to__all__ = Bool(False,
- help="""
- DEPRECATED as of version 5.0.
+ ).tag(config=True)
+ limit_to__all__ = Bool(False,
+ help="""
+ DEPRECATED as of version 5.0.
+
+ Instruct the completer to use __all__ for the completion
- Instruct the completer to use __all__ for the completion
-
Specifically, when completing on ``object.<tab>``.
When True: only those names in obj.__all__ will be included.
When False [default]: the __all__ attribute is ignored
- """,
- ).tag(config=True)
+ """,
+ ).tag(config=True)
@observe('limit_to__all__')
def _limit_to_all_changed(self, change):
@@ -621,24 +621,24 @@ class IPCompleter(Completer):
#= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
# All active matcher routines for completion
- self.matchers = [
- self.python_matches,
+ self.matchers = [
+ self.python_matches,
self.file_matches,
self.magic_matches,
self.python_func_kw_matches,
self.dict_key_matches,
]
- # This is set externally by InteractiveShell
- self.custom_completers = None
-
+ # This is set externally by InteractiveShell
+ self.custom_completers = None
+
def all_completions(self, text):
"""
- Wrapper around the complete method for the benefit of emacs.
+ Wrapper around the complete method for the benefit of emacs.
"""
return self.complete(text)[1]
- def _clean_glob(self, text):
+ def _clean_glob(self, text):
return self.glob("%s*" % text)
def _clean_glob_win32(self,text):
@@ -665,9 +665,9 @@ class IPCompleter(Completer):
# when escaped with backslash
if text.startswith('!'):
text = text[1:]
- text_prefix = u'!'
+ text_prefix = u'!'
else:
- text_prefix = u''
+ text_prefix = u''
text_until_cursor = self.text_until_cursor
# track strings with open quotes
@@ -698,13 +698,13 @@ class IPCompleter(Completer):
text = os.path.expanduser(text)
if text == "":
- return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
+ return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
# Compute the matches from the filesystem
- if sys.platform == 'win32':
- m0 = self.clean_glob(text)
- else:
- m0 = self.clean_glob(text.replace('\\', ''))
+ if sys.platform == 'win32':
+ m0 = self.clean_glob(text)
+ else:
+ m0 = self.clean_glob(text.replace('\\', ''))
if has_protectables:
# If we had protectables, we need to revert our changes to the
@@ -724,7 +724,7 @@ class IPCompleter(Completer):
protect_filename(f) for f in m0]
# Mark directories in input list by appending '/' to their names.
- return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
+ return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
def magic_matches(self, text):
"""Match magics"""
@@ -745,10 +745,10 @@ class IPCompleter(Completer):
comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
if not text.startswith(pre2):
comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
- return [cast_unicode_py2(c) for c in comp]
+ return [cast_unicode_py2(c) for c in comp]
+
-
- def python_matches(self, text):
+ def python_matches(self, text):
"""Match attributes or global python names"""
if "." in text:
try:
@@ -896,19 +896,19 @@ class IPCompleter(Completer):
for namedArg in namedArgs:
if namedArg.startswith(text):
- argMatches.append(u"%s=" %namedArg)
+ argMatches.append(u"%s=" %namedArg)
return argMatches
def dict_key_matches(self, text):
"Match string keys in a dictionary, after e.g. 'foo[' "
def get_keys(obj):
- # Objects can define their own completions by defining an
- # _ipy_key_completions_() method.
- method = get_real_method(obj, '_ipython_key_completions_')
- if method is not None:
- return method()
-
- # Special case some common in-memory dict-like types
+ # Objects can define their own completions by defining an
+ # _ipy_key_completions_() method.
+ method = get_real_method(obj, '_ipython_key_completions_')
+ if method is not None:
+ return method()
+
+ # Special case some common in-memory dict-like types
if isinstance(obj, dict) or\
_safe_isinstance(obj, 'pandas', 'DataFrame'):
try:
@@ -1026,7 +1026,7 @@ class IPCompleter(Completer):
# allow combining chars
if ('a'+unic).isidentifier():
return '\\'+s,[unic]
- except KeyError:
+ except KeyError:
pass
return u'', []
@@ -1055,9 +1055,9 @@ class IPCompleter(Completer):
return u'', []
def dispatch_custom_completer(self, text):
- if not self.custom_completers:
- return
-
+ if not self.custom_completers:
+ return
+
line = self.line_buffer
if not line.strip():
return None
@@ -1085,12 +1085,12 @@ class IPCompleter(Completer):
res = c(event)
if res:
# first, try case sensitive match
- withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
+ withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
if withcase:
return withcase
# if none, then case insensitive ones are ok too
text_low = text.lower()
- return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
+ return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
except TryNext:
pass
except KeyboardInterrupt:
diff --git a/contrib/python/ipython/py2/IPython/core/completerlib.py b/contrib/python/ipython/py2/IPython/core/completerlib.py
index 5d51991725..e736ca73d1 100644
--- a/contrib/python/ipython/py2/IPython/core/completerlib.py
+++ b/contrib/python/ipython/py2/IPython/core/completerlib.py
@@ -227,8 +227,8 @@ def try_import(mod, only_modules=False):
completions.extend(getattr(m, '__all__', []))
if m_is_init:
completions.extend(arcadia_module_list(mod))
- completions = {c for c in completions if isinstance(c, string_types)}
- completions.discard('__init__')
+ completions = {c for c in completions if isinstance(c, string_types)}
+ completions.discard('__init__')
return sorted(completions)
diff --git a/contrib/python/ipython/py2/IPython/core/debugger.py b/contrib/python/ipython/py2/IPython/core/debugger.py
index 4980c3551b..f08cfb1a78 100644
--- a/contrib/python/ipython/py2/IPython/core/debugger.py
+++ b/contrib/python/ipython/py2/IPython/core/debugger.py
@@ -31,40 +31,40 @@ import bdb
import functools
import inspect
import sys
-import warnings
+import warnings
from IPython import get_ipython
from IPython.utils import PyColorize, ulinecache
-from IPython.utils import coloransi, py3compat
+from IPython.utils import coloransi, py3compat
from IPython.core.excolors import exception_colors
from IPython.testing.skipdoctest import skip_doctest
-
+
prompt = 'ipdb> '
-
+
#We have to check this directly from sys.argv, config struct not yet available
-from pdb import Pdb as OldPdb
+from pdb import Pdb as OldPdb
# Allow the set_trace code to operate outside of an ipython instance, even if
# it does so with some limitations. The rest of this support is implemented in
# the Tracer constructor.
-
-def make_arrow(pad):
- """generate the leading arrow in front of traceback or debugger"""
- if pad >= 2:
- return '-'*(pad-2) + '> '
- elif pad == 1:
- return '>'
- return ''
-
-
+
+def make_arrow(pad):
+ """generate the leading arrow in front of traceback or debugger"""
+ if pad >= 2:
+ return '-'*(pad-2) + '> '
+ elif pad == 1:
+ return '>'
+ return ''
+
+
def BdbQuit_excepthook(et, ev, tb, excepthook=None):
"""Exception hook which handles `BdbQuit` exceptions.
All other exceptions are processed using the `excepthook`
parameter.
"""
- warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
+ warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
DeprecationWarning, stacklevel=2)
if et==bdb.BdbQuit:
print('Exiting Debugger.')
@@ -74,20 +74,20 @@ def BdbQuit_excepthook(et, ev, tb, excepthook=None):
# Backwards compatibility. Raise deprecation warning?
BdbQuit_excepthook.excepthook_ori(et,ev,tb)
-
+
def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
- warnings.warn(
- "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
+ warnings.warn(
+ "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
DeprecationWarning, stacklevel=2)
print('Exiting Debugger.')
class Tracer(object):
- """
- DEPRECATED
+ """
+ DEPRECATED
+
+ Class for local debugging, similar to pdb.set_trace.
- Class for local debugging, similar to pdb.set_trace.
-
Instances of this class, when called, behave like pdb.set_trace, but
providing IPython's enhanced capabilities.
@@ -100,11 +100,11 @@ class Tracer(object):
@skip_doctest
def __init__(self, colors=None):
- """
- DEPRECATED
+ """
+ DEPRECATED
+
+ Create a local debugger instance.
- Create a local debugger instance.
-
Parameters
----------
@@ -128,8 +128,8 @@ class Tracer(object):
step through code, set breakpoints, etc. See the pdb documentation
from the Python standard library for usage details.
"""
- warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
- "`IPython.core.debugger.Pdb.set_trace()`",
+ warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
+ "`IPython.core.debugger.Pdb.set_trace()`",
DeprecationWarning, stacklevel=2)
ip = get_ipython()
@@ -204,25 +204,25 @@ def _file_lines(fname):
class Pdb(OldPdb):
- """Modified Pdb class, does not load readline.
-
- for a standalone version that uses prompt_toolkit, see
- `IPython.terminal.debugger.TerminalPdb` and
- `IPython.terminal.debugger.set_trace()`
- """
-
- def __init__(self, color_scheme=None, completekey=None,
+ """Modified Pdb class, does not load readline.
+
+ for a standalone version that uses prompt_toolkit, see
+ `IPython.terminal.debugger.TerminalPdb` and
+ `IPython.terminal.debugger.set_trace()`
+ """
+
+ def __init__(self, color_scheme=None, completekey=None,
stdin=None, stdout=None, context=5):
# Parent constructor:
try:
- self.context = int(context)
+ self.context = int(context)
if self.context <= 0:
raise ValueError("Context must be a positive integer")
except (TypeError, ValueError):
raise ValueError("Context must be a positive integer")
- OldPdb.__init__(self, completekey, stdin, stdout)
+ OldPdb.__init__(self, completekey, stdin, stdout)
# IPython changes...
self.shell = get_ipython()
@@ -237,12 +237,12 @@ class Pdb(OldPdb):
# the debugger was entered. See also #9941.
sys.modules['__main__'] = save_main
- if color_scheme is not None:
- warnings.warn(
- "The `color_scheme` argument is deprecated since version 5.1",
- DeprecationWarning)
- else:
- color_scheme = self.shell.colors
+ if color_scheme is not None:
+ warnings.warn(
+ "The `color_scheme` argument is deprecated since version 5.1",
+ DeprecationWarning)
+ else:
+ color_scheme = self.shell.colors
self.aliases = {}
@@ -266,28 +266,28 @@ class Pdb(OldPdb):
cst['LightBG'].colors.breakpoint_enabled = C.LightRed
cst['LightBG'].colors.breakpoint_disabled = C.Red
- cst['Neutral'].colors.prompt = C.Blue
- cst['Neutral'].colors.breakpoint_enabled = C.LightRed
- cst['Neutral'].colors.breakpoint_disabled = C.Red
-
+ cst['Neutral'].colors.prompt = C.Blue
+ cst['Neutral'].colors.breakpoint_enabled = C.LightRed
+ cst['Neutral'].colors.breakpoint_disabled = C.Red
+
self.set_colors(color_scheme)
# Add a python parser so we can syntax highlight source while
# debugging.
self.parser = PyColorize.Parser()
- # Set the prompt - the default prompt is '(Pdb)'
- self.prompt = prompt
+ # Set the prompt - the default prompt is '(Pdb)'
+ self.prompt = prompt
def set_colors(self, scheme):
"""Shorthand access to the color table scheme selector method."""
self.color_scheme_table.set_active_scheme(scheme)
def interaction(self, frame, traceback):
- try:
- OldPdb.interaction(self, frame, traceback)
- except KeyboardInterrupt:
- sys.stdout.write('\n' + self.shell.get_exception_only())
+ try:
+ OldPdb.interaction(self, frame, traceback)
+ except KeyboardInterrupt:
+ sys.stdout.write('\n' + self.shell.get_exception_only())
def new_do_up(self, arg):
OldPdb.do_up(self, arg)
@@ -331,7 +331,7 @@ class Pdb(OldPdb):
except KeyboardInterrupt:
pass
- def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
+ def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
context=None):
if context is None:
context = self.context
@@ -341,7 +341,7 @@ class Pdb(OldPdb):
raise ValueError("Context must be a positive integer")
except (TypeError, ValueError):
raise ValueError("Context must be a positive integer")
- print(self.format_stack_entry(frame_lineno, '', context))
+ print(self.format_stack_entry(frame_lineno, '', context))
# vds: >>
frame, lineno = frame_lineno
@@ -447,11 +447,11 @@ class Pdb(OldPdb):
if arrow:
# This is the line with the error
pad = numbers_width - len(str(lineno)) - len(bp_mark)
- num = '%s%s' % (make_arrow(pad), str(lineno))
+ num = '%s%s' % (make_arrow(pad), str(lineno))
else:
num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
- return tpl_line % (bp_mark_color + bp_mark, num, line)
+ return tpl_line % (bp_mark_color + bp_mark, num, line)
def print_list_lines(self, filename, first, last):
@@ -479,7 +479,7 @@ class Pdb(OldPdb):
src.append(line)
self.lineno = lineno
- print(''.join(src))
+ print(''.join(src))
except KeyboardInterrupt:
pass
diff --git a/contrib/python/ipython/py2/IPython/core/display.py b/contrib/python/ipython/py2/IPython/core/display.py
index a099031953..5c82a57b31 100644
--- a/contrib/python/ipython/py2/IPython/core/display.py
+++ b/contrib/python/ipython/py2/IPython/core/display.py
@@ -6,17 +6,17 @@
from __future__ import print_function
-try:
- from base64 import encodebytes as base64_encode
-except ImportError:
- from base64 import encodestring as base64_encode
-
+try:
+ from base64 import encodebytes as base64_encode
+except ImportError:
+ from base64 import encodestring as base64_encode
+
from binascii import b2a_hex, hexlify
import json
import mimetypes
import os
import struct
-import sys
+import sys
import warnings
from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
@@ -964,9 +964,9 @@ class Image(DisplayObject):
Note that QtConsole is not able to display images if `embed` is set to `False`
width : int
- Width in pixels to which to constrain the image in html
+ Width in pixels to which to constrain the image in html
height : int
- Height in pixels to which to constrain the image in html
+ Height in pixels to which to constrain the image in html
retina : bool
Automatically set the width and height to half of the measured
width and height.
@@ -1111,7 +1111,7 @@ class Image(DisplayObject):
class Video(DisplayObject):
- def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
+ def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
"""Create a video object given raw data or an URL.
When this object is returned by an input cell or passed to the
@@ -1121,54 +1121,54 @@ class Video(DisplayObject):
Parameters
----------
data : unicode, str or bytes
- The raw video data or a URL or filename to load the data from.
- Raw data will require passing `embed=True`.
+ The raw video data or a URL or filename to load the data from.
+ Raw data will require passing `embed=True`.
url : unicode
- A URL for the video. If you specify `url=`,
- the image data will not be embedded.
+ A URL for the video. If you specify `url=`,
+ the image data will not be embedded.
filename : unicode
- Path to a local file containing the video.
- Will be interpreted as a local URL unless `embed=True`.
+ Path to a local file containing the video.
+ Will be interpreted as a local URL unless `embed=True`.
embed : bool
- Should the video be embedded using a data URI (True) or be
- loaded using a <video> tag (False).
+ Should the video be embedded using a data URI (True) or be
+ loaded using a <video> tag (False).
+
+ Since videos are large, embedding them should be avoided, if possible.
+ You must confirm embedding as your intention by passing `embed=True`.
+
+ Local files can be displayed with URLs without embedding the content, via::
- Since videos are large, embedding them should be avoided, if possible.
- You must confirm embedding as your intention by passing `embed=True`.
+ Video('./video.mp4')
- Local files can be displayed with URLs without embedding the content, via::
-
- Video('./video.mp4')
-
mimetype: unicode
- Specify the mimetype for embedded videos.
- Default will be guessed from file extension, if available.
-
+ Specify the mimetype for embedded videos.
+ Default will be guessed from file extension, if available.
+
Examples
--------
-
+
Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
Video('path/to/video.mp4')
- Video('path/to/video.mp4', embed=True)
- Video(b'raw-videodata', embed=True)
+ Video('path/to/video.mp4', embed=True)
+ Video(b'raw-videodata', embed=True)
"""
- if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
+ if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
url = data
data = None
elif os.path.exists(data):
filename = data
data = None
-
- if data and not embed:
- msg = ''.join([
- "To embed videos, you must pass embed=True ",
- "(this may make your notebook files huge)\n",
- "Consider passing Video(url='...')",
- ])
- raise ValueError(msg)
+
+ if data and not embed:
+ msg = ''.join([
+ "To embed videos, you must pass embed=True ",
+ "(this may make your notebook files huge)\n",
+ "Consider passing Video(url='...')",
+ ])
+ raise ValueError(msg)
self.mimetype = mimetype
- self.embed = embed
+ self.embed = embed
super(Video, self).__init__(data=data, url=url, filename=filename)
def _repr_html_(self):
@@ -1180,27 +1180,27 @@ class Video(DisplayObject):
Your browser does not support the <code>video</code> element.
</video>""".format(url)
return output
-
- # Embedded videos are base64-encoded.
- mimetype = self.mimetype
+
+ # Embedded videos are base64-encoded.
+ mimetype = self.mimetype
if self.filename is not None:
- if not mimetype:
- mimetype, _ = mimetypes.guess_type(self.filename)
-
- with open(self.filename, 'rb') as f:
- video = f.read()
+ if not mimetype:
+ mimetype, _ = mimetypes.guess_type(self.filename)
+
+ with open(self.filename, 'rb') as f:
+ video = f.read()
else:
- video = self.data
- if isinstance(video, unicode_type):
- # unicode input is already b64-encoded
- b64_video = video
- else:
- b64_video = base64_encode(video).decode('ascii').rstrip()
-
+ video = self.data
+ if isinstance(video, unicode_type):
+ # unicode input is already b64-encoded
+ b64_video = video
+ else:
+ b64_video = base64_encode(video).decode('ascii').rstrip()
+
output = """<video controls>
<source src="data:{0};base64,{1}" type="{0}">
Your browser does not support the video tag.
- </video>""".format(mimetype, b64_video)
+ </video>""".format(mimetype, b64_video)
return output
def reload(self):
@@ -1225,10 +1225,10 @@ def clear_output(wait=False):
if InteractiveShell.initialized():
InteractiveShell.instance().display_pub.clear_output(wait)
else:
- print('\033[2K\r', end='')
- sys.stdout.flush()
- print('\033[2K\r', end='')
- sys.stderr.flush()
+ print('\033[2K\r', end='')
+ sys.stdout.flush()
+ print('\033[2K\r', end='')
+ sys.stderr.flush()
@skip_doctest
diff --git a/contrib/python/ipython/py2/IPython/core/displayhook.py b/contrib/python/ipython/py2/IPython/core/displayhook.py
index e07b577680..cce7c83d16 100644
--- a/contrib/python/ipython/py2/IPython/core/displayhook.py
+++ b/contrib/python/ipython/py2/IPython/core/displayhook.py
@@ -16,7 +16,7 @@ import tokenize
from traitlets.config.configurable import Configurable
from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
from traitlets import Instance, Float
-from warnings import warn
+from warnings import warn
# TODO: Move the various attributes (cache_size, [others now moved]). Some
# of these are also attributes of InteractiveShell. They should be on ONE object
@@ -94,7 +94,7 @@ class DisplayHook(Configurable):
tokens = list(tokenize.generate_tokens(sio.readline))
for token in reversed(tokens):
- if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
+ if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
continue
if (token[0] == tokenize.OP) and (token[1] == ';'):
return True
@@ -109,13 +109,13 @@ class DisplayHook(Configurable):
"""Write the output prompt.
The default implementation simply writes the prompt to
- ``sys.stdout``.
+ ``sys.stdout``.
"""
# Use write, not print which adds an extra space.
- sys.stdout.write(self.shell.separate_out)
- outprompt = 'Out[{}]: '.format(self.shell.execution_count)
+ sys.stdout.write(self.shell.separate_out)
+ outprompt = 'Out[{}]: '.format(self.shell.execution_count)
if self.do_full_cache:
- sys.stdout.write(outprompt)
+ sys.stdout.write(outprompt)
def compute_format_data(self, result):
"""Compute format data of the object to be displayed.
@@ -149,14 +149,14 @@ class DisplayHook(Configurable):
"""
return self.shell.display_formatter.format(result)
- # This can be set to True by the write_output_prompt method in a subclass
- prompt_end_newline = False
-
+ # This can be set to True by the write_output_prompt method in a subclass
+ prompt_end_newline = False
+
def write_format_data(self, format_dict, md_dict=None):
"""Write the format data dict to the frontend.
This default version of this method simply writes the plain text
- representation of the object to ``sys.stdout``. Subclasses should
+ representation of the object to ``sys.stdout``. Subclasses should
override this method to send the entire `format_dict` to the
frontends.
@@ -182,11 +182,11 @@ class DisplayHook(Configurable):
# because the expansion may add ANSI escapes that will interfere
# with our ability to determine whether or not we should add
# a newline.
- if not self.prompt_end_newline:
+ if not self.prompt_end_newline:
# But avoid extraneous empty lines.
result_repr = '\n' + result_repr
- print(result_repr)
+ print(result_repr)
def update_user_ns(self, result):
"""Update user_ns with various things like _, __, _1, etc."""
@@ -230,8 +230,8 @@ class DisplayHook(Configurable):
def finish_displayhook(self):
"""Finish up all displayhook activities."""
- sys.stdout.write(self.shell.separate_out2)
- sys.stdout.flush()
+ sys.stdout.write(self.shell.separate_out2)
+ sys.stdout.flush()
def __call__(self, result=None):
"""Printing with history cache management.
diff --git a/contrib/python/ipython/py2/IPython/core/displaypub.py b/contrib/python/ipython/py2/IPython/core/displaypub.py
index cd7be5797e..82a859ae15 100644
--- a/contrib/python/ipython/py2/IPython/core/displaypub.py
+++ b/contrib/python/ipython/py2/IPython/core/displaypub.py
@@ -17,8 +17,8 @@ spec.
from __future__ import print_function
-import sys
-
+import sys
+
from traitlets.config.configurable import Configurable
from traitlets import List
@@ -105,16 +105,16 @@ class DisplayPublisher(Configurable):
transient = kwargs.pop('transient', None)
update = kwargs.pop('update', False)
- # The default is to simply write the plain text data using sys.stdout.
+ # The default is to simply write the plain text data using sys.stdout.
if 'text/plain' in data:
- print(data['text/plain'])
+ print(data['text/plain'])
def clear_output(self, wait=False):
"""Clear the output of the cell receiving output."""
- print('\033[2K\r', end='')
- sys.stdout.flush()
- print('\033[2K\r', end='')
- sys.stderr.flush()
+ print('\033[2K\r', end='')
+ sys.stdout.flush()
+ print('\033[2K\r', end='')
+ sys.stderr.flush()
class CapturingDisplayPublisher(DisplayPublisher):
diff --git a/contrib/python/ipython/py2/IPython/core/events.py b/contrib/python/ipython/py2/IPython/core/events.py
index 776fa191da..bfd09fec6a 100644
--- a/contrib/python/ipython/py2/IPython/core/events.py
+++ b/contrib/python/ipython/py2/IPython/core/events.py
@@ -69,7 +69,7 @@ class EventManager(object):
Any additional arguments are passed to all callbacks registered for this
event. Exceptions raised by callbacks are caught, and a message printed.
"""
- for func in self.callbacks[event][:]:
+ for func in self.callbacks[event][:]:
try:
func(*args, **kwargs)
except Exception:
diff --git a/contrib/python/ipython/py2/IPython/core/excolors.py b/contrib/python/ipython/py2/IPython/core/excolors.py
index de46ac13a5..487bde18c8 100644
--- a/contrib/python/ipython/py2/IPython/core/excolors.py
+++ b/contrib/python/ipython/py2/IPython/core/excolors.py
@@ -19,7 +19,7 @@ def exception_colors():
"""Return a color table with fields for exception reporting.
The table is an instance of ColorSchemeTable with schemes added for
- 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
+ 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
in.
Examples:
@@ -128,41 +128,41 @@ def exception_colors():
Normal = C.Normal,
))
- ex_colors.add_scheme(ColorScheme(
- 'Neutral',
- # The color to be used for the top line
- topline = C.Red,
-
- # The colors to be used in the traceback
- filename = C.LightGreen,
- lineno = C.LightGreen,
- name = C.LightPurple,
- vName = C.Cyan,
- val = C.LightGreen,
- em = C.Cyan,
-
- # Emphasized colors for the last frame of the traceback
- normalEm = C.Cyan,
- filenameEm = C.Green,
- linenoEm = C.Green,
- nameEm = C.Purple,
- valEm = C.Blue,
-
- # Colors for printing the exception
- excName = C.Red,
- #line = C.Brown, # brown often is displayed as yellow
- line = C.Red,
- caret = C.Normal,
- Normal = C.Normal,
- ))
-
+ ex_colors.add_scheme(ColorScheme(
+ 'Neutral',
+ # The color to be used for the top line
+ topline = C.Red,
+
+ # The colors to be used in the traceback
+ filename = C.LightGreen,
+ lineno = C.LightGreen,
+ name = C.LightPurple,
+ vName = C.Cyan,
+ val = C.LightGreen,
+ em = C.Cyan,
+
+ # Emphasized colors for the last frame of the traceback
+ normalEm = C.Cyan,
+ filenameEm = C.Green,
+ linenoEm = C.Green,
+ nameEm = C.Purple,
+ valEm = C.Blue,
+
+ # Colors for printing the exception
+ excName = C.Red,
+ #line = C.Brown, # brown often is displayed as yellow
+ line = C.Red,
+ caret = C.Normal,
+ Normal = C.Normal,
+ ))
+
# Hack: the 'neutral' colours are not very visible on a dark background on
# Windows. Since Windows command prompts have a dark background by default, and
# relatively few users are likely to alter that, we will use the 'Linux' colours,
# designed for a dark background, as the default on Windows.
if os.name == "nt":
ex_colors.add_scheme(ex_colors['Linux'].copy('Neutral'))
-
+
return ex_colors
class Deprec(object):
diff --git a/contrib/python/ipython/py2/IPython/core/extensions.py b/contrib/python/ipython/py2/IPython/core/extensions.py
index 81c5de462d..58855466f1 100644
--- a/contrib/python/ipython/py2/IPython/core/extensions.py
+++ b/contrib/python/ipython/py2/IPython/core/extensions.py
@@ -36,7 +36,7 @@ class ExtensionManager(Configurable):
the only argument. You can do anything you want with IPython at
that point, including defining new magic and aliases, adding new
components, etc.
-
+
You can also optionally define an :func:`unload_ipython_extension(ipython)`
function, which will be called if the user unloads or reloads the extension.
The extension manager will only call :func:`load_ipython_extension` again
@@ -49,12 +49,12 @@ class ExtensionManager(Configurable):
is added to ``sys.path`` automatically.
"""
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs):
super(ExtensionManager, self).__init__(shell=shell, **kwargs)
- self.shell.observe(
- self._on_ipython_dir_changed, names=('ipython_dir',)
+ self.shell.observe(
+ self._on_ipython_dir_changed, names=('ipython_dir',)
)
self.loaded = set()
@@ -62,7 +62,7 @@ class ExtensionManager(Configurable):
def ipython_extension_dir(self):
return os.path.join(self.shell.ipython_dir, u'extensions')
- def _on_ipython_dir_changed(self, change):
+ def _on_ipython_dir_changed(self, change):
ensure_dir_exists(self.ipython_extension_dir)
def load_extension(self, module_str):
@@ -74,7 +74,7 @@ class ExtensionManager(Configurable):
"""
if module_str in self.loaded:
return "already loaded"
-
+
with self.shell.builtin_trap:
if module_str not in sys.modules:
try:
@@ -92,14 +92,14 @@ class ExtensionManager(Configurable):
This function looks up the extension's name in ``sys.modules`` and
simply calls ``mod.unload_ipython_extension(self)``.
-
+
Returns the string "no unload function" if the extension doesn't define
a function to unload itself, "not loaded" if the extension isn't loaded,
otherwise None.
"""
if module_str not in self.loaded:
return "not loaded"
-
+
if module_str in sys.modules:
mod = sys.modules[module_str]
if self._call_unload_ipython_extension(mod):
@@ -138,7 +138,7 @@ class ExtensionManager(Configurable):
return True
def install_extension(self, url, filename=None):
- """Download and install an IPython extension.
+ """Download and install an IPython extension.
If filename is given, the file will be so named (inside the extension
directory). Otherwise, the name from the URL will be used. The file must
diff --git a/contrib/python/ipython/py2/IPython/core/formatters.py b/contrib/python/ipython/py2/IPython/core/formatters.py
index 06af83c1a9..d990619f27 100644
--- a/contrib/python/ipython/py2/IPython/core/formatters.py
+++ b/contrib/python/ipython/py2/IPython/core/formatters.py
@@ -21,12 +21,12 @@ from decorator import decorator
from traitlets.config.configurable import Configurable
from IPython.core.getipython import get_ipython
from IPython.utils.sentinel import Sentinel
-from IPython.utils.dir2 import get_real_method
+from IPython.utils.dir2 import get_real_method
from IPython.lib import pretty
from traitlets import (
Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
ForwardDeclaredInstance,
- default, observe,
+ default, observe,
)
from IPython.utils.py3compat import (
with_metaclass, string_types, unicode_type,
@@ -35,28 +35,28 @@ from IPython.utils.py3compat import (
class DisplayFormatter(Configurable):
- active_types = List(Unicode(),
+ active_types = List(Unicode(),
help="""List of currently active mime-types to display.
You can use this to set a white-list for formats to display.
Most users will not need to change this value.
- """).tag(config=True)
-
- @default('active_types')
+ """).tag(config=True)
+
+ @default('active_types')
def _active_types_default(self):
return self.format_types
-
- @observe('active_types')
- def _active_types_changed(self, change):
+
+ @observe('active_types')
+ def _active_types_changed(self, change):
for key, formatter in self.formatters.items():
- if key in change['new']:
+ if key in change['new']:
formatter.enabled = True
else:
formatter.enabled = False
ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
- @default('ipython_display_formatter')
- def _default_formatter(self):
+ @default('ipython_display_formatter')
+ def _default_formatter(self):
return IPythonDisplayFormatter(parent=self)
mimebundle_formatter = ForwardDeclaredInstance('FormatterABC')
@@ -67,7 +67,7 @@ class DisplayFormatter(Configurable):
# A dict of formatter whose keys are format types (MIME types) and whose
# values are subclasses of BaseFormatter.
formatters = Dict()
- @default('formatters')
+ @default('formatters')
def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
@@ -305,21 +305,21 @@ class BaseFormatter(Configurable):
format_type = Unicode('text/plain')
_return_type = string_types
- enabled = Bool(True).tag(config=True)
+ enabled = Bool(True).tag(config=True)
print_method = ObjectName('__repr__')
# The singleton printers.
# Maps the IDs of the builtin singleton objects to the format functions.
- singleton_printers = Dict().tag(config=True)
+ singleton_printers = Dict().tag(config=True)
# The type-specific printers.
# Map type objects to the format functions.
- type_printers = Dict().tag(config=True)
+ type_printers = Dict().tag(config=True)
# The deferred-import type-specific printers.
# Map (modulename, classname) pairs to the format functions.
- deferred_printers = Dict().tag(config=True)
+ deferred_printers = Dict().tag(config=True)
@catch_format_error
def __call__(self, obj):
@@ -333,7 +333,7 @@ class BaseFormatter(Configurable):
else:
return printer(obj)
# Finally look for special method names
- method = get_real_method(obj, self.print_method)
+ method = get_real_method(obj, self.print_method)
if method is not None:
return method()
return None
@@ -586,37 +586,37 @@ class PlainTextFormatter(BaseFormatter):
# This subclass ignores this attribute as it always need to return
# something.
- enabled = Bool(True).tag(config=False)
+ enabled = Bool(True).tag(config=False)
- max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
+ max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
Set to 0 to disable truncation.
"""
- ).tag(config=True)
+ ).tag(config=True)
# Look for a _repr_pretty_ methods to use for pretty printing.
print_method = ObjectName('_repr_pretty_')
# Whether to pretty-print or not.
- pprint = Bool(True).tag(config=True)
+ pprint = Bool(True).tag(config=True)
# Whether to be verbose or not.
- verbose = Bool(False).tag(config=True)
+ verbose = Bool(False).tag(config=True)
# The maximum width.
- max_width = Integer(79).tag(config=True)
+ max_width = Integer(79).tag(config=True)
# The newline character.
- newline = Unicode('\n').tag(config=True)
+ newline = Unicode('\n').tag(config=True)
# format-string for pprinting floats
float_format = Unicode('%r')
# setter for float precision, either int or direct format-string
- float_precision = CUnicode('').tag(config=True)
+ float_precision = CUnicode('').tag(config=True)
- @observe('float_precision')
- def _float_precision_changed(self, change):
+ @observe('float_precision')
+ def _float_precision_changed(self, change):
"""float_precision changed, set float_format accordingly.
float_precision can be set by int or str.
@@ -630,7 +630,7 @@ class PlainTextFormatter(BaseFormatter):
This parameter can be set via the '%precision' magic.
"""
- new = change['new']
+ new = change['new']
if '%' in new:
# got explicit format string
fmt = new
@@ -663,17 +663,17 @@ class PlainTextFormatter(BaseFormatter):
self.float_format = fmt
# Use the default pretty printers from IPython.lib.pretty.
- @default('singleton_printers')
+ @default('singleton_printers')
def _singleton_printers_default(self):
return pretty._singleton_pprinters.copy()
- @default('type_printers')
+ @default('type_printers')
def _type_printers_default(self):
d = pretty._type_pprinters.copy()
d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
return d
- @default('deferred_printers')
+ @default('deferred_printers')
def _deferred_printers_default(self):
return pretty._deferred_type_pprinters.copy()
@@ -910,7 +910,7 @@ class IPythonDisplayFormatter(BaseFormatter):
printer(obj)
return True
# Finally look for special method names
- method = get_real_method(obj, self.print_method)
+ method = get_real_method(obj, self.print_method)
if method is not None:
method()
return True
@@ -1030,7 +1030,7 @@ def format_display_data(obj, include=None, exclude=None):
"""
from IPython.core.interactiveshell import InteractiveShell
- return InteractiveShell.instance().display_formatter.format(
+ return InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
diff --git a/contrib/python/ipython/py2/IPython/core/history.py b/contrib/python/ipython/py2/IPython/core/history.py
index 1e8e227a50..2e7fdbc845 100644
--- a/contrib/python/ipython/py2/IPython/core/history.py
+++ b/contrib/python/ipython/py2/IPython/core/history.py
@@ -1,8 +1,8 @@
""" History related magics and functionality """
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
from __future__ import print_function
import atexit
@@ -18,16 +18,16 @@ except ImportError:
sqlite3 = None
import threading
-from traitlets.config.configurable import LoggingConfigurable
+from traitlets.config.configurable import LoggingConfigurable
from decorator import decorator
from IPython.utils.decorators import undoc
from IPython.paths import locate_profile
from IPython.utils import py3compat
from traitlets import (
Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
- default, observe,
+ default, observe,
)
-from warnings import warn
+from warnings import warn
#-----------------------------------------------------------------------------
# Classes and functions
@@ -72,55 +72,55 @@ else:
class OperationalError(Exception):
"Dummy exception when sqlite could not be imported. Should never occur."
-# use 16kB as threshold for whether a corrupt history db should be saved
-# that should be at least 100 entries or so
-_SAVE_DB_SIZE = 16384
-
+# use 16kB as threshold for whether a corrupt history db should be saved
+# that should be at least 100 entries or so
+_SAVE_DB_SIZE = 16384
+
@decorator
def catch_corrupt_db(f, self, *a, **kw):
"""A decorator which wraps HistoryAccessor method calls to catch errors from
a corrupt SQLite database, move the old database out of the way, and create
a new one.
-
- We avoid clobbering larger databases because this may be triggered due to filesystem issues,
- not just a corrupt file.
+
+ We avoid clobbering larger databases because this may be triggered due to filesystem issues,
+ not just a corrupt file.
"""
try:
return f(self, *a, **kw)
- except (DatabaseError, OperationalError) as e:
- self._corrupt_db_counter += 1
- self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
- if self.hist_file != ':memory:':
- if self._corrupt_db_counter > self._corrupt_db_limit:
- self.hist_file = ':memory:'
- self.log.error("Failed to load history too many times, history will not be saved.")
- elif os.path.isfile(self.hist_file):
- # move the file out of the way
- base, ext = os.path.splitext(self.hist_file)
- size = os.stat(self.hist_file).st_size
- if size >= _SAVE_DB_SIZE:
- # if there's significant content, avoid clobbering
- now = datetime.datetime.now().isoformat().replace(':', '.')
- newpath = base + '-corrupt-' + now + ext
- # don't clobber previous corrupt backups
- for i in range(100):
- if not os.path.isfile(newpath):
- break
- else:
- newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
- else:
- # not much content, possibly empty; don't worry about clobbering
- # maybe we should just delete it?
- newpath = base + '-corrupt' + ext
- os.rename(self.hist_file, newpath)
- self.log.error("History file was moved to %s and a new file created.", newpath)
+ except (DatabaseError, OperationalError) as e:
+ self._corrupt_db_counter += 1
+ self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
+ if self.hist_file != ':memory:':
+ if self._corrupt_db_counter > self._corrupt_db_limit:
+ self.hist_file = ':memory:'
+ self.log.error("Failed to load history too many times, history will not be saved.")
+ elif os.path.isfile(self.hist_file):
+ # move the file out of the way
+ base, ext = os.path.splitext(self.hist_file)
+ size = os.stat(self.hist_file).st_size
+ if size >= _SAVE_DB_SIZE:
+ # if there's significant content, avoid clobbering
+ now = datetime.datetime.now().isoformat().replace(':', '.')
+ newpath = base + '-corrupt-' + now + ext
+ # don't clobber previous corrupt backups
+ for i in range(100):
+ if not os.path.isfile(newpath):
+ break
+ else:
+ newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
+ else:
+ # not much content, possibly empty; don't worry about clobbering
+ # maybe we should just delete it?
+ newpath = base + '-corrupt' + ext
+ os.rename(self.hist_file, newpath)
+ self.log.error("History file was moved to %s and a new file created.", newpath)
self.init_db()
return []
else:
- # Failed with :memory:, something serious is wrong
+ # Failed with :memory:, something serious is wrong
raise
-class HistoryAccessorBase(LoggingConfigurable):
+class HistoryAccessorBase(LoggingConfigurable):
"""An abstract class for History Accessors """
def get_tail(self, n=10, raw=True, output=False, include_latest=False):
@@ -143,13 +143,13 @@ class HistoryAccessor(HistoryAccessorBase):
This is intended for use by standalone history tools. IPython shells use
HistoryManager, below, which is a subclass of this."""
- # counter for init_db retries, so we don't keep trying over and over
- _corrupt_db_counter = 0
- # after two failures, fallback on :memory:
- _corrupt_db_limit = 2
-
+ # counter for init_db retries, so we don't keep trying over and over
+ _corrupt_db_counter = 0
+ # after two failures, fallback on :memory:
+ _corrupt_db_limit = 2
+
# String holding the path to the history file
- hist_file = Unicode(
+ hist_file = Unicode(
help="""Path to file to use for SQLite history database.
By default, IPython will put the history database in the IPython
@@ -161,13 +161,13 @@ class HistoryAccessor(HistoryAccessorBase):
local disk, e.g::
ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
-
- you can also use the specific value `:memory:` (including the colon
- at both end but not the back ticks), to avoid creating an history file.
+
+ you can also use the specific value `:memory:` (including the colon
+ at both end but not the back ticks), to avoid creating an history file.
- """).tag(config=True)
+ """).tag(config=True)
- enabled = Bool(True,
+ enabled = Bool(True,
help="""enable the SQLite history
set enabled=False to disable the SQLite history,
@@ -175,22 +175,22 @@ class HistoryAccessor(HistoryAccessorBase):
and no background saving thread. This may be necessary in some
threaded environments where IPython is embedded.
"""
- ).tag(config=True)
+ ).tag(config=True)
- connection_options = Dict(
+ connection_options = Dict(
help="""Options for configuring the SQLite connection
These options are passed as keyword args to sqlite3.connect
when establishing database conenctions.
"""
- ).tag(config=True)
+ ).tag(config=True)
# The SQLite database
db = Any()
- @observe('db')
- def _db_changed(self, change):
+ @observe('db')
+ def _db_changed(self, change):
"""validate the db, since it can be an Instance of two different types"""
- new = change['new']
+ new = change['new']
connection_types = (DummyDB,)
if sqlite3 is not None:
connection_types = (DummyDB, sqlite3.Connection)
@@ -266,8 +266,8 @@ class HistoryAccessor(HistoryAccessorBase):
(session integer, line integer, output text,
PRIMARY KEY (session, line))""")
self.db.commit()
- # success! reset corrupt db count
- self._corrupt_db_counter = 0
+ # success! reset corrupt db count
+ self._corrupt_db_counter = 0
def writeout_cache(self):
"""Overridden by HistoryManager to dump the cache before certain
@@ -486,7 +486,7 @@ class HistoryManager(HistoryAccessor):
input_hist_raw = List([""])
# A list of directories visited during session
dir_hist = List()
- @default('dir_hist')
+ @default('dir_hist')
def _dir_hist_default(self):
try:
return [py3compat.getcwd()]
@@ -502,13 +502,13 @@ class HistoryManager(HistoryAccessor):
# The number of the current session in the history database
session_number = Integer()
- db_log_output = Bool(False,
+ db_log_output = Bool(False,
help="Should the history database include output? (default: no)"
- ).tag(config=True)
- db_cache_size = Integer(0,
+ ).tag(config=True)
+ db_cache_size = Integer(0,
help="Write to database every x commands (higher values save disk access & power).\n"
"Values of 1 or less effectively disable caching."
- ).tag(config=True)
+ ).tag(config=True)
# The input and output caches
db_input_cache = List()
db_output_cache = List()
diff --git a/contrib/python/ipython/py2/IPython/core/historyapp.py b/contrib/python/ipython/py2/IPython/core/historyapp.py
index d083a78822..d51426d2ca 100644
--- a/contrib/python/ipython/py2/IPython/core/historyapp.py
+++ b/contrib/python/ipython/py2/IPython/core/historyapp.py
@@ -34,17 +34,17 @@ This is an handy alias to `ipython history trim --keep=0`
class HistoryTrim(BaseIPythonApplication):
description = trim_hist_help
- backup = Bool(False,
- help="Keep the old history file as history.sqlite.<N>"
- ).tag(config=True)
+ backup = Bool(False,
+ help="Keep the old history file as history.sqlite.<N>"
+ ).tag(config=True)
- keep = Int(1000,
- help="Number of recent lines to keep in the database."
- ).tag(config=True)
+ keep = Int(1000,
+ help="Number of recent lines to keep in the database."
+ ).tag(config=True)
flags = Dict(dict(
backup = ({'HistoryTrim' : {'backup' : True}},
- backup.help
+ backup.help
)
))
@@ -120,18 +120,18 @@ class HistoryTrim(BaseIPythonApplication):
class HistoryClear(HistoryTrim):
description = clear_hist_help
- keep = Int(0,
+ keep = Int(0,
help="Number of recent lines to keep in the database.")
- force = Bool(False,
- help="Don't prompt user for confirmation"
- ).tag(config=True)
+ force = Bool(False,
+ help="Don't prompt user for confirmation"
+ ).tag(config=True)
flags = Dict(dict(
force = ({'HistoryClear' : {'force' : True}},
- force.help),
+ force.help),
f = ({'HistoryTrim' : {'force' : True}},
- force.help
+ force.help
)
))
aliases = Dict()
diff --git a/contrib/python/ipython/py2/IPython/core/hooks.py b/contrib/python/ipython/py2/IPython/core/hooks.py
index a93bc31627..e6fc84087f 100644
--- a/contrib/python/ipython/py2/IPython/core/hooks.py
+++ b/contrib/python/ipython/py2/IPython/core/hooks.py
@@ -37,7 +37,7 @@ example, you could use a startup file like this::
import os
import subprocess
-import warnings
+import warnings
import sys
from IPython.core.error import TryNext
@@ -84,24 +84,24 @@ def editor(self, filename, linenum=None, wait=True):
import tempfile
def fix_error_editor(self,filename,linenum,column,msg):
- """DEPRECATED
-
- Open the editor at the given filename, linenumber, column and
+ """DEPRECATED
+
+ Open the editor at the given filename, linenumber, column and
show an error message. This is used for correcting syntax errors.
The current implementation only has special support for the VIM editor,
and falls back on the 'editor' hook if VIM is not used.
- Call ip.set_hook('fix_error_editor',yourfunc) to use your own function,
+ Call ip.set_hook('fix_error_editor',yourfunc) to use your own function,
"""
-
- warnings.warn("""
-`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed
-in future versions. It appears to be used only for automatically fixing syntax
-error that has been broken for a few years and has thus been removed. If you
-happend to use this function and still need it please make your voice heard on
+
+ warnings.warn("""
+`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed
+in future versions. It appears to be used only for automatically fixing syntax
+error that has been broken for a few years and has thus been removed. If you
+happend to use this function and still need it please make your voice heard on
the mailing list ipython-dev@python.org , or on the GitHub Issue tracker:
-https://github.com/ipython/ipython/issues/9649 """, UserWarning)
-
+https://github.com/ipython/ipython/issues/9649 """, UserWarning)
+
def vim_quickfix_file():
t = tempfile.NamedTemporaryFile()
t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
diff --git a/contrib/python/ipython/py2/IPython/core/interactiveshell.py b/contrib/python/ipython/py2/IPython/core/interactiveshell.py
index 67b84a6e5f..ad8824b606 100644
--- a/contrib/python/ipython/py2/IPython/core/interactiveshell.py
+++ b/contrib/python/ipython/py2/IPython/core/interactiveshell.py
@@ -31,7 +31,7 @@ from io import open as io_open
from pickleshare import PickleShareDB
from traitlets.config.configurable import SingletonConfigurable
-from IPython.core import oinspect
+from IPython.core import oinspect
from IPython.core import magic
from IPython.core import page
from IPython.core import prefilter
@@ -42,7 +42,7 @@ from IPython.core.autocall import ExitAutocall
from IPython.core.builtin_trap import BuiltinTrap
from IPython.core.events import EventManager, available_events
from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
-from IPython.core.debugger import Pdb
+from IPython.core.debugger import Pdb
from IPython.core.display_trap import DisplayTrap
from IPython.core.displayhook import DisplayHook
from IPython.core.displaypub import DisplayPublisher
@@ -50,14 +50,14 @@ from IPython.core.error import InputRejected, UsageError
from IPython.core.extensions import ExtensionManager
from IPython.core.formatters import DisplayFormatter
from IPython.core.history import HistoryManager
-from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
+from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
from IPython.core.logger import Logger
from IPython.core.macro import Macro
from IPython.core.payload import PayloadManager
from IPython.core.prefilter import PrefilterManager
from IPython.core.profiledir import ProfileDir
from IPython.core.usage import default_banner
-from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
+from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
from IPython.display import display
from IPython.utils import PyColorize
from IPython.utils import io
@@ -67,45 +67,45 @@ from IPython.utils.decorators import undoc
from IPython.utils.io import ask_yes_no
from IPython.utils.ipstruct import Struct
from IPython.paths import get_ipython_dir
-from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
+from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
from IPython.utils.process import system, getoutput
from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
with_metaclass, iteritems)
from IPython.utils.strdispatch import StrDispatch
from IPython.utils.syspathcontext import prepended_to_syspath
-from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
-from IPython.utils.tempdir import TemporaryDirectory
-from traitlets import (
- Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
- observe, default,
-)
-from warnings import warn
-from logging import error
+from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
+from IPython.utils.tempdir import TemporaryDirectory
+from traitlets import (
+ Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
+ observe, default,
+)
+from warnings import warn
+from logging import error
import IPython.core.hooks
-# NoOpContext is deprecated, but ipykernel imports it from here.
-# See https://github.com/ipython/ipykernel/issues/157
-from IPython.utils.contexts import NoOpContext
-
-try:
- import docrepr.sphinxify as sphx
-
- def sphinxify(doc):
- with TemporaryDirectory() as dirname:
- return {
- 'text/html': sphx.sphinxify(doc, dirname),
- 'text/plain': doc
- }
-except ImportError:
- sphinxify = None
-
-
-class ProvisionalWarning(DeprecationWarning):
- """
- Warning class for unstable features
- """
- pass
-
+# NoOpContext is deprecated, but ipykernel imports it from here.
+# See https://github.com/ipython/ipykernel/issues/157
+from IPython.utils.contexts import NoOpContext
+
+try:
+ import docrepr.sphinxify as sphx
+
+ def sphinxify(doc):
+ with TemporaryDirectory() as dirname:
+ return {
+ 'text/html': sphx.sphinxify(doc, dirname),
+ 'text/plain': doc
+ }
+except ImportError:
+ sphinxify = None
+
+
+class ProvisionalWarning(DeprecationWarning):
+ """
+ Warning class for unstable features
+ """
+ pass
+
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
@@ -141,10 +141,10 @@ class SpaceInInput(Exception): pass
def get_default_colors():
- "DEPRECATED"
- warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
- DeprecationWarning, stacklevel=2)
- return 'Neutral'
+ "DEPRECATED"
+ warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
+ DeprecationWarning, stacklevel=2)
+ return 'Neutral'
class SeparateUnicode(Unicode):
@@ -187,28 +187,28 @@ class ExecutionResult(object):
if self.error_in_exec is not None:
raise self.error_in_exec
- def __repr__(self):
- if sys.version_info > (3,):
- name = self.__class__.__qualname__
- else:
- name = self.__class__.__name__
- return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
- (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
+ def __repr__(self):
+ if sys.version_info > (3,):
+ name = self.__class__.__qualname__
+ else:
+ name = self.__class__.__name__
+ return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
+ (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
+
-
class InteractiveShell(SingletonConfigurable):
"""An enhanced, interactive shell for Python."""
_instance = None
-
- ast_transformers = List([], help=
+
+ ast_transformers = List([], help=
"""
A list of ast.NodeTransformer subclass instances, which will be applied
to user input before code is run.
"""
- ).tag(config=True)
+ ).tag(config=True)
- autocall = Enum((0,1,2), default_value=0, help=
+ autocall = Enum((0,1,2), default_value=0, help=
"""
Make IPython automatically call any callable object even if you didn't
type explicit parentheses. For example, 'str 43' becomes 'str(43)'
@@ -217,29 +217,29 @@ class InteractiveShell(SingletonConfigurable):
arguments on the line, and '2' for 'full' autocall, where all callable
objects are automatically called (even if no arguments are present).
"""
- ).tag(config=True)
+ ).tag(config=True)
# TODO: remove all autoindent logic and put into frontends.
# We can't do this yet because even runlines uses the autoindent.
- autoindent = Bool(True, help=
+ autoindent = Bool(True, help=
"""
Autoindent IPython code entered interactively.
"""
- ).tag(config=True)
-
- automagic = Bool(True, help=
+ ).tag(config=True)
+
+ automagic = Bool(True, help=
"""
Enable magic commands to be called without the leading %.
"""
- ).tag(config=True)
-
- banner1 = Unicode(default_banner,
+ ).tag(config=True)
+
+ banner1 = Unicode(default_banner,
help="""The part of the banner to be printed before the profile"""
- ).tag(config=True)
- banner2 = Unicode('',
+ ).tag(config=True)
+ banner2 = Unicode('',
help="""The part of the banner to be printed after the profile"""
- ).tag(config=True)
+ ).tag(config=True)
- cache_size = Integer(1000, help=
+ cache_size = Integer(1000, help=
"""
Set the size of the output cache. The default is 1000, you can
change it permanently in your config file. Setting it to 0 completely
@@ -248,20 +248,20 @@ class InteractiveShell(SingletonConfigurable):
issued). This limit is defined because otherwise you'll spend more
time re-flushing a too small cache than working
"""
- ).tag(config=True)
- color_info = Bool(True, help=
+ ).tag(config=True)
+ color_info = Bool(True, help=
"""
Use colors for displaying information about objects. Because this
information is passed through a pager (like 'less'), and some pagers
get confused with color codes, this capability can be turned off.
"""
- ).tag(config=True)
- colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
- default_value='Neutral',
- help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
- ).tag(config=True)
- debug = Bool(False).tag(config=True)
- deep_reload = Bool(False, help=
+ ).tag(config=True)
+ colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
+ default_value='Neutral',
+ help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
+ ).tag(config=True)
+ debug = Bool(False).tag(config=True)
+ deep_reload = Bool(False, help=
"""
**Deprecated**
@@ -275,47 +275,47 @@ class InteractiveShell(SingletonConfigurable):
deep_reload is off, IPython will use the normal reload(), but
deep_reload will still be available as dreload().
"""
- ).tag(config=True)
- disable_failing_post_execute = Bool(False,
+ ).tag(config=True)
+ disable_failing_post_execute = Bool(False,
help="Don't call post-execute functions that have failed in the past."
- ).tag(config=True)
+ ).tag(config=True)
display_formatter = Instance(DisplayFormatter, allow_none=True)
displayhook_class = Type(DisplayHook)
display_pub_class = Type(DisplayPublisher)
-
- sphinxify_docstring = Bool(False, help=
- """
- Enables rich html representation of docstrings. (This requires the
- docrepr module).
- """).tag(config=True)
-
- @observe("sphinxify_docstring")
- def _sphinxify_docstring_changed(self, change):
- if change['new']:
- warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
-
- enable_html_pager = Bool(False, help=
- """
- (Provisional API) enables html representation in mime bundles sent
- to pagers.
- """).tag(config=True)
-
- @observe("enable_html_pager")
- def _enable_html_pager_changed(self, change):
- if change['new']:
- warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
-
+
+ sphinxify_docstring = Bool(False, help=
+ """
+ Enables rich html representation of docstrings. (This requires the
+ docrepr module).
+ """).tag(config=True)
+
+ @observe("sphinxify_docstring")
+ def _sphinxify_docstring_changed(self, change):
+ if change['new']:
+ warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
+
+ enable_html_pager = Bool(False, help=
+ """
+ (Provisional API) enables html representation in mime bundles sent
+ to pagers.
+ """).tag(config=True)
+
+ @observe("enable_html_pager")
+ def _enable_html_pager_changed(self, change):
+ if change['new']:
+ warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
+
data_pub_class = None
- exit_now = Bool(False)
+ exit_now = Bool(False)
exiter = Instance(ExitAutocall)
- @default('exiter')
+ @default('exiter')
def _exiter_default(self):
return ExitAutocall(self)
# Monotonically increasing execution counter
execution_count = Integer(1)
filename = Unicode("<ipython console>")
- ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
+ ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
# Input splitter, to transform input line by line and detect when a block
# is ready to be executed.
@@ -327,90 +327,90 @@ class InteractiveShell(SingletonConfigurable):
input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
(), {'line_input_checker': False})
- logstart = Bool(False, help=
+ logstart = Bool(False, help=
"""
Start logging to the default log file in overwrite mode.
Use `logappend` to specify a log file to **append** logs to.
"""
- ).tag(config=True)
- logfile = Unicode('', help=
+ ).tag(config=True)
+ logfile = Unicode('', help=
"""
The name of the logfile to use.
"""
- ).tag(config=True)
- logappend = Unicode('', help=
+ ).tag(config=True)
+ logappend = Unicode('', help=
"""
Start logging to the given file in append mode.
Use `logfile` to specify a log file to **overwrite** logs to.
"""
- ).tag(config=True)
+ ).tag(config=True)
object_info_string_level = Enum((0,1,2), default_value=0,
- ).tag(config=True)
- pdb = Bool(False, help=
+ ).tag(config=True)
+ pdb = Bool(False, help=
"""
Automatically call the pdb debugger after every exception.
"""
- ).tag(config=True)
- display_page = Bool(False,
+ ).tag(config=True)
+ display_page = Bool(False,
help="""If True, anything that would be passed to the pager
will be displayed as regular output instead."""
- ).tag(config=True)
+ ).tag(config=True)
# deprecated prompt traits:
-
- prompt_in1 = Unicode('In [\\#]: ',
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
- prompt_in2 = Unicode(' .\\D.: ',
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
- prompt_out = Unicode('Out[\\#]: ',
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
- prompts_pad_left = Bool(True,
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
-
- @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
- def _prompt_trait_changed(self, change):
- name = change['name']
- warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
- name=name)
+
+ prompt_in1 = Unicode('In [\\#]: ',
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+ prompt_in2 = Unicode(' .\\D.: ',
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+ prompt_out = Unicode('Out[\\#]: ',
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+ prompts_pad_left = Bool(True,
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+
+ @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
+ def _prompt_trait_changed(self, change):
+ name = change['name']
+ warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
+ name=name)
)
# protect against weird cases where self.config may not exist:
- show_rewritten_input = Bool(True,
+ show_rewritten_input = Bool(True,
help="Show rewritten input, e.g. for autocall."
- ).tag(config=True)
+ ).tag(config=True)
- quiet = Bool(False).tag(config=True)
+ quiet = Bool(False).tag(config=True)
- history_length = Integer(10000,
- help='Total length of command history'
- ).tag(config=True)
+ history_length = Integer(10000,
+ help='Total length of command history'
+ ).tag(config=True)
- history_load_length = Integer(1000, help=
+ history_load_length = Integer(1000, help=
"""
The number of saved history entries to be loaded
- into the history buffer at startup.
+ into the history buffer at startup.
"""
- ).tag(config=True)
+ ).tag(config=True)
ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
- default_value='last_expr',
+ default_value='last_expr',
help="""
'all', 'last', 'last_expr' or 'none', specifying which nodes should be
- run interactively (displaying output from expressions)."""
- ).tag(config=True)
+ run interactively (displaying output from expressions)."""
+ ).tag(config=True)
# TODO: this part of prompt management should be moved to the frontends.
# Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
- separate_in = SeparateUnicode('\n').tag(config=True)
- separate_out = SeparateUnicode('').tag(config=True)
- separate_out2 = SeparateUnicode('').tag(config=True)
- wildcards_case_sensitive = Bool(True).tag(config=True)
+ separate_in = SeparateUnicode('\n').tag(config=True)
+ separate_out = SeparateUnicode('').tag(config=True)
+ separate_out2 = SeparateUnicode('').tag(config=True)
+ wildcards_case_sensitive = Bool(True).tag(config=True)
xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
- default_value='Context').tag(config=True)
+ default_value='Context').tag(config=True)
# Subcomponents of InteractiveShell
alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
@@ -436,8 +436,8 @@ class InteractiveShell(SingletonConfigurable):
# Tracks any GUI loop loaded for pylab
pylab_gui_select = None
- last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
-
+ last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
+
def __init__(self, ipython_dir=None, profile_dir=None,
user_module=None, user_ns=None,
custom_exceptions=((), None), **kwargs):
@@ -445,9 +445,9 @@ class InteractiveShell(SingletonConfigurable):
# This is where traits with a config_key argument are updated
# from the values on config.
super(InteractiveShell, self).__init__(**kwargs)
- if 'PromptManager' in self.config:
- warn('As of IPython 5.0 `PromptManager` config will have no effect'
- ' and has been replaced by TerminalInteractiveShell.prompts_class')
+ if 'PromptManager' in self.config:
+ warn('As of IPython 5.0 `PromptManager` config will have no effect'
+ ' and has been replaced by TerminalInteractiveShell.prompts_class')
self.configurables = [self]
# These are relatively independent and stateless
@@ -455,7 +455,7 @@ class InteractiveShell(SingletonConfigurable):
self.init_profile_dir(profile_dir)
self.init_instance_attrs()
self.init_environment()
-
+
# Check if we're in a virtualenv, and set up sys.path.
self.init_virtualenv()
@@ -522,12 +522,12 @@ class InteractiveShell(SingletonConfigurable):
#-------------------------------------------------------------------------
# Trait changed handlers
#-------------------------------------------------------------------------
- @observe('ipython_dir')
- def _ipython_dir_changed(self, change):
- ensure_dir_exists(change['new'])
+ @observe('ipython_dir')
+ def _ipython_dir_changed(self, change):
+ ensure_dir_exists(change['new'])
def set_autoindent(self,value=None):
- """Set the autoindent flag.
+ """Set the autoindent flag.
If called with no arguments, it acts as a toggle."""
if value is None:
@@ -598,10 +598,10 @@ class InteractiveShell(SingletonConfigurable):
pyformat = PyColorize.Parser().format
self.pycolorize = lambda src: pyformat(src,'str',self.colors)
- def refresh_style(self):
- # No-op here, used in subclass
- pass
-
+ def refresh_style(self):
+ # No-op here, used in subclass
+ pass
+
def init_pushd_popd_magic(self):
# for pushd/popd management
self.home_dir = get_home_dir()
@@ -653,10 +653,10 @@ class InteractiveShell(SingletonConfigurable):
# override sys.stdout and sys.stderr themselves, you need to do that
# *before* instantiating this class, because io holds onto
# references to the underlying streams.
- # io.std* are deprecated, but don't show our own deprecation warnings
- # during initialization of the deprecated API.
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
+ # io.std* are deprecated, but don't show our own deprecation warnings
+ # during initialization of the deprecated API.
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', DeprecationWarning)
io.stdout = io.IOStream(sys.stdout)
io.stderr = io.IOStream(sys.stderr)
@@ -700,15 +700,15 @@ class InteractiveShell(SingletonConfigurable):
virtualenv was built, and it ignores the --no-site-packages option. A
warning will appear suggesting the user installs IPython in the
virtualenv, but for many cases, it probably works well enough.
-
+
Adapted from code snippets online.
-
+
http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
"""
if 'VIRTUAL_ENV' not in os.environ:
# Not in a virtualenv
return
-
+
# venv detection:
# stdlib venv may symlink sys.executable, so we can't use realpath.
# but others can symlink *to* the venv Python, so we can't just use sys.executable.
@@ -722,15 +722,15 @@ class InteractiveShell(SingletonConfigurable):
if any(p.startswith(p_venv) for p in paths):
# Running properly in the virtualenv, don't need to do anything
return
-
+
warn("Attempting to work in a virtualenv. If you encounter problems, please "
"install IPython inside the virtualenv.")
if sys.platform == "win32":
- virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
+ virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
else:
virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
'python%d.%d' % sys.version_info[:2], 'site-packages')
-
+
import site
sys.path.insert(0, virtual_env)
site.addsitedir(virtual_env)
@@ -765,7 +765,7 @@ class InteractiveShell(SingletonConfigurable):
#-------------------------------------------------------------------------
# Things related to the banner
#-------------------------------------------------------------------------
-
+
@property
def banner(self):
banner = self.banner1
@@ -778,8 +778,8 @@ class InteractiveShell(SingletonConfigurable):
def show_banner(self, banner=None):
if banner is None:
banner = self.banner
- sys.stdout.write(banner)
-
+ sys.stdout.write(banner)
+
#-------------------------------------------------------------------------
# Things related to hooks
#-------------------------------------------------------------------------
@@ -796,10 +796,10 @@ class InteractiveShell(SingletonConfigurable):
# default hooks have priority 100, i.e. low; user hooks should have
# 0-100 priority
self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
-
+
if self.display_page:
self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
-
+
def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
_warn_deprecated=True):
"""set_hook(name,hook) -> sets an internal IPython hook.
@@ -857,13 +857,13 @@ class InteractiveShell(SingletonConfigurable):
def register_post_execute(self, func):
"""DEPRECATED: Use ip.events.register('post_run_cell', func)
-
+
Register a function for calling after code execution.
"""
warn("ip.register_post_execute is deprecated, use "
"ip.events.register('post_run_cell', func) instead.")
self.events.register('post_run_cell', func)
-
+
def _clear_warning_registry(self):
# clear the warning registry, so that different code blocks with
# overlapping line number ranges don't cause spurious suppression of
@@ -877,14 +877,14 @@ class InteractiveShell(SingletonConfigurable):
def new_main_mod(self, filename, modname):
"""Return a new 'main' module object for user code execution.
-
+
``filename`` should be the path of the script which will be run in the
module. Requests with the same filename will get the same module, with
its namespace cleared.
-
+
``modname`` should be the module name - normally either '__main__' or
the basename of the file without the extension.
-
+
When scripts are executed via %run, we must keep a reference to their
__main__ module around so that Python doesn't
clear it, rendering references to module globals useless.
@@ -905,12 +905,12 @@ class InteractiveShell(SingletonConfigurable):
else:
main_mod.__dict__.clear()
main_mod.__name__ = modname
-
+
main_mod.__file__ = filename
# It seems pydoc (and perhaps others) needs any module instance to
# implement a __nonzero__ method
main_mod.__nonzero__ = lambda : True
-
+
return main_mod
def clear_main_mod_cache(self):
@@ -962,7 +962,7 @@ class InteractiveShell(SingletonConfigurable):
'Control auto-activation of pdb at exceptions')
def debugger(self,force=False):
- """Call the pdb debugger.
+ """Call the pdb debugger.
Keywords:
@@ -979,7 +979,7 @@ class InteractiveShell(SingletonConfigurable):
error('No traceback has been produced, nothing to debug.')
return
- self.InteractiveTB.debugger(force=True)
+ self.InteractiveTB.debugger(force=True)
#-------------------------------------------------------------------------
# Things related to IPython's various namespaces
@@ -1063,17 +1063,17 @@ class InteractiveShell(SingletonConfigurable):
'user_local':self.user_ns,
'builtin':builtin_mod.__dict__
}
-
+
@property
def user_global_ns(self):
return self.user_module.__dict__
def prepare_user_module(self, user_module=None, user_ns=None):
"""Prepare the module and namespace in which user code will be run.
-
+
When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
-
+
If only user_module is provided, its __dict__ is used as the namespace.
If only user_ns is provided, a dummy module is created, and user_ns
becomes the global namespace. If both are provided (as they may be
@@ -1096,17 +1096,17 @@ class InteractiveShell(SingletonConfigurable):
user_ns.setdefault("__name__", "__main__")
user_module = DummyMod()
user_module.__dict__ = user_ns
-
+
if user_module is None:
user_module = types.ModuleType("__main__",
doc="Automatically created module for IPython interactive environment")
-
+
# We must ensure that __builtin__ (without the final 's') is always
# available and pointing to the __builtin__ *module*. For more details:
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
user_module.__dict__.setdefault('__builtin__', builtin_mod)
user_module.__dict__.setdefault('__builtins__', builtin_mod)
-
+
if user_ns is None:
user_ns = user_module.__dict__
@@ -1162,7 +1162,7 @@ class InteractiveShell(SingletonConfigurable):
# For more details:
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
ns = dict()
-
+
# make global variables for user access to the histories
ns['_ih'] = self.history_manager.input_hist_parsed
ns['_oh'] = self.history_manager.output_hist
@@ -1177,7 +1177,7 @@ class InteractiveShell(SingletonConfigurable):
# Store myself as the public api!!!
ns['get_ipython'] = self.get_ipython
-
+
ns['exit'] = self.exiter
ns['quit'] = self.exiter
@@ -1191,12 +1191,12 @@ class InteractiveShell(SingletonConfigurable):
# Finally, update the real user's namespace
self.user_ns.update(ns)
-
+
@property
def all_ns_refs(self):
"""Get a list of references to all the namespace dictionaries in which
IPython might store a user-created object.
-
+
Note that this does not include the displayhook, which also caches
objects from the output."""
return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
@@ -1230,9 +1230,9 @@ class InteractiveShell(SingletonConfigurable):
drop_keys.discard('__name__')
for k in drop_keys:
del ns[k]
-
+
self.user_ns_hidden.clear()
-
+
# Restore the user namespaces to minimal usability
self.init_user_ns()
@@ -1261,7 +1261,7 @@ class InteractiveShell(SingletonConfigurable):
raise ValueError("Refusing to delete %s" % varname)
ns_refs = self.all_ns_refs
-
+
if by_name: # Delete by name
for ns in ns_refs:
try:
@@ -1358,11 +1358,11 @@ class InteractiveShell(SingletonConfigurable):
def drop_by_id(self, variables):
"""Remove a dict of variables from the user namespace, if they are the
same as the values in the dictionary.
-
+
This is intended for use by extensions: variables that they've added can
be taken back out if they are unloaded, without removing any that the
user has overwritten.
-
+
Parameters
----------
variables : dict
@@ -1520,20 +1520,20 @@ class InteractiveShell(SingletonConfigurable):
def _inspect(self, meth, oname, namespaces=None, **kw):
"""Generic interface to the inspector system.
- This function is meant to be called by pdef, pdoc & friends.
- """
+ This function is meant to be called by pdef, pdoc & friends.
+ """
info = self._object_find(oname, namespaces)
- docformat = sphinxify if self.sphinxify_docstring else None
+ docformat = sphinxify if self.sphinxify_docstring else None
if info.found:
pmethod = getattr(self.inspector, meth)
- # TODO: only apply format_screen to the plain/text repr of the mime
- # bundle.
- formatter = format_screen if info.ismagic else docformat
+ # TODO: only apply format_screen to the plain/text repr of the mime
+ # bundle.
+ formatter = format_screen if info.ismagic else docformat
if meth == 'pdoc':
pmethod(info.obj, oname, formatter)
elif meth == 'pinfo':
- pmethod(info.obj, oname, formatter, info,
- enable_html_pager=self.enable_html_pager, **kw)
+ pmethod(info.obj, oname, formatter, info,
+ enable_html_pager=self.enable_html_pager, **kw)
else:
pmethod(info.obj, oname)
else:
@@ -1553,18 +1553,18 @@ class InteractiveShell(SingletonConfigurable):
def object_inspect_text(self, oname, detail_level=0):
"""Get object info as formatted text"""
- return self.object_inspect_mime(oname, detail_level)['text/plain']
-
- def object_inspect_mime(self, oname, detail_level=0):
- """Get object info as a mimebundle of formatted representations.
-
- A mimebundle is a dictionary, keyed by mime-type.
- It must always have the key `'text/plain'`.
- """
+ return self.object_inspect_mime(oname, detail_level)['text/plain']
+
+ def object_inspect_mime(self, oname, detail_level=0):
+ """Get object info as a mimebundle of formatted representations.
+
+ A mimebundle is a dictionary, keyed by mime-type.
+ It must always have the key `'text/plain'`.
+ """
with self.builtin_trap:
info = self._object_find(oname)
if info.found:
- return self.inspector._get_info(info.obj, oname, info=info,
+ return self.inspector._get_info(info.obj, oname, info=info,
detail_level=detail_level
)
else:
@@ -1583,8 +1583,8 @@ class InteractiveShell(SingletonConfigurable):
# Things related to exception handling and tracebacks (not debugging)
#-------------------------------------------------------------------------
- debugger_cls = Pdb
-
+ debugger_cls = Pdb
+
def init_traceback_handlers(self, custom_exceptions):
# Syntax error handler.
self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
@@ -1595,8 +1595,8 @@ class InteractiveShell(SingletonConfigurable):
self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
color_scheme='NoColor',
tb_offset = 1,
- check_cache=check_linecache_ipython,
- debugger_cls=self.debugger_cls)
+ check_cache=check_linecache_ipython,
+ debugger_cls=self.debugger_cls)
# The instance will store a pointer to the system-wide exception hook,
# so that runtime code (such as magics) can access it. This is because
@@ -1610,7 +1610,7 @@ class InteractiveShell(SingletonConfigurable):
self.InteractiveTB.set_mode(mode=self.xmode)
def set_custom_exc(self, exc_tuple, handler):
- """set_custom_exc(exc_tuple, handler)
+ """set_custom_exc(exc_tuple, handler)
Set a custom exception handler, which will be called if any of the
exceptions in exc_tuple occur in the mainloop (specifically, in the
@@ -1653,19 +1653,19 @@ class InteractiveShell(SingletonConfigurable):
assert type(exc_tuple)==type(()) , \
"The custom exceptions must be given AS A TUPLE."
- def dummy_handler(self, etype, value, tb, tb_offset=None):
+ def dummy_handler(self, etype, value, tb, tb_offset=None):
print('*** Simple custom exception handler ***')
print('Exception type :',etype)
print('Exception value:',value)
print('Traceback :',tb)
#print 'Source code :','\n'.join(self.buffer)
-
+
def validate_stb(stb):
"""validate structured traceback return type
-
+
return type of CustomTB *should* be a list of strings, but allow
single strings or None, which are harmless.
-
+
This function will *always* return a list of strings,
and will raise a TypeError if stb is inappropriate.
"""
@@ -1688,7 +1688,7 @@ class InteractiveShell(SingletonConfigurable):
else:
def wrapped(self,etype,value,tb,tb_offset=None):
"""wrap CustomTB handler, to protect IPython from user code
-
+
This makes it harder (but not impossible) for custom exception
handlers to crash IPython.
"""
@@ -1698,11 +1698,11 @@ class InteractiveShell(SingletonConfigurable):
except:
# clear custom handler immediately
self.set_custom_exc((), None)
- print("Custom TB Handler failed, unregistering", file=sys.stderr)
+ print("Custom TB Handler failed, unregistering", file=sys.stderr)
# show the exception in handler first
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
- print(self.InteractiveTB.stb2text(stb))
- print("The original exception:")
+ print(self.InteractiveTB.stb2text(stb))
+ print("The original exception:")
stb = self.InteractiveTB.structured_traceback(
(etype,value,tb), tb_offset=tb_offset
)
@@ -1737,10 +1737,10 @@ class InteractiveShell(SingletonConfigurable):
def _get_exc_info(self, exc_tuple=None):
"""get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
-
+
Ensures sys.last_type,value,traceback hold the exc_info we found,
from whichever source.
-
+
raises ValueError if none of these contain any information
"""
if exc_tuple is None:
@@ -1752,10 +1752,10 @@ class InteractiveShell(SingletonConfigurable):
if hasattr(sys, 'last_type'):
etype, value, tb = sys.last_type, sys.last_value, \
sys.last_traceback
-
+
if etype is None:
raise ValueError("No exception to find")
-
+
# Now store the exception info in sys.last_type etc.
# WARNING: these variables are somewhat deprecated and not
# necessarily safe to use in a threaded environment, but tools
@@ -1764,16 +1764,16 @@ class InteractiveShell(SingletonConfigurable):
sys.last_type = etype
sys.last_value = value
sys.last_traceback = tb
-
+
return etype, value, tb
-
+
def show_usage_error(self, exc):
"""Show a short message for UsageErrors
-
+
These are special exceptions that shouldn't show a traceback.
"""
- print("UsageError: %s" % exc, file=sys.stderr)
-
+ print("UsageError: %s" % exc, file=sys.stderr)
+
def get_exception_only(self, exc_tuple=None):
"""
Return as a string (ending with a newline) the exception that
@@ -1800,9 +1800,9 @@ class InteractiveShell(SingletonConfigurable):
try:
etype, value, tb = self._get_exc_info(exc_tuple)
except ValueError:
- print('No traceback available to show.', file=sys.stderr)
+ print('No traceback available to show.', file=sys.stderr)
return
-
+
if issubclass(etype, SyntaxError):
# Though this won't be called by syntax errors in the input
# line, there may be SyntaxError cases with imported code.
@@ -1835,7 +1835,7 @@ class InteractiveShell(SingletonConfigurable):
self._showtraceback(etype, value, stb)
except KeyboardInterrupt:
- print('\n' + self.get_exception_only(), file=sys.stderr)
+ print('\n' + self.get_exception_only(), file=sys.stderr)
def _showtraceback(self, etype, evalue, stb):
"""Actually show a traceback.
@@ -1843,7 +1843,7 @@ class InteractiveShell(SingletonConfigurable):
Subclasses may override this method to put the traceback on a different
place, like a side channel.
"""
- print(self.InteractiveTB.stb2text(stb))
+ print(self.InteractiveTB.stb2text(stb))
def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
@@ -1862,7 +1862,7 @@ class InteractiveShell(SingletonConfigurable):
except:
# Not the format we expect; leave it alone
pass
-
+
stb = self.SyntaxTB.structured_traceback(etype, value, [])
self._showtraceback(etype, value, stb)
@@ -1881,12 +1881,12 @@ class InteractiveShell(SingletonConfigurable):
#-------------------------------------------------------------------------
def init_readline(self):
- """DEPRECATED
-
- Moved to terminal subclass, here only to simplify the init logic."""
+ """DEPRECATED
+
+ Moved to terminal subclass, here only to simplify the init logic."""
# Set a number of methods that depend on readline to be no-op
- warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
- DeprecationWarning, stacklevel=2)
+ warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
+ DeprecationWarning, stacklevel=2)
self.set_custom_completer = no_op
@skip_doctest
@@ -1923,7 +1923,7 @@ class InteractiveShell(SingletonConfigurable):
self.Completer = IPCompleter(shell=self,
namespace=self.user_ns,
global_namespace=self.user_global_ns,
- use_readline=False,
+ use_readline=False,
parent=self,
)
self.configurables.append(self.Completer)
@@ -1941,7 +1941,7 @@ class InteractiveShell(SingletonConfigurable):
self.set_hook('complete_command', reset_completer, str_key = '%reset')
- @skip_doctest_py2
+ @skip_doctest_py2
def complete(self, text, line=None, cursor_pos=None):
"""Return the completed text and a list of completions.
@@ -2020,7 +2020,7 @@ class InteractiveShell(SingletonConfigurable):
self.register_magics = self.magics_manager.register
self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
- m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
+ m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
)
@@ -2040,11 +2040,11 @@ class InteractiveShell(SingletonConfigurable):
# should be split into a prompt manager and displayhook. We probably
# even need a centralize colors management object.
self.magic('colors %s' % self.colors)
-
+
# Defined here so that it's included in the documentation
@functools.wraps(magic.MagicsManager.register_function)
def register_magic_function(self, func, magic_kind='line', magic_name=None):
- self.magics_manager.register_function(func,
+ self.magics_manager.register_function(func,
magic_kind=magic_kind, magic_name=magic_name)
def run_line_magic(self, magic_name, line):
@@ -2083,7 +2083,7 @@ class InteractiveShell(SingletonConfigurable):
def run_cell_magic(self, magic_name, line, cell):
"""Execute the given cell magic.
-
+
Parameters
----------
magic_name : str
@@ -2230,7 +2230,7 @@ class InteractiveShell(SingletonConfigurable):
try:
ec = os.system(cmd)
except KeyboardInterrupt:
- print('\n' + self.get_exception_only(), file=sys.stderr)
+ print('\n' + self.get_exception_only(), file=sys.stderr)
ec = -2
else:
cmd = py3compat.unicode_to_str(cmd)
@@ -2249,11 +2249,11 @@ class InteractiveShell(SingletonConfigurable):
ec = subprocess.call(cmd, shell=True, executable=executable)
except KeyboardInterrupt:
# intercept control-C; a long traceback is not useful here
- print('\n' + self.get_exception_only(), file=sys.stderr)
+ print('\n' + self.get_exception_only(), file=sys.stderr)
ec = 130
if ec > 128:
ec = -(ec - 128)
-
+
# We explicitly do NOT return the subprocess status code, because
# a non-None value would trigger :func:`sys.displayhook` calls.
# Instead, we store the exit_code in user_ns. Note the semantics
@@ -2316,7 +2316,7 @@ class InteractiveShell(SingletonConfigurable):
def init_payload(self):
self.payload_manager = PayloadManager(parent=self)
self.configurables.append(self.payload_manager)
-
+
#-------------------------------------------------------------------------
# Things related to the prefilter
#-------------------------------------------------------------------------
@@ -2347,8 +2347,8 @@ class InteractiveShell(SingletonConfigurable):
if not self.show_rewritten_input:
return
- # This is overridden in TerminalInteractiveShell to use fancy prompts
- print("------> " + cmd)
+ # This is overridden in TerminalInteractiveShell to use fancy prompts
+ print("------> " + cmd)
#-------------------------------------------------------------------------
# Things related to extracting values/expressions from kernel and user_ns
@@ -2356,13 +2356,13 @@ class InteractiveShell(SingletonConfigurable):
def _user_obj_error(self):
"""return simple exception dict
-
+
for use in user_expressions
"""
-
+
etype, evalue, tb = self._get_exc_info()
stb = self.InteractiveTB.get_exception_only(etype, evalue)
-
+
exc_info = {
u'status' : 'error',
u'traceback' : stb,
@@ -2371,13 +2371,13 @@ class InteractiveShell(SingletonConfigurable):
}
return exc_info
-
+
def _format_user_obj(self, obj):
"""format a user object to display dict
-
+
for use in user_expressions
"""
-
+
data, md = self.display_formatter.format(obj)
value = {
'status' : 'ok',
@@ -2385,7 +2385,7 @@ class InteractiveShell(SingletonConfigurable):
'metadata' : md,
}
return value
-
+
def user_expressions(self, expressions):
"""Evaluate a dict of expressions in the user's namespace.
@@ -2404,7 +2404,7 @@ class InteractiveShell(SingletonConfigurable):
out = {}
user_ns = self.user_ns
global_ns = self.user_global_ns
-
+
for key, expr in iteritems(expressions):
try:
value = self._format_user_obj(eval(expr, global_ns, user_ns))
@@ -2475,7 +2475,7 @@ class InteractiveShell(SingletonConfigurable):
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
- with prepended_to_syspath(dname), self.builtin_trap:
+ with prepended_to_syspath(dname), self.builtin_trap:
try:
glob, loc = (where + (None, ))[:2]
py3compat.execfile(
@@ -2532,7 +2532,7 @@ class InteractiveShell(SingletonConfigurable):
# behavior of running a script from the system command line, where
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
-
+
def get_cells():
"""generator for sequence of code blocks to run"""
if fname.endswith('.ipynb'):
@@ -2616,9 +2616,9 @@ class InteractiveShell(SingletonConfigurable):
result = ExecutionResult()
if (not raw_cell) or raw_cell.isspace():
- self.last_execution_succeeded = True
+ self.last_execution_succeeded = True
return result
-
+
if silent:
store_history = False
@@ -2629,7 +2629,7 @@ class InteractiveShell(SingletonConfigurable):
if store_history:
self.execution_count += 1
result.error_before_exec = value
- self.last_execution_succeeded = False
+ self.last_execution_succeeded = False
return result
self.events.trigger('pre_execute')
@@ -2685,10 +2685,10 @@ class InteractiveShell(SingletonConfigurable):
# Compile to bytecode
try:
code_ast = compiler.ast_parse(cell, filename=cell_name)
- except self.custom_exceptions as e:
- etype, value, tb = sys.exc_info()
- self.CustomTB(etype, value, tb)
- return error_before_exec(e)
+ except self.custom_exceptions as e:
+ etype, value, tb = sys.exc_info()
+ self.CustomTB(etype, value, tb)
+ return error_before_exec(e)
except IndentationError as e:
self.showindentationerror()
return error_before_exec(e)
@@ -2710,10 +2710,10 @@ class InteractiveShell(SingletonConfigurable):
# Execute the user code
interactivity = "none" if silent else self.ast_node_interactivity
- has_raised = self.run_ast_nodes(code_ast.body, cell_name,
+ has_raised = self.run_ast_nodes(code_ast.body, cell_name,
interactivity=interactivity, compiler=compiler, result=result)
-
- self.last_execution_succeeded = not has_raised
+
+ self.last_execution_succeeded = not has_raised
# Reset this so later displayed values do not modify the
# ExecutionResult
@@ -2731,16 +2731,16 @@ class InteractiveShell(SingletonConfigurable):
self.execution_count += 1
return result
-
+
def transform_ast(self, node):
"""Apply the AST transformations from self.ast_transformers
-
+
Parameters
----------
node : ast.Node
The root node to be transformed. Typically called with the ast.Module
produced by parsing user input.
-
+
Returns
-------
An ast.Node corresponding to the node it was called with. Note that it
@@ -2758,11 +2758,11 @@ class InteractiveShell(SingletonConfigurable):
except Exception:
warn("AST transformer %r threw an error. It will be unregistered." % transformer)
self.ast_transformers.remove(transformer)
-
+
if self.ast_transformers:
ast.fix_missing_locations(node)
return node
-
+
def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
compiler=compile, result=None):
@@ -2883,7 +2883,7 @@ class InteractiveShell(SingletonConfigurable):
if result is not None:
result.error_in_exec = e
self.showtraceback(exception_only=True)
- warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
+ warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
except self.custom_exceptions:
etype, value, tb = sys.exc_info()
if result is not None:
@@ -2928,17 +2928,17 @@ class InteractiveShell(SingletonConfigurable):
def enable_gui(self, gui=None):
raise NotImplementedError('Implement enable_gui in a subclass')
-
+
def enable_matplotlib(self, gui=None):
"""Enable interactive matplotlib and inline figure support.
-
+
This takes the following steps:
-
+
1. select the appropriate eventloop and matplotlib backend
2. set up matplotlib for interactive use with that backend
3. configure formatters for inline figure display
4. enable the selected gui eventloop
-
+
Parameters
----------
gui : optional, string
@@ -2952,7 +2952,7 @@ class InteractiveShell(SingletonConfigurable):
"""
from IPython.core import pylabtools as pt
gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
-
+
if gui != 'inline':
# If we have our first gui selection, store it
if self.pylab_gui_select is None:
@@ -2962,16 +2962,16 @@ class InteractiveShell(SingletonConfigurable):
print ('Warning: Cannot change to a different GUI toolkit: %s.'
' Using %s instead.' % (gui, self.pylab_gui_select))
gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
-
+
pt.activate_matplotlib(backend)
pt.configure_inline_support(self, backend)
-
+
# Now we must activate the gui pylab wants to use, and fix %run to take
# plot updates into account
self.enable_gui(gui)
self.magics_manager.registry['ExecutionMagics'].default_runner = \
pt.mpl_runner(self.safe_execfile)
-
+
return gui, backend
def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
@@ -2981,7 +2981,7 @@ class InteractiveShell(SingletonConfigurable):
namespace all of numpy and pylab, and configures IPython to correctly
interact with the GUI event loop. The GUI backend to be used can be
optionally selected with the optional ``gui`` argument.
-
+
This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
Parameters
@@ -3001,9 +3001,9 @@ class InteractiveShell(SingletonConfigurable):
This argument is ignored, no welcome message will be displayed.
"""
from IPython.core.pylabtools import import_pylab
-
+
gui, backend = self.enable_matplotlib(gui)
-
+
# We want to prevent the loading of pylab to pollute the user's
# namespace as shown by the %who* magics, so we execute the activation
# code in an empty namespace, and we update *both* user_ns and
@@ -3076,19 +3076,19 @@ class InteractiveShell(SingletonConfigurable):
tmp_file.close()
return filename
- @undoc
+ @undoc
def write(self,data):
- """DEPRECATED: Write a string to the default output"""
- warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
- DeprecationWarning, stacklevel=2)
- sys.stdout.write(data)
+ """DEPRECATED: Write a string to the default output"""
+ warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
+ DeprecationWarning, stacklevel=2)
+ sys.stdout.write(data)
- @undoc
+ @undoc
def write_err(self,data):
- """DEPRECATED: Write a string to the default error output"""
- warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
- DeprecationWarning, stacklevel=2)
- sys.stderr.write(data)
+ """DEPRECATED: Write a string to the default error output"""
+ warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
+ DeprecationWarning, stacklevel=2)
+ sys.stderr.write(data)
def ask_yes_no(self, prompt, default=None, interrupt=None):
if self.quiet:
@@ -3160,8 +3160,8 @@ class InteractiveShell(SingletonConfigurable):
if code:
return code
try:
- if target.startswith(('http://', 'https://')):
- return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
+ if target.startswith(('http://', 'https://')):
+ return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
except UnicodeDecodeError:
if not py_only :
# Deferred import
@@ -3171,7 +3171,7 @@ class InteractiveShell(SingletonConfigurable):
from urllib import urlopen
response = urlopen(target)
return response.read().decode('latin1')
- raise ValueError(("'%s' seem to be unreadable.") % target)
+ raise ValueError(("'%s' seem to be unreadable.") % target)
potential_target = [target]
try :
@@ -3253,11 +3253,11 @@ class InteractiveShell(SingletonConfigurable):
self.restore_sys_module_state()
- # Overridden in terminal subclass to change prompts
- def switch_doctest_mode(self, mode):
- pass
-
-
+ # Overridden in terminal subclass to change prompts
+ def switch_doctest_mode(self, mode):
+ pass
+
+
class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
"""An abstract base class for InteractiveShell."""
diff --git a/contrib/python/ipython/py2/IPython/core/magic.py b/contrib/python/ipython/py2/IPython/core/magic.py
index f3a0b5be33..61a929fd23 100644
--- a/contrib/python/ipython/py2/IPython/core/magic.py
+++ b/contrib/python/ipython/py2/IPython/core/magic.py
@@ -27,8 +27,8 @@ from IPython.utils.ipstruct import Struct
from IPython.utils.process import arg_split
from IPython.utils.py3compat import string_types, iteritems
from IPython.utils.text import dedent
-from traitlets import Bool, Dict, Instance, observe
-from logging import error
+from traitlets import Bool, Dict, Instance, observe
+from logging import error
#-----------------------------------------------------------------------------
# Globals
@@ -298,12 +298,12 @@ class MagicsManager(Configurable):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
- auto_magic = Bool(True, help=
- "Automatically call line magics without requiring explicit % prefix"
- ).tag(config=True)
- @observe('auto_magic')
- def _auto_magic_changed(self, change):
- self.shell.automagic = change['new']
+ auto_magic = Bool(True, help=
+ "Automatically call line magics without requiring explicit % prefix"
+ ).tag(config=True)
+ @observe('auto_magic')
+ def _auto_magic_changed(self, change):
+ self.shell.automagic = change['new']
_auto_status = [
'Automagic is OFF, % prefix IS needed for line magics.',
diff --git a/contrib/python/ipython/py2/IPython/core/magics/auto.py b/contrib/python/ipython/py2/IPython/core/magics/auto.py
index dc229d509b..f87bafdeb1 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/auto.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/auto.py
@@ -1,7 +1,7 @@
"""Implementation of magic functions that control various automatic behaviors.
"""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
@@ -17,7 +17,7 @@ from __future__ import absolute_import
# Our own packages
from IPython.core.magic import Bunch, Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
-from logging import error
+from logging import error
#-----------------------------------------------------------------------------
# Magic implementation classes
diff --git a/contrib/python/ipython/py2/IPython/core/magics/basic.py b/contrib/python/ipython/py2/IPython/core/magics/basic.py
index 529cdd2b65..ca69e2e698 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/basic.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/basic.py
@@ -1,7 +1,7 @@
"""Implementation of basic magic functions."""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
import argparse
import io
@@ -15,8 +15,8 @@ from IPython.utils.text import format_screen, dedent, indent
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.ipstruct import Struct
from IPython.utils.py3compat import unicode_type
-from warnings import warn
-from logging import error
+from warnings import warn
+from logging import error
class MagicsDisplay(object):
@@ -328,7 +328,7 @@ Currently the magic system has the following functions:""",
"""
def color_switch_err(name):
warn('Error changing %s color schemes.\n%s' %
- (name, sys.exc_info()[1]), stacklevel=2)
+ (name, sys.exc_info()[1]), stacklevel=2)
new_scheme = parameter_s.strip()
@@ -338,13 +338,13 @@ Currently the magic system has the following functions:""",
# local shortcut
shell = self.shell
- # Set shell colour scheme
+ # Set shell colour scheme
try:
- shell.colors = new_scheme
- shell.refresh_style()
+ shell.colors = new_scheme
+ shell.refresh_style()
except:
- color_switch_err('shell')
-
+ color_switch_err('shell')
+
# Set exception colors
try:
shell.InteractiveTB.set_colors(scheme = new_scheme)
@@ -458,12 +458,12 @@ Currently the magic system has the following functions:""",
shell.magic('xmode ' + dstore.xmode)
- # mode here is the state before we switch; switch_doctest_mode takes
- # the mode we're switching to.
- shell.switch_doctest_mode(not mode)
-
+ # mode here is the state before we switch; switch_doctest_mode takes
+ # the mode we're switching to.
+ shell.switch_doctest_mode(not mode)
+
# Store new mode and inform
- dstore.mode = bool(not mode)
+ dstore.mode = bool(not mode)
mode_label = ['OFF','ON'][dstore.mode]
print('Doctest mode is:', mode_label)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/code.py b/contrib/python/ipython/py2/IPython/core/magics/code.py
index c91d24c639..4c1a40f197 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/code.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/code.py
@@ -1,7 +1,7 @@
"""Implementation of code management magic functions.
"""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
@@ -32,9 +32,9 @@ from IPython.testing.skipdoctest import skip_doctest
from IPython.utils import py3compat
from IPython.utils.py3compat import string_types
from IPython.utils.contexts import preserve_keys
-from IPython.utils.path import get_py_filename
-from warnings import warn
-from logging import error
+from IPython.utils.path import get_py_filename
+from warnings import warn
+from logging import error
from IPython.utils.text import get_text_list
#-----------------------------------------------------------------------------
@@ -138,37 +138,37 @@ def extract_symbols(code, symbols):
return blocks, not_found
-def strip_initial_indent(lines):
- """For %load, strip indent from lines until finding an unindented line.
-
- https://github.com/ipython/ipython/issues/9775
- """
- indent_re = re.compile(r'\s+')
-
- it = iter(lines)
- first_line = next(it)
- indent_match = indent_re.match(first_line)
-
- if indent_match:
- # First line was indented
- indent = indent_match.group()
- yield first_line[len(indent):]
-
- for line in it:
- if line.startswith(indent):
- yield line[len(indent):]
- else:
- # Less indented than the first line - stop dedenting
- yield line
- break
- else:
- yield first_line
-
- # Pass the remaining lines through without dedenting
- for line in it:
- yield line
-
-
+def strip_initial_indent(lines):
+ """For %load, strip indent from lines until finding an unindented line.
+
+ https://github.com/ipython/ipython/issues/9775
+ """
+ indent_re = re.compile(r'\s+')
+
+ it = iter(lines)
+ first_line = next(it)
+ indent_match = indent_re.match(first_line)
+
+ if indent_match:
+ # First line was indented
+ indent = indent_match.group()
+ yield first_line[len(indent):]
+
+ for line in it:
+ if line.startswith(indent):
+ yield line[len(indent):]
+ else:
+ # Less indented than the first line - stop dedenting
+ yield line
+ break
+ else:
+ yield first_line
+
+ # Pass the remaining lines through without dedenting
+ for line in it:
+ yield line
+
+
class InteractivelyDefined(Exception):
"""Exception for interactively defined variable in magic_edit"""
def __init__(self, index):
@@ -219,7 +219,7 @@ class CodeMagics(Magics):
append = 'a' in opts
mode = 'a' if append else 'w'
ext = u'.ipy' if raw else u'.py'
- fname, codefrom = args[0], " ".join(args[1:])
+ fname, codefrom = args[0], " ".join(args[1:])
if not fname.endswith((u'.py',u'.ipy')):
fname += ext
file_exists = os.path.isfile(fname)
@@ -371,7 +371,7 @@ class CodeMagics(Magics):
lines = contents.split('\n')
slices = extract_code_ranges(ranges)
contents = [lines[slice(*slc)] for slc in slices]
- contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
+ contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
l = len(contents)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/config.py b/contrib/python/ipython/py2/IPython/core/magics/config.py
index 184388f064..9505697791 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/config.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/config.py
@@ -1,7 +1,7 @@
"""Implementation of configuration-related magic functions.
"""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
@@ -20,7 +20,7 @@ import re
# Our own packages
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic
-from logging import error
+from logging import error
#-----------------------------------------------------------------------------
# Magic implementation classes
diff --git a/contrib/python/ipython/py2/IPython/core/magics/display.py b/contrib/python/ipython/py2/IPython/core/magics/display.py
index a0a74a62cc..c4a8f44d9a 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/display.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/display.py
@@ -25,32 +25,32 @@ from IPython.core.magic import (
@magics_class
class DisplayMagics(Magics):
"""Magics for displaying various output types with literals
-
- Defines javascript/latex/svg/html cell magics for writing
+
+ Defines javascript/latex/svg/html cell magics for writing
blocks in those languages, to be rendered in the frontend.
"""
-
+
+ @cell_magic
+ def js(self, line, cell):
+ """Run the cell block of Javascript code
+
+ Alias of `%%javascript`
+ """
+ self.javascript(line, cell)
+
@cell_magic
- def js(self, line, cell):
- """Run the cell block of Javascript code
-
- Alias of `%%javascript`
- """
- self.javascript(line, cell)
-
- @cell_magic
def javascript(self, line, cell):
"""Run the cell block of Javascript code"""
display(Javascript(cell))
-
-
+
+
@cell_magic
def latex(self, line, cell):
"""Render the cell as a block of latex
-
+
The subset of latex which is support depends on the implementation in
- the client. In the Jupyter Notebook, this magic only renders the subset
- of latex defined by MathJax
+ the client. In the Jupyter Notebook, this magic only renders the subset
+ of latex defined by MathJax
[here](https://docs.mathjax.org/en/v2.5-latest/tex.html)."""
display(Latex(cell))
diff --git a/contrib/python/ipython/py2/IPython/core/magics/execution.py b/contrib/python/ipython/py2/IPython/core/magics/execution.py
index 2597cab3fc..3734b0cdae 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/execution.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/execution.py
@@ -5,7 +5,7 @@
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
import ast
import bdb
@@ -28,7 +28,7 @@ except ImportError:
except ImportError:
profile = pstats = None
-from IPython.core import oinspect
+from IPython.core import oinspect
from IPython.core import magic_arguments
from IPython.core import page
from IPython.core.error import UsageError
@@ -42,10 +42,10 @@ from IPython.utils.contexts import preserve_keys
from IPython.utils.capture import capture_output
from IPython.utils.ipstruct import Struct
from IPython.utils.module_paths import find_mod
-from IPython.utils.path import get_py_filename, shellglob
+from IPython.utils.path import get_py_filename, shellglob
from IPython.utils.timing import clock, clock2
-from warnings import warn
-from logging import error
+from warnings import warn
+from logging import error
if PY3:
from io import StringIO
@@ -61,12 +61,12 @@ class TimeitResult(object):
"""
Object returned by the timeit magic with info about the run.
- Contains the following attributes :
+ Contains the following attributes :
- loops: (int) number of loops done per measurement
- repeat: (int) number of times the measurement has been repeated
- best: (float) best execution time / number
- all_runs: (list of float) execution time of each run (in s)
+ loops: (int) number of loops done per measurement
+ repeat: (int) number of times the measurement has been repeated
+ best: (float) best execution time / number
+ all_runs: (list of float) execution time of each run (in s)
compile_time: (float) time of statement compilation (s)
"""
@@ -705,54 +705,54 @@ python-profiler package from non-free.""")
try:
stats = None
- if 'p' in opts:
- stats = self._run_with_profiler(code, opts, code_ns)
- else:
- if 'd' in opts:
- bp_file, bp_line = parse_breakpoint(
- opts.get('b', ['1'])[0], filename)
- self._run_with_debugger(
- code, code_ns, filename, bp_line, bp_file)
+ if 'p' in opts:
+ stats = self._run_with_profiler(code, opts, code_ns)
+ else:
+ if 'd' in opts:
+ bp_file, bp_line = parse_breakpoint(
+ opts.get('b', ['1'])[0], filename)
+ self._run_with_debugger(
+ code, code_ns, filename, bp_line, bp_file)
else:
- if 'm' in opts:
- def run():
- self.shell.safe_run_module(modulename, prog_ns)
+ if 'm' in opts:
+ def run():
+ self.shell.safe_run_module(modulename, prog_ns)
else:
- if runner is None:
- runner = self.default_runner
- if runner is None:
- runner = self.shell.safe_execfile
-
- def run():
- runner(filename, prog_ns, prog_ns,
- exit_ignore=exit_ignore)
-
- if 't' in opts:
- # timed execution
- try:
- nruns = int(opts['N'][0])
- if nruns < 1:
- error('Number of runs must be >=1')
- return
- except (KeyError):
- nruns = 1
- self._run_with_timing(run, nruns)
- else:
- # regular execution
- run()
-
- if 'i' in opts:
- self.shell.user_ns['__name__'] = __name__save
- else:
- # update IPython interactive namespace
-
- # Some forms of read errors on the file may mean the
- # __name__ key was never set; using pop we don't have to
- # worry about a possible KeyError.
- prog_ns.pop('__name__', None)
-
- with preserve_keys(self.shell.user_ns, '__file__'):
- self.shell.user_ns.update(prog_ns)
+ if runner is None:
+ runner = self.default_runner
+ if runner is None:
+ runner = self.shell.safe_execfile
+
+ def run():
+ runner(filename, prog_ns, prog_ns,
+ exit_ignore=exit_ignore)
+
+ if 't' in opts:
+ # timed execution
+ try:
+ nruns = int(opts['N'][0])
+ if nruns < 1:
+ error('Number of runs must be >=1')
+ return
+ except (KeyError):
+ nruns = 1
+ self._run_with_timing(run, nruns)
+ else:
+ # regular execution
+ run()
+
+ if 'i' in opts:
+ self.shell.user_ns['__name__'] = __name__save
+ else:
+ # update IPython interactive namespace
+
+ # Some forms of read errors on the file may mean the
+ # __name__ key was never set; using pop we don't have to
+ # worry about a possible KeyError.
+ prog_ns.pop('__name__', None)
+
+ with preserve_keys(self.shell.user_ns, '__file__'):
+ self.shell.user_ns.update(prog_ns)
finally:
# It's a bit of a mystery why, but __builtins__ can change from
# being a module to becoming a dict missing some key data after
@@ -801,11 +801,11 @@ python-profiler package from non-free.""")
If the break point given by `bp_line` is not valid.
"""
- deb = self.shell.InteractiveTB.pdb
- if not deb:
- self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
- deb = self.shell.InteractiveTB.pdb
-
+ deb = self.shell.InteractiveTB.pdb
+ if not deb:
+ self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
+ deb = self.shell.InteractiveTB.pdb
+
# deb.checkline() fails if deb.curframe exists but is None; it can
# handle it not existing. https://github.com/ipython/ipython/issues/10028
if hasattr(deb, 'curframe'):
diff --git a/contrib/python/ipython/py2/IPython/core/magics/history.py b/contrib/python/ipython/py2/IPython/core/magics/history.py
index d24bfd2a4e..5967591394 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/history.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/history.py
@@ -15,7 +15,7 @@ from __future__ import print_function
# Stdlib
import os
-import sys
+import sys
from io import open as io_open
# Our own packages
@@ -148,7 +148,7 @@ class HistoryMagics(Magics):
# Check if output to specific file was requested.
outfname = args.filename
if not outfname:
- outfile = sys.stdout # default
+ outfile = sys.stdout # default
# We don't want to close stdout at the end!
close_at_end = False
else:
diff --git a/contrib/python/ipython/py2/IPython/core/magics/logging.py b/contrib/python/ipython/py2/IPython/core/magics/logging.py
index 22500f8156..90214ab54a 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/logging.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/logging.py
@@ -18,7 +18,7 @@ import sys
# Our own packages
from IPython.core.magic import Magics, magics_class, line_magic
-from warnings import warn
+from warnings import warn
from IPython.utils.py3compat import str_to_unicode
#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py2/IPython/core/magics/osm.py b/contrib/python/ipython/py2/IPython/core/magics/osm.py
index f48259ee02..352cf2d451 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/osm.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/osm.py
@@ -323,7 +323,7 @@ class OSMagics(Magics):
else:
- opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
+ opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
# jump to previous
if ps == '-':
try:
@@ -437,7 +437,7 @@ class OSMagics(Magics):
"""
dir_s = self.shell.dir_stack
- tgt = os.path.expanduser(parameter_s)
+ tgt = os.path.expanduser(parameter_s)
cwd = py3compat.getcwd().replace(self.shell.home_dir,'~')
if tgt:
self.cd(parameter_s)
@@ -775,8 +775,8 @@ class OSMagics(Magics):
The file will be overwritten unless the -a (--append) flag is specified.
"""
args = magic_arguments.parse_argstring(self.writefile, line)
- filename = os.path.expanduser(args.filename)
-
+ filename = os.path.expanduser(args.filename)
+
if os.path.exists(filename):
if args.append:
print("Appending to %s" % filename)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/pylab.py b/contrib/python/ipython/py2/IPython/core/magics/pylab.py
index 62308d5e49..6c5cd68a59 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/pylab.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/pylab.py
@@ -18,7 +18,7 @@ from traitlets.config.application import Application
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
-from warnings import warn
+from warnings import warn
from IPython.core.pylabtools import backends
#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py2/IPython/core/magics/script.py b/contrib/python/ipython/py2/IPython/core/magics/script.py
index bfcad64919..3fbddc38a8 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/script.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/script.py
@@ -1,8 +1,8 @@
"""Magic functions for running cells in various scripts."""
from __future__ import print_function
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import errno
import os
@@ -19,7 +19,7 @@ from IPython.core.magic import (
from IPython.lib.backgroundjobs import BackgroundJobManager
from IPython.utils import py3compat
from IPython.utils.process import arg_split
-from traitlets import List, Dict, default
+from traitlets import List, Dict, default
#-----------------------------------------------------------------------------
# Magic implementation classes
@@ -68,7 +68,7 @@ class ScriptMagics(Magics):
with a program in a subprocess, and registers a few top-level
magics that call %%script with common interpreters.
"""
- script_magics = List(
+ script_magics = List(
help="""Extra script cell magics to define
This generates simple wrappers of `%%script foo` as `%%foo`.
@@ -76,8 +76,8 @@ class ScriptMagics(Magics):
If you want to add script magics that aren't on your path,
specify them in script_paths
""",
- ).tag(config=True)
- @default('script_magics')
+ ).tag(config=True)
+ @default('script_magics')
def _script_magics_default(self):
"""default to a common list of programs"""
@@ -98,13 +98,13 @@ class ScriptMagics(Magics):
return defaults
- script_paths = Dict(
+ script_paths = Dict(
help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
Only necessary for items in script_magics where the default path will not
find the right interpreter.
"""
- ).tag(config=True)
+ ).tag(config=True)
def __init__(self, shell=None):
super(ScriptMagics, self).__init__(shell=shell)
diff --git a/contrib/python/ipython/py2/IPython/core/oinspect.py b/contrib/python/ipython/py2/IPython/core/oinspect.py
index b11e24e435..55a4efe8c0 100644
--- a/contrib/python/ipython/py2/IPython/core/oinspect.py
+++ b/contrib/python/ipython/py2/IPython/core/oinspect.py
@@ -17,7 +17,7 @@ __all__ = ['Inspector','InspectColors']
# stdlib modules
import inspect
import linecache
-import warnings
+import warnings
import os
from textwrap import dedent
import types
@@ -42,19 +42,19 @@ from IPython.utils.wildcard import list_namespace
from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
from IPython.utils.py3compat import cast_unicode, string_types, PY3
from IPython.utils.signatures import signature
-from IPython.utils.colorable import Colorable
+from IPython.utils.colorable import Colorable
-from pygments import highlight
+from pygments import highlight
try:
# PythonLexer was renamed to Python2Lexer in pygments 2.5
from pygments.lexers import Python2Lexer
except ImportError:
from pygments.lexers import PythonLexer as Python2Lexer
-from pygments.formatters import HtmlFormatter
-
-def pylight(code):
+from pygments.formatters import HtmlFormatter
+
+def pylight(code):
return highlight(code, Python2Lexer(), HtmlFormatter(noclasses=True))
-
+
# builtin docstrings to ignore
_func_call_docstring = types.FunctionType.__call__.__doc__
_object_init_docstring = object.__init__.__doc__
@@ -124,8 +124,8 @@ def getdoc(obj):
It also attempts to call a getdoc() method on the given object. This
allows objects which provide their docstrings via non-standard mechanisms
- (like Pyro proxies) to still be inspected by ipython's ? system.
- """
+ (like Pyro proxies) to still be inspected by ipython's ? system.
+ """
# Allow objects to offer customized documentation via a getdoc method:
try:
ds = obj.getdoc()
@@ -141,7 +141,7 @@ def getdoc(obj):
return py3compat.cast_unicode(docstr, encoding=encoding)
except Exception:
# Harden against an inspect failure, which can occur with
- # extensions modules.
+ # extensions modules.
raise
return None
@@ -376,16 +376,16 @@ def find_source_lines(obj):
return lineno
-class Inspector(Colorable):
+class Inspector(Colorable):
def __init__(self, color_table=InspectColors,
code_color_table=PyColorize.ANSICodeColors,
scheme='NoColor',
- str_detail_level=0,
- parent=None, config=None):
- super(Inspector, self).__init__(parent=parent, config=config)
+ str_detail_level=0,
+ parent=None, config=None):
+ super(Inspector, self).__init__(parent=parent, config=config)
self.color_table = color_table
- self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
+ self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
self.format = self.parser.format
self.str_detail_level = str_detail_level
self.set_active_scheme(scheme)
@@ -438,11 +438,11 @@ class Inspector(Colorable):
if output is None:
self.noinfo('definition header',oname)
else:
- print(header,self.format(output), end=' ')
+ print(header,self.format(output), end=' ')
# In Python 3, all classes are new-style, so they all have __init__.
@skip_doctest_py3
- def pdoc(self, obj, oname='', formatter=None):
+ def pdoc(self, obj, oname='', formatter=None):
"""Print the docstring for any object.
Optional:
@@ -480,7 +480,7 @@ class Inspector(Colorable):
lines = []
ds = getdoc(obj)
if formatter:
- ds = formatter(ds).get('plain/text', ds)
+ ds = formatter(ds).get('plain/text', ds)
if ds:
lines.append(head("Class docstring:"))
lines.append(indent(ds))
@@ -517,7 +517,7 @@ class Inspector(Colorable):
def pfile(self, obj, oname=''):
"""Show the whole file where an object was defined."""
-
+
lineno = find_source_lines(obj)
if lineno is None:
self.noinfo('file', oname)
@@ -553,184 +553,184 @@ class Inspector(Colorable):
title_width = max(len(title) + 2 for title, _ in fields)
for title, content in fields:
if len(content.splitlines()) > 1:
- title = header(title + ':') + '\n'
+ title = header(title + ':') + '\n'
else:
- title = header((title + ':').ljust(title_width))
+ title = header((title + ':').ljust(title_width))
out.append(cast_unicode(title) + cast_unicode(content))
return "\n".join(out)
- def _mime_format(self, text, formatter=None):
- """Return a mime bundle representation of the input text.
-
- - if `formatter` is None, the returned mime bundle has
- a `text/plain` field, with the input text.
- a `text/html` field with a `<pre>` tag containing the input text.
-
- - if `formatter` is not None, it must be a callable transforming the
- input text into a mime bundle. Default values for `text/plain` and
- `text/html` representations are the ones described above.
-
- Note:
-
- Formatters returning strings are supported but this behavior is deprecated.
-
- """
- text = cast_unicode(text)
- defaults = {
- 'text/plain': text,
- 'text/html': '<pre>' + text + '</pre>'
- }
-
- if formatter is None:
- return defaults
- else:
- formatted = formatter(text)
-
- if not isinstance(formatted, dict):
- # Handle the deprecated behavior of a formatter returning
- # a string instead of a mime bundle.
- return {
- 'text/plain': formatted,
- 'text/html': '<pre>' + formatted + '</pre>'
- }
-
- else:
- return dict(defaults, **formatted)
-
-
- def format_mime(self, bundle):
-
- text_plain = bundle['text/plain']
-
- text = ''
- heads, bodies = list(zip(*text_plain))
- _len = max(len(h) for h in heads)
-
- for head, body in zip(heads, bodies):
- body = body.strip('\n')
- delim = '\n' if '\n' in body else ' '
- text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
-
- bundle['text/plain'] = text
- return bundle
-
- def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
- """Retrieve an info dict and format it."""
-
- info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
-
- _mime = {
- 'text/plain': [],
- 'text/html': '',
- }
-
- def append_field(bundle, title, key, formatter=None):
- field = info[key]
- if field is not None:
- formatted_field = self._mime_format(field, formatter)
- bundle['text/plain'].append((title, formatted_field['text/plain']))
- bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
-
- def code_formatter(text):
- return {
- 'text/plain': self.format(text),
- 'text/html': pylight(text)
- }
-
+ def _mime_format(self, text, formatter=None):
+ """Return a mime bundle representation of the input text.
+
+ - if `formatter` is None, the returned mime bundle has
+ a `text/plain` field, with the input text.
+ a `text/html` field with a `<pre>` tag containing the input text.
+
+ - if `formatter` is not None, it must be a callable transforming the
+ input text into a mime bundle. Default values for `text/plain` and
+ `text/html` representations are the ones described above.
+
+ Note:
+
+ Formatters returning strings are supported but this behavior is deprecated.
+
+ """
+ text = cast_unicode(text)
+ defaults = {
+ 'text/plain': text,
+ 'text/html': '<pre>' + text + '</pre>'
+ }
+
+ if formatter is None:
+ return defaults
+ else:
+ formatted = formatter(text)
+
+ if not isinstance(formatted, dict):
+ # Handle the deprecated behavior of a formatter returning
+ # a string instead of a mime bundle.
+ return {
+ 'text/plain': formatted,
+ 'text/html': '<pre>' + formatted + '</pre>'
+ }
+
+ else:
+ return dict(defaults, **formatted)
+
+
+ def format_mime(self, bundle):
+
+ text_plain = bundle['text/plain']
+
+ text = ''
+ heads, bodies = list(zip(*text_plain))
+ _len = max(len(h) for h in heads)
+
+ for head, body in zip(heads, bodies):
+ body = body.strip('\n')
+ delim = '\n' if '\n' in body else ' '
+ text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
+
+ bundle['text/plain'] = text
+ return bundle
+
+ def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
+ """Retrieve an info dict and format it."""
+
+ info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
+
+ _mime = {
+ 'text/plain': [],
+ 'text/html': '',
+ }
+
+ def append_field(bundle, title, key, formatter=None):
+ field = info[key]
+ if field is not None:
+ formatted_field = self._mime_format(field, formatter)
+ bundle['text/plain'].append((title, formatted_field['text/plain']))
+ bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
+
+ def code_formatter(text):
+ return {
+ 'text/plain': self.format(text),
+ 'text/html': pylight(text)
+ }
+
if info['isalias']:
- append_field(_mime, 'Repr', 'string_form')
+ append_field(_mime, 'Repr', 'string_form')
elif info['ismagic']:
- if detail_level > 0:
- append_field(_mime, 'Source', 'source', code_formatter)
+ if detail_level > 0:
+ append_field(_mime, 'Source', 'source', code_formatter)
else:
- append_field(_mime, 'Docstring', 'docstring', formatter)
- append_field(_mime, 'File', 'file')
+ append_field(_mime, 'Docstring', 'docstring', formatter)
+ append_field(_mime, 'File', 'file')
elif info['isclass'] or is_simple_callable(obj):
# Functions, methods, classes
- append_field(_mime, 'Signature', 'definition', code_formatter)
- append_field(_mime, 'Init signature', 'init_definition', code_formatter)
+ append_field(_mime, 'Signature', 'definition', code_formatter)
+ append_field(_mime, 'Init signature', 'init_definition', code_formatter)
if detail_level > 0 and info['source']:
- append_field(_mime, 'Source', 'source', code_formatter)
+ append_field(_mime, 'Source', 'source', code_formatter)
else:
- append_field(_mime, 'Docstring', 'docstring', formatter)
- append_field(_mime, 'Init docstring', 'init_docstring', formatter)
+ append_field(_mime, 'Docstring', 'docstring', formatter)
+ append_field(_mime, 'Init docstring', 'init_docstring', formatter)
- append_field(_mime, 'File', 'file')
- append_field(_mime, 'Type', 'type_name')
+ append_field(_mime, 'File', 'file')
+ append_field(_mime, 'Type', 'type_name')
else:
# General Python objects
append_field(_mime, 'Signature', 'definition', code_formatter)
append_field(_mime, 'Call signature', 'call_def', code_formatter)
- append_field(_mime, 'Type', 'type_name')
+ append_field(_mime, 'Type', 'type_name')
# Base class for old-style instances
if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
- append_field(_mime, 'Base Class', 'base_class')
+ append_field(_mime, 'Base Class', 'base_class')
- append_field(_mime, 'String form', 'string_form')
+ append_field(_mime, 'String form', 'string_form')
# Namespace
if info['namespace'] != 'Interactive':
- append_field(_mime, 'Namespace', 'namespace')
+ append_field(_mime, 'Namespace', 'namespace')
- append_field(_mime, 'Length', 'length')
+ append_field(_mime, 'Length', 'length')
append_field(_mime, 'File', 'file')
# Source or docstring, depending on detail level and whether
# source found.
- if detail_level > 0:
- append_field(_mime, 'Source', 'source', code_formatter)
- else:
- append_field(_mime, 'Docstring', 'docstring', formatter)
-
- append_field(_mime, 'Class docstring', 'class_docstring', formatter)
- append_field(_mime, 'Init docstring', 'init_docstring', formatter)
- append_field(_mime, 'Call docstring', 'call_docstring', formatter)
+ if detail_level > 0:
+ append_field(_mime, 'Source', 'source', code_formatter)
+ else:
+ append_field(_mime, 'Docstring', 'docstring', formatter)
+
+ append_field(_mime, 'Class docstring', 'class_docstring', formatter)
+ append_field(_mime, 'Init docstring', 'init_docstring', formatter)
+ append_field(_mime, 'Call docstring', 'call_docstring', formatter)
-
- return self.format_mime(_mime)
-
- def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
+
+ return self.format_mime(_mime)
+
+ def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
"""Show detailed information about an object.
Optional arguments:
- oname: name of the variable pointing to the object.
- - formatter: callable (optional)
- A special formatter for docstrings.
+ - formatter: callable (optional)
+ A special formatter for docstrings.
+
+ The formatter is a callable that takes a string as an input
+ and returns either a formatted string or a mime type bundle
+ in the form of a dictionnary.
+
+ Although the support of custom formatter returning a string
+ instead of a mime type bundle is deprecated.
- The formatter is a callable that takes a string as an input
- and returns either a formatted string or a mime type bundle
- in the form of a dictionnary.
-
- Although the support of custom formatter returning a string
- instead of a mime type bundle is deprecated.
-
- info: a structure with some information fields which may have been
precomputed already.
- detail_level: if set to 1, more information is given.
"""
- info = self._get_info(obj, oname, formatter, info, detail_level)
- if not enable_html_pager:
- del info['text/html']
- page.page(info)
-
+ info = self._get_info(obj, oname, formatter, info, detail_level)
+ if not enable_html_pager:
+ del info['text/html']
+ page.page(info)
+
def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
- """DEPRECATED. Compute a dict with detailed information about an object.
- """
- if formatter is not None:
- warnings.warn('The `formatter` keyword argument to `Inspector.info`'
- 'is deprecated as of IPython 5.0 and will have no effects.',
- DeprecationWarning, stacklevel=2)
- return self._info(obj, oname=oname, info=info, detail_level=detail_level)
-
- def _info(self, obj, oname='', info=None, detail_level=0):
+ """DEPRECATED. Compute a dict with detailed information about an object.
+ """
+ if formatter is not None:
+ warnings.warn('The `formatter` keyword argument to `Inspector.info`'
+ 'is deprecated as of IPython 5.0 and will have no effects.',
+ DeprecationWarning, stacklevel=2)
+ return self._info(obj, oname=oname, info=info, detail_level=detail_level)
+
+ def _info(self, obj, oname='', info=None, detail_level=0):
"""Compute a dict with detailed information about an object.
Optional arguments:
@@ -774,7 +774,7 @@ class Inspector(Colorable):
out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
string_max = 200 # max size of strings to show (snipped if longer)
- shalf = int((string_max - 5) / 2)
+ shalf = int((string_max - 5) / 2)
if ismagic:
obj_type_name = 'Magic function'
@@ -846,43 +846,43 @@ class Inspector(Colorable):
# Constructor docstring for classes
if inspect.isclass(obj):
out['isclass'] = True
-
- # get the init signature:
+
+ # get the init signature:
try:
- init_def = self._getdef(obj, oname)
+ init_def = self._getdef(obj, oname)
except AttributeError:
- init_def = None
-
- # get the __init__ docstring
- try:
- obj_init = obj.__init__
- except AttributeError:
- init_ds = None
+ init_def = None
+
+ # get the __init__ docstring
+ try:
+ obj_init = obj.__init__
+ except AttributeError:
+ init_ds = None
else:
- if init_def is None:
- # Get signature from init if top-level sig failed.
- # Can happen for built-in types (list, etc.).
- try:
- init_def = self._getdef(obj_init, oname)
- except AttributeError:
- pass
- init_ds = getdoc(obj_init)
+ if init_def is None:
+ # Get signature from init if top-level sig failed.
+ # Can happen for built-in types (list, etc.).
+ try:
+ init_def = self._getdef(obj_init, oname)
+ except AttributeError:
+ pass
+ init_ds = getdoc(obj_init)
# Skip Python's auto-generated docstrings
if init_ds == _object_init_docstring:
init_ds = None
- if init_def:
- out['init_definition'] = init_def
+ if init_def:
+ out['init_definition'] = init_def
+
+ if init_ds:
+ out['init_docstring'] = init_ds
- if init_ds:
- out['init_docstring'] = init_ds
-
# and class docstring for instances:
else:
# reconstruct the function definition and print it:
defln = self._getdef(obj, oname)
if defln:
- out['definition'] = defln
+ out['definition'] = defln
# First, check whether the instance docstring is identical to the
# class one, and print it separately if they don't coincide. In
@@ -915,10 +915,10 @@ class Inspector(Colorable):
# Call form docstring for callable instances
if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
call_def = self._getdef(obj.__call__, oname)
- if call_def and (call_def != out.get('definition')):
+ if call_def and (call_def != out.get('definition')):
# it may never be the case that call def and definition differ,
# but don't include the same signature twice
- out['call_def'] = call_def
+ out['call_def'] = call_def
call_ds = getdoc(obj.__call__)
# Skip Python's auto-generated docstrings
if call_ds == _func_call_docstring:
diff --git a/contrib/python/ipython/py2/IPython/core/page.py b/contrib/python/ipython/py2/IPython/core/page.py
index a9de4f4805..6d213c9f29 100644
--- a/contrib/python/ipython/py2/IPython/core/page.py
+++ b/contrib/python/ipython/py2/IPython/core/page.py
@@ -38,7 +38,7 @@ def display_page(strng, start=0, screen_lines=25):
else:
if start:
strng = u'\n'.join(strng.splitlines()[start:])
- data = { 'text/plain': strng }
+ data = { 'text/plain': strng }
display(data, raw=True)
@@ -56,25 +56,25 @@ def page_dumb(strng, start=0, screen_lines=25):
"""Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and
- mode.
- """
- if isinstance(strng, dict):
- strng = strng.get('text/plain', '')
+ mode.
+ """
+ if isinstance(strng, dict):
+ strng = strng.get('text/plain', '')
out_ln = strng.splitlines()[start:]
screens = chop(out_ln,screen_lines-1)
if len(screens) == 1:
- print(os.linesep.join(screens[0]))
+ print(os.linesep.join(screens[0]))
else:
last_escape = ""
for scr in screens[0:-1]:
hunk = os.linesep.join(scr)
- print(last_escape + hunk)
+ print(last_escape + hunk)
if not page_more():
return
esc_list = esc_re.findall(hunk)
if len(esc_list) > 0:
last_escape = esc_list[-1]
- print(last_escape + os.linesep.join(screens[-1]))
+ print(last_escape + os.linesep.join(screens[-1]))
def _detect_screen_size(screen_lines_def):
"""Attempt to work out the number of lines on the screen.
@@ -192,13 +192,13 @@ def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
try:
screen_lines += _detect_screen_size(screen_lines_def)
except (TypeError, UnsupportedOperation):
- print(str_toprint)
+ print(str_toprint)
return
#print 'numlines',numlines,'screenlines',screen_lines # dbg
if numlines <= screen_lines :
#print '*** normal print' # dbg
- print(str_toprint)
+ print(str_toprint)
else:
# Try to open pager and default to internal one if that fails.
# All failure modes are tagged as 'retval=1', to match the return
@@ -300,7 +300,7 @@ def get_pager_cmd(pager_cmd=None):
Makes some attempts at finding an OS-correct one.
"""
if os.name == 'posix':
- default_pager_cmd = 'less -R' # -R for color control sequences
+ default_pager_cmd = 'less -R' # -R for color control sequences
elif os.name in ['nt','dos']:
default_pager_cmd = 'type'
@@ -309,10 +309,10 @@ def get_pager_cmd(pager_cmd=None):
pager_cmd = os.environ['PAGER']
except:
pager_cmd = default_pager_cmd
-
- if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
- pager_cmd += ' -R'
-
+
+ if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
+ pager_cmd += ' -R'
+
return pager_cmd
@@ -340,13 +340,13 @@ if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
@return: True if need print more lines, False if quit
"""
- sys.stdout.write('---Return to continue, q to quit--- ')
+ sys.stdout.write('---Return to continue, q to quit--- ')
ans = msvcrt.getwch()
if ans in ("q", "Q"):
result = False
else:
result = True
- sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
+ sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
return result
else:
def page_more():
diff --git a/contrib/python/ipython/py2/IPython/core/prefilter.py b/contrib/python/ipython/py2/IPython/core/prefilter.py
index 1f2367fe52..cbed3fd80a 100644
--- a/contrib/python/ipython/py2/IPython/core/prefilter.py
+++ b/contrib/python/ipython/py2/IPython/core/prefilter.py
@@ -6,8 +6,8 @@ Prefilters transform user input before it is exec'd by Python. These
transforms are used to implement additional syntax such as !ls and %magic.
"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
from keyword import iskeyword
import re
@@ -24,7 +24,7 @@ from IPython.core.macro import Macro
from IPython.core.splitinput import LineInfo
from traitlets import (
- List, Integer, Unicode, Bool, Instance, CRegExp
+ List, Integer, Unicode, Bool, Instance, CRegExp
)
#-----------------------------------------------------------------------------
@@ -114,7 +114,7 @@ class PrefilterManager(Configurable):
or :meth:`sort_transformers` method after changing the priority.
"""
- multi_line_specials = Bool(True).tag(config=True)
+ multi_line_specials = Bool(True).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs):
@@ -344,12 +344,12 @@ class PrefilterManager(Configurable):
class PrefilterTransformer(Configurable):
"""Transform a line of user input."""
- priority = Integer(100).tag(config=True)
+ priority = Integer(100).tag(config=True)
# Transformers don't currently use shell or prefilter_manager, but as we
# move away from checkers and handlers, they will need them.
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
- enabled = Bool(True).tag(config=True)
+ enabled = Bool(True).tag(config=True)
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
super(PrefilterTransformer, self).__init__(
@@ -374,10 +374,10 @@ class PrefilterTransformer(Configurable):
class PrefilterChecker(Configurable):
"""Inspect an input line and return a handler for that line."""
- priority = Integer(100).tag(config=True)
+ priority = Integer(100).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
- enabled = Bool(True).tag(config=True)
+ enabled = Bool(True).tag(config=True)
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
super(PrefilterChecker, self).__init__(
@@ -396,8 +396,8 @@ class PrefilterChecker(Configurable):
class EmacsChecker(PrefilterChecker):
- priority = Integer(100).tag(config=True)
- enabled = Bool(False).tag(config=True)
+ priority = Integer(100).tag(config=True)
+ enabled = Bool(False).tag(config=True)
def check(self, line_info):
"Emacs ipython-mode tags certain input lines."
@@ -409,7 +409,7 @@ class EmacsChecker(PrefilterChecker):
class MacroChecker(PrefilterChecker):
- priority = Integer(250).tag(config=True)
+ priority = Integer(250).tag(config=True)
def check(self, line_info):
obj = self.shell.user_ns.get(line_info.ifun)
@@ -421,7 +421,7 @@ class MacroChecker(PrefilterChecker):
class IPyAutocallChecker(PrefilterChecker):
- priority = Integer(300).tag(config=True)
+ priority = Integer(300).tag(config=True)
def check(self, line_info):
"Instances of IPyAutocall in user_ns get autocalled immediately"
@@ -435,7 +435,7 @@ class IPyAutocallChecker(PrefilterChecker):
class AssignmentChecker(PrefilterChecker):
- priority = Integer(600).tag(config=True)
+ priority = Integer(600).tag(config=True)
def check(self, line_info):
"""Check to see if user is assigning to a var for the first time, in
@@ -453,7 +453,7 @@ class AssignmentChecker(PrefilterChecker):
class AutoMagicChecker(PrefilterChecker):
- priority = Integer(700).tag(config=True)
+ priority = Integer(700).tag(config=True)
def check(self, line_info):
"""If the ifun is magic, and automagic is on, run it. Note: normal,
@@ -477,7 +477,7 @@ class AutoMagicChecker(PrefilterChecker):
class PythonOpsChecker(PrefilterChecker):
- priority = Integer(900).tag(config=True)
+ priority = Integer(900).tag(config=True)
def check(self, line_info):
"""If the 'rest' of the line begins with a function call or pretty much
@@ -492,14 +492,14 @@ class PythonOpsChecker(PrefilterChecker):
class AutocallChecker(PrefilterChecker):
- priority = Integer(1000).tag(config=True)
+ priority = Integer(1000).tag(config=True)
- function_name_regexp = CRegExp(re_fun_name,
- help="RegExp to identify potential function names."
- ).tag(config=True)
- exclude_regexp = CRegExp(re_exclude_auto,
- help="RegExp to exclude strings with this start from autocalling."
- ).tag(config=True)
+ function_name_regexp = CRegExp(re_fun_name,
+ help="RegExp to identify potential function names."
+ ).tag(config=True)
+ exclude_regexp = CRegExp(re_exclude_auto,
+ help="RegExp to exclude strings with this start from autocalling."
+ ).tag(config=True)
def check(self, line_info):
"Check if the initial word/function is callable and autocall is on."
diff --git a/contrib/python/ipython/py2/IPython/core/profileapp.py b/contrib/python/ipython/py2/IPython/core/profileapp.py
index 3f9ce97b8b..b8e5fd26ac 100644
--- a/contrib/python/ipython/py2/IPython/core/profileapp.py
+++ b/contrib/python/ipython/py2/IPython/core/profileapp.py
@@ -32,7 +32,7 @@ from IPython.core.profiledir import ProfileDir
from IPython.utils.importstring import import_item
from IPython.paths import get_ipython_dir, get_ipython_package_dir
from IPython.utils import py3compat
-from traitlets import Unicode, Bool, Dict, observe
+from traitlets import Unicode, Bool, Dict, observe
#-----------------------------------------------------------------------------
# Constants
@@ -149,14 +149,14 @@ class ProfileList(Application):
)
))
- ipython_dir = Unicode(get_ipython_dir(),
+ ipython_dir = Unicode(get_ipython_dir(),
help="""
The name of the IPython directory. This directory is used for logging
configuration (through profiles), history storage, etc. The default
is usually $HOME/.ipython. This options can also be specified through
the environment variable IPYTHONDIR.
"""
- ).tag(config=True)
+ ).tag(config=True)
def _print_profiles(self, profiles):
@@ -211,24 +211,24 @@ class ProfileCreate(BaseIPythonApplication):
name = u'ipython-profile'
description = create_help
examples = _create_examples
- auto_create = Bool(True)
+ auto_create = Bool(True)
def _log_format_default(self):
return "[%(name)s] %(message)s"
def _copy_config_files_default(self):
return True
- parallel = Bool(False,
- help="whether to include parallel computing config files"
- ).tag(config=True)
-
- @observe('parallel')
- def _parallel_changed(self, change):
+ parallel = Bool(False,
+ help="whether to include parallel computing config files"
+ ).tag(config=True)
+
+ @observe('parallel')
+ def _parallel_changed(self, change):
parallel_files = [ 'ipcontroller_config.py',
'ipengine_config.py',
'ipcluster_config.py'
]
- if change['new']:
+ if change['new']:
for cf in parallel_files:
self.config_files.append(cf)
else:
diff --git a/contrib/python/ipython/py2/IPython/core/profiledir.py b/contrib/python/ipython/py2/IPython/core/profiledir.py
index e0e754a78f..b777f13da0 100644
--- a/contrib/python/ipython/py2/IPython/core/profiledir.py
+++ b/contrib/python/ipython/py2/IPython/core/profiledir.py
@@ -12,7 +12,7 @@ from traitlets.config.configurable import LoggingConfigurable
from IPython.paths import get_ipython_package_dir
from IPython.utils.path import expand_path, ensure_dir_exists
from IPython.utils import py3compat
-from traitlets import Unicode, Bool, observe
+from traitlets import Unicode, Bool, observe
#-----------------------------------------------------------------------------
# Module errors
@@ -47,18 +47,18 @@ class ProfileDir(LoggingConfigurable):
pid_dir = Unicode(u'')
static_dir = Unicode(u'')
- location = Unicode(u'',
+ location = Unicode(u'',
help="""Set the profile location directly. This overrides the logic used by the
`profile` option.""",
- ).tag(config=True)
+ ).tag(config=True)
_location_isset = Bool(False) # flag for detecting multiply set location
- @observe('location')
- def _location_changed(self, change):
+ @observe('location')
+ def _location_changed(self, change):
if self._location_isset:
raise RuntimeError("Cannot set profile location more than once.")
self._location_isset = True
- new = change['new']
+ new = change['new']
ensure_dir_exists(new)
# ensure config files exist:
@@ -68,7 +68,7 @@ class ProfileDir(LoggingConfigurable):
self.pid_dir = os.path.join(new, self.pid_dir_name)
self.static_dir = os.path.join(new, self.static_dir_name)
self.check_dirs()
-
+
def _mkdir(self, path, mode=None):
"""ensure a directory exists at a given path
@@ -102,13 +102,13 @@ class ProfileDir(LoggingConfigurable):
raise
return True
-
- @observe('log_dir')
- def check_log_dir(self, change=None):
+
+ @observe('log_dir')
+ def check_log_dir(self, change=None):
self._mkdir(self.log_dir)
-
- @observe('startup_dir')
- def check_startup_dir(self, change=None):
+
+ @observe('startup_dir')
+ def check_startup_dir(self, change=None):
self._mkdir(self.startup_dir)
readme = os.path.join(self.startup_dir, 'README')
@@ -118,12 +118,12 @@ class ProfileDir(LoggingConfigurable):
with open(readme, 'wb') as f:
f.write(pkgutil.get_data(__name__, 'profile/README_STARTUP'))
- @observe('security_dir')
- def check_security_dir(self, change=None):
+ @observe('security_dir')
+ def check_security_dir(self, change=None):
self._mkdir(self.security_dir, 0o40700)
- @observe('pid_dir')
- def check_pid_dir(self, change=None):
+ @observe('pid_dir')
+ def check_pid_dir(self, change=None):
self._mkdir(self.pid_dir, 0o40700)
def check_dirs(self):
diff --git a/contrib/python/ipython/py2/IPython/core/prompts.py b/contrib/python/ipython/py2/IPython/core/prompts.py
index cc6bcb721f..7802bc5363 100644
--- a/contrib/python/ipython/py2/IPython/core/prompts.py
+++ b/contrib/python/ipython/py2/IPython/core/prompts.py
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
-"""Being removed
+"""Being removed
"""
-from IPython.utils import py3compat
+from IPython.utils import py3compat
class LazyEvaluate(object):
"""This is used for formatting strings with values that need to be updated
diff --git a/contrib/python/ipython/py2/IPython/core/pylabtools.py b/contrib/python/ipython/py2/IPython/core/pylabtools.py
index ace18b57e8..a1932d8c48 100644
--- a/contrib/python/ipython/py2/IPython/core/pylabtools.py
+++ b/contrib/python/ipython/py2/IPython/core/pylabtools.py
@@ -377,7 +377,7 @@ def configure_inline_support(shell, backend):
from ipykernel.pylab.backend_inline import InlineBackend
except ImportError:
return
- import matplotlib
+ import matplotlib
cfg = InlineBackend.instance(parent=shell)
cfg.shell = shell
@@ -391,9 +391,9 @@ def configure_inline_support(shell, backend):
# Save rcParams that will be overwrittern
shell._saved_rcParams = dict()
for k in cfg.rc:
- shell._saved_rcParams[k] = matplotlib.rcParams[k]
+ shell._saved_rcParams[k] = matplotlib.rcParams[k]
# load inline_rc
- matplotlib.rcParams.update(cfg.rc)
+ matplotlib.rcParams.update(cfg.rc)
new_backend_name = "inline"
else:
from ipykernel.pylab.backend_inline import flush_figures
@@ -402,7 +402,7 @@ def configure_inline_support(shell, backend):
except ValueError:
pass
if hasattr(shell, '_saved_rcParams'):
- matplotlib.rcParams.update(shell._saved_rcParams)
+ matplotlib.rcParams.update(shell._saved_rcParams)
del shell._saved_rcParams
new_backend_name = "other"
diff --git a/contrib/python/ipython/py2/IPython/core/release.py b/contrib/python/ipython/py2/IPython/core/release.py
index 127e59629f..94dea1073b 100644
--- a/contrib/python/ipython/py2/IPython/core/release.py
+++ b/contrib/python/ipython/py2/IPython/core/release.py
@@ -19,11 +19,11 @@ name = 'ipython'
# IPython version information. An empty _version_extra corresponds to a full
# release. 'dev' as a _version_extra string means this is a development
# version
-_version_major = 5
+_version_major = 5
_version_minor = 9
-_version_patch = 0
+_version_patch = 0
_version_extra = '.dev'
-# _version_extra = 'rc1'
+# _version_extra = 'rc1'
_version_extra = '' # Uncomment this for full releases
# release.codename is deprecated in 2.0, will be removed in 3.0
diff --git a/contrib/python/ipython/py2/IPython/core/shellapp.py b/contrib/python/ipython/py2/IPython/core/shellapp.py
index 0684b41880..213648246e 100644
--- a/contrib/python/ipython/py2/IPython/core/shellapp.py
+++ b/contrib/python/ipython/py2/IPython/core/shellapp.py
@@ -24,15 +24,15 @@ from IPython.utils import py3compat
from IPython.utils.contexts import preserve_keys
from IPython.utils.path import filefind
from traitlets import (
- Unicode, Instance, List, Bool, CaselessStrEnum, observe,
+ Unicode, Instance, List, Bool, CaselessStrEnum, observe,
)
-from IPython.terminal import pt_inputhooks
+from IPython.terminal import pt_inputhooks
#-----------------------------------------------------------------------------
# Aliases and Flags
#-----------------------------------------------------------------------------
-gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
+gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
backend_keys = sorted(pylabtools.backends.keys())
backend_keys.insert(0, 'auto')
@@ -102,7 +102,7 @@ shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
class InteractiveShellApp(Configurable):
"""A Mixin for applications that start InteractiveShell instances.
-
+
Provides configurables for loading extensions and executing files
as part of configuring a Shell environment.
@@ -115,73 +115,73 @@ class InteractiveShellApp(Configurable):
- :meth:`init_extensions`
- :meth:`init_code`
"""
- extensions = List(Unicode(),
+ extensions = List(Unicode(),
help="A list of dotted module names of IPython extensions to load."
- ).tag(config=True)
- extra_extension = Unicode('',
+ ).tag(config=True)
+ extra_extension = Unicode('',
help="dotted module name of an IPython extension to load."
- ).tag(config=True)
+ ).tag(config=True)
- reraise_ipython_extension_failures = Bool(False,
+ reraise_ipython_extension_failures = Bool(False,
help="Reraise exceptions encountered loading IPython extensions?",
- ).tag(config=True)
+ ).tag(config=True)
# Extensions that are always loaded (not configurable)
- default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
-
- hide_initial_ns = Bool(True,
+ default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
+
+ hide_initial_ns = Bool(True,
help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
be hidden from tools like %who?"""
- ).tag(config=True)
+ ).tag(config=True)
- exec_files = List(Unicode(),
+ exec_files = List(Unicode(),
help="""List of files to run at IPython startup."""
- ).tag(config=True)
- exec_PYTHONSTARTUP = Bool(True,
+ ).tag(config=True)
+ exec_PYTHONSTARTUP = Bool(True,
help="""Run the file referenced by the PYTHONSTARTUP environment
variable at IPython startup."""
- ).tag(config=True)
- file_to_run = Unicode('',
- help="""A file to be run""").tag(config=True)
+ ).tag(config=True)
+ file_to_run = Unicode('',
+ help="""A file to be run""").tag(config=True)
- exec_lines = List(Unicode(),
+ exec_lines = List(Unicode(),
help="""lines of code to run at IPython startup."""
- ).tag(config=True)
- code_to_run = Unicode('',
+ ).tag(config=True)
+ code_to_run = Unicode('',
help="Execute the given command string."
- ).tag(config=True)
- module_to_run = Unicode('',
+ ).tag(config=True)
+ module_to_run = Unicode('',
help="Run the module as a script."
- ).tag(config=True)
- gui = CaselessStrEnum(gui_keys, allow_none=True,
+ ).tag(config=True)
+ gui = CaselessStrEnum(gui_keys, allow_none=True,
help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
- ).tag(config=True)
+ ).tag(config=True)
matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
help="""Configure matplotlib for interactive use with
the default matplotlib backend."""
- ).tag(config=True)
+ ).tag(config=True)
pylab = CaselessStrEnum(backend_keys, allow_none=True,
help="""Pre-load matplotlib and numpy for interactive use,
selecting a particular matplotlib backend and loop integration.
"""
- ).tag(config=True)
- pylab_import_all = Bool(True,
+ ).tag(config=True)
+ pylab_import_all = Bool(True,
help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
and an ``import *`` is done from numpy and pylab, when using pylab mode.
-
+
When False, pylab mode should not import any names into the user namespace.
"""
- ).tag(config=True)
+ ).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
allow_none=True)
- # whether interact-loop should start
- interact = Bool(True)
-
+ # whether interact-loop should start
+ interact = Bool(True)
+
user_ns = Instance(dict, args=None, allow_none=True)
- @observe('user_ns')
- def _user_ns_changed(self, change):
+ @observe('user_ns')
+ def _user_ns_changed(self, change):
if self.shell is not None:
- self.shell.user_ns = change['new']
+ self.shell.user_ns = change['new']
self.shell.init_user_ns()
def init_path(self):
@@ -205,10 +205,10 @@ class InteractiveShellApp(Configurable):
elif self.gui:
enable = shell.enable_gui
key = self.gui
-
+
if not enable:
return
-
+
try:
r = enable(key)
except ImportError:
@@ -219,7 +219,7 @@ class InteractiveShellApp(Configurable):
self.log.warning("GUI event loop or pylab initialization failed")
self.shell.showtraceback()
return
-
+
if isinstance(r, tuple):
gui, backend = r[:2]
self.log.info("Enabling GUI event loop integration, "
@@ -265,16 +265,16 @@ class InteractiveShellApp(Configurable):
self._run_startup_files()
self._run_exec_lines()
self._run_exec_files()
-
+
# Hide variables defined here from %who etc.
if self.hide_initial_ns:
self.shell.user_ns_hidden.update(self.shell.user_ns)
-
+
# command-line execution (ipython -i script.py, ipython -m module)
# should *not* be excluded from %whos
self._run_cmd_line_code()
self._run_module()
-
+
# flush output, so itwon't be attached to the first cell
sys.stdout.flush()
sys.stderr.flush()
@@ -301,7 +301,7 @@ class InteractiveShellApp(Configurable):
def _exec_file(self, fname, shell_futures=False):
try:
full_filename = filefind(fname, [u'.', self.ipython_dir])
- except IOError:
+ except IOError:
self.log.warning("File not found: %r"%fname)
return
# Make sure that the running script gets a proper sys.argv as if it
@@ -337,7 +337,7 @@ class InteractiveShellApp(Configurable):
os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
]
startup_files = []
-
+
if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
not (self.file_to_run or self.code_to_run or self.module_to_run):
python_startup = os.environ['PYTHONSTARTUP']
@@ -352,7 +352,7 @@ class InteractiveShellApp(Configurable):
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
if not startup_files:
return
-
+
self.log.debug("Running startup files from %s...", startup_dir)
try:
for fname in sorted(startup_files):
@@ -386,20 +386,20 @@ class InteractiveShellApp(Configurable):
self.log.warning("Error in executing line in user namespace: %s" %
line)
self.shell.showtraceback()
- if not self.interact:
- self.exit(1)
+ if not self.interact:
+ self.exit(1)
# Like Python itself, ignore the second if the first of these is present
elif self.file_to_run:
fname = self.file_to_run
- if os.path.isdir(fname):
- fname = os.path.join(fname, "__main__.py")
+ if os.path.isdir(fname):
+ fname = os.path.join(fname, "__main__.py")
try:
self._exec_file(fname, shell_futures=True)
except:
self.shell.showtraceback(tb_offset=4)
- if not self.interact:
- self.exit(1)
+ if not self.interact:
+ self.exit(1)
def _run_module(self):
"""Run module specified at the command-line."""
diff --git a/contrib/python/ipython/py2/IPython/core/ultratb.py b/contrib/python/ipython/py2/IPython/core/ultratb.py
index f327943eb8..a855145825 100644
--- a/contrib/python/ipython/py2/IPython/core/ultratb.py
+++ b/contrib/python/ipython/py2/IPython/core/ultratb.py
@@ -38,12 +38,12 @@ Give it a shot--you'll love it or you'll hate it.
variables (but otherwise includes the information and context given by
Verbose).
-.. note::
+.. note::
+
+ The verbose mode print all variables in the stack, which means it can
+ potentially leak sensitive information like access keys, or unencryted
+ password.
- The verbose mode print all variables in the stack, which means it can
- potentially leak sensitive information like access keys, or unencryted
- password.
-
Installation instructions for VerboseTB::
import sys,ultratb
@@ -67,9 +67,9 @@ ColorSchemeTable class. Currently the following exist:
- LightBG: similar to Linux but swaps dark/light colors to be more readable
in light background terminals.
- - Neutral: a neutral color scheme that should be readable on both light and
- dark background
-
+ - Neutral: a neutral color scheme that should be readable on both light and
+ dark background
+
You can implement other color schemes easily, the syntax is fairly
self-explanatory. Please send back new schemes you develop to the author for
possible inclusion in future releases.
@@ -88,7 +88,7 @@ Inheritance diagram:
# the file COPYING, distributed as part of this software.
#*****************************************************************************
-from __future__ import absolute_import
+from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
@@ -125,11 +125,11 @@ from IPython.utils import path as util_path
from IPython.utils import py3compat
from IPython.utils import ulinecache
from IPython.utils.data import uniq_stable
-from IPython.utils.terminal import get_terminal_size
-from logging import info, error
+from IPython.utils.terminal import get_terminal_size
+from logging import info, error
+
+import IPython.utils.colorable as colorable
-import IPython.utils.colorable as colorable
-
# Globals
# amount of space to put line numbers before verbose tracebacks
INDENT_SIZE = 8
@@ -226,8 +226,8 @@ def findsource(object):
# the length of lines, which causes an error. Safeguard against that.
lnum = min(object.co_firstlineno, len(lines)) - 1
while lnum > 0:
- if pmatch(lines[lnum]):
- break
+ if pmatch(lines[lnum]):
+ break
lnum -= 1
return lines, lnum
@@ -283,11 +283,11 @@ def getargs(co):
remain.pop()
size = count.pop()
stack[-size:] = [stack[-size:]]
- if not remain:
- break
+ if not remain:
+ break
remain[-1] = remain[-1] - 1
- if not remain:
- break
+ if not remain:
+ break
args[i] = stack[0]
varargs = None
@@ -413,7 +413,7 @@ def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None)
if i == lnum:
# This is the line with the error
pad = numbers_width - len(str(i))
- num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
+ num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
line = '%s%s%s %s%s' % (Colors.linenoEm, num,
Colors.line, line, Colors.Normal)
else:
@@ -481,22 +481,22 @@ def find_recursion(etype, value, records):
#---------------------------------------------------------------------------
# Module classes
-class TBTools(colorable.Colorable):
+class TBTools(colorable.Colorable):
"""Basic tools used by all traceback printer classes."""
# Number of frames to skip when reporting tracebacks
tb_offset = 0
- def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
+ def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
# Whether to call the interactive pdb debugger after printing
# tracebacks or not
- super(TBTools, self).__init__(parent=parent, config=config)
+ super(TBTools, self).__init__(parent=parent, config=config)
self.call_pdb = call_pdb
# Output stream to write to. Note that we store the original value in
# a private attribute and then make the public ostream a property, so
- # that we can delay accessing sys.stdout until runtime. The way
- # things are written now, the sys.stdout object is dynamically managed
+ # that we can delay accessing sys.stdout until runtime. The way
+ # things are written now, the sys.stdout object is dynamically managed
# so a reference to it should NEVER be stored statically. This
# property approach confines this detail to a single location, and all
# subclasses can simply access self.ostream for writing.
@@ -509,7 +509,7 @@ class TBTools(colorable.Colorable):
self.old_scheme = color_scheme # save initial value for toggles
if call_pdb:
- self.pdb = debugger.Pdb()
+ self.pdb = debugger.Pdb()
else:
self.pdb = None
@@ -519,12 +519,12 @@ class TBTools(colorable.Colorable):
Valid values are:
- None: the default, which means that IPython will dynamically resolve
- to sys.stdout. This ensures compatibility with most tools, including
+ to sys.stdout. This ensures compatibility with most tools, including
Windows (where plain stdout doesn't recognize ANSI escapes).
- Any object with 'write' and 'flush' attributes.
"""
- return sys.stdout if self._ostream is None else self._ostream
+ return sys.stdout if self._ostream is None else self._ostream
def _set_ostream(self, val):
assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
@@ -596,9 +596,9 @@ class ListTB(TBTools):
Because they are meant to be called without a full traceback (only a
list), instances of this class can't call the interactive pdb debugger."""
- def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
+ def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
- ostream=ostream, parent=parent)
+ ostream=ostream, parent=parent)
def __call__(self, etype, value, elist):
self.ostream.flush()
@@ -711,10 +711,10 @@ class ListTB(TBTools):
have_filedata = False
Colors = self.Colors
list = []
- stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
+ stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
if value is None:
# Not sure if this can still happen in Python 2.6 and above
- list.append(stype + '\n')
+ list.append(stype + '\n')
else:
if issubclass(etype, SyntaxError):
have_filedata = True
@@ -754,10 +754,10 @@ class ListTB(TBTools):
except Exception:
s = self._some_str(value)
if s:
- list.append('%s%s:%s %s\n' % (stype, Colors.excName,
+ list.append('%s%s:%s %s\n' % (stype, Colors.excName,
Colors.Normal, s))
else:
- list.append('%s\n' % stype)
+ list.append('%s\n' % stype)
# sync with user hooks
if have_filedata:
@@ -795,9 +795,9 @@ class ListTB(TBTools):
def _some_str(self, value):
# Lifted from traceback.py
try:
- return py3compat.cast_unicode(str(value))
+ return py3compat.cast_unicode(str(value))
except:
- return u'<unprintable %s object>' % type(value).__name__
+ return u'<unprintable %s object>' % type(value).__name__
#----------------------------------------------------------------------------
@@ -811,7 +811,7 @@ class VerboseTB(TBTools):
def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
tb_offset=0, long_header=False, include_vars=True,
- check_cache=None, debugger_cls = None):
+ check_cache=None, debugger_cls = None):
"""Specify traceback offset, headers and color scheme.
Define how many frames to drop from the tracebacks. Calling it with
@@ -832,8 +832,8 @@ class VerboseTB(TBTools):
check_cache = linecache.checkcache
self.check_cache = check_cache
- self.debugger_cls = debugger_cls or debugger.Pdb
-
+ self.debugger_cls = debugger_cls or debugger.Pdb
+
def format_records(self, records, last_unique, recursion_repeat):
"""Format the stack frames of the traceback"""
frames = []
@@ -929,12 +929,12 @@ class VerboseTB(TBTools):
elif file.endswith(('.pyc', '.pyo')):
# Look up the corresponding source file.
- try:
- file = openpy.source_from_cache(file)
- except ValueError:
- # Failed to get the source file for some reason
- # E.g. https://github.com/ipython/ipython/issues/9486
- return '%s %s\n' % (link, call)
+ try:
+ file = openpy.source_from_cache(file)
+ except ValueError:
+ # Failed to get the source file for some reason
+ # E.g. https://github.com/ipython/ipython/issues/9486
+ return '%s %s\n' % (link, call)
def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
line = getline(file, lnum[0])
@@ -1038,21 +1038,21 @@ class VerboseTB(TBTools):
colors = self.Colors # just a shorthand + quicker name lookup
colorsnormal = colors.Normal # used a lot
exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
- width = min(75, get_terminal_size()[0])
+ width = min(75, get_terminal_size()[0])
if long_version:
# Header with the exception type, python version, and date
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
- head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
- exc, ' ' * (width - len(str(etype)) - len(pyver)),
- pyver, date.rjust(width) )
+ head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
+ exc, ' ' * (width - len(str(etype)) - len(pyver)),
+ pyver, date.rjust(width) )
head += "\nA problem occurred executing Python code. Here is the sequence of function" \
"\ncalls leading up to the error, with the most recent (innermost) call last."
else:
# Simplified header
head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
- rjust(width - len(str(etype))) )
+ rjust(width - len(str(etype))) )
return head
@@ -1171,7 +1171,7 @@ class VerboseTB(TBTools):
colors = self.Colors # just a shorthand + quicker name lookup
colorsnormal = colors.Normal # used a lot
- head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
+ head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
structured_traceback_parts = [head]
if py3compat.PY3:
chained_exceptions_tb_offset = 0
@@ -1287,7 +1287,7 @@ class FormattedTB(VerboseTB, ListTB):
def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
ostream=None,
tb_offset=0, long_header=False, include_vars=False,
- check_cache=None, debugger_cls=None):
+ check_cache=None, debugger_cls=None):
# NEVER change the order of this list. Put new modes at the end:
self.valid_modes = ['Plain', 'Context', 'Verbose']
@@ -1296,7 +1296,7 @@ class FormattedTB(VerboseTB, ListTB):
VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
ostream=ostream, tb_offset=tb_offset,
long_header=long_header, include_vars=include_vars,
- check_cache=check_cache, debugger_cls=debugger_cls)
+ check_cache=check_cache, debugger_cls=debugger_cls)
# Different types of tracebacks are joined with different separators to
# form a single string. They are taken from this dict
@@ -1446,7 +1446,7 @@ class SyntaxTB(ListTB):
newtext = ulinecache.getline(value.filename, value.lineno)
if newtext:
value.text = newtext
- self.last_syntax_error = value
+ self.last_syntax_error = value
return super(SyntaxTB, self).structured_traceback(etype, value, elist,
tb_offset=tb_offset, context=context)
diff --git a/contrib/python/ipython/py2/IPython/core/usage.py b/contrib/python/ipython/py2/IPython/core/usage.py
index 26506281a7..c4d3c16eca 100644
--- a/contrib/python/ipython/py2/IPython/core/usage.py
+++ b/contrib/python/ipython/py2/IPython/core/usage.py
@@ -114,7 +114,7 @@ MAIN FEATURES
your history for lines that match what you've typed so far, completing as
much as it can.
- - %hist: search history by index.
+ - %hist: search history by index.
* Persistent command history across sessions.
@@ -337,9 +337,9 @@ default_banner_parts = [
default_banner = ''.join(default_banner_parts)
-# deprecated GUI banner
+# deprecated GUI banner
-default_gui_banner = '\n'.join([
- 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed',
- default_banner,
-])
+default_gui_banner = '\n'.join([
+ 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed',
+ default_banner,
+])
diff --git a/contrib/python/ipython/py2/IPython/extensions/storemagic.py b/contrib/python/ipython/py2/IPython/extensions/storemagic.py
index 7de7271772..2fd1abf993 100644
--- a/contrib/python/ipython/py2/IPython/extensions/storemagic.py
+++ b/contrib/python/ipython/py2/IPython/extensions/storemagic.py
@@ -11,8 +11,8 @@ To automatically restore stored variables at startup, add this to your
"""
from __future__ import print_function
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import inspect, os, sys, textwrap
@@ -61,11 +61,11 @@ class StoreMagics(Magics):
Provides the %store magic."""
- autorestore = Bool(False, help=
+ autorestore = Bool(False, help=
"""If True, any %store-d variables will be automatically restored
when IPython starts.
"""
- ).tag(config=True)
+ ).tag(config=True)
def __init__(self, shell):
super(StoreMagics, self).__init__(shell=shell)
diff --git a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
index 34de37d525..ad7bd0f981 100644
--- a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
+++ b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
@@ -85,7 +85,7 @@ class WarningManager:
else:
return None
- def __exit__(self, type_, value, traceback):
+ def __exit__(self, type_, value, traceback):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
self._module.filters = self._filters
@@ -101,8 +101,8 @@ def assert_warns(warning_class, func, *args, **kw):
# XXX: once we may depend on python >= 2.6, this can be replaced by the
# warnings module context manager.
- with WarningManager(record=True) as l:
- warnings.simplefilter('always')
+ with WarningManager(record=True) as l:
+ warnings.simplefilter('always')
func(*args, **kw)
if not len(l) > 0:
raise AssertionError("No warning raised when calling %s"
diff --git a/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py b/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
index 62ae52e94e..b724126bbb 100644
--- a/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
+++ b/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
@@ -36,7 +36,7 @@ import threading
from IPython import get_ipython
from IPython.core.ultratb import AutoFormattedTB
-from logging import error
+from logging import error
from IPython.utils.py3compat import string_types
diff --git a/contrib/python/ipython/py2/IPython/lib/deepreload.py b/contrib/python/ipython/py2/IPython/lib/deepreload.py
index 45efcb45d2..76b493c0bb 100644
--- a/contrib/python/ipython/py2/IPython/lib/deepreload.py
+++ b/contrib/python/ipython/py2/IPython/lib/deepreload.py
@@ -351,11 +351,11 @@ def _dreload(module, **kwargs):
import reload explicitly from `IPython.lib.deepreload` to use it
"""
- # this was marked as deprecated and for 5.0 removal, but
- # IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
- # remove that now.
+ # this was marked as deprecated and for 5.0 removal, but
+ # IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
+ # remove that now.
warn("""
-injecting `dreload` in interactive namespace is deprecated since IPython 4.0.
+injecting `dreload` in interactive namespace is deprecated since IPython 4.0.
Please import `reload` explicitly from `IPython.lib.deepreload`.
""", DeprecationWarning, stacklevel=2)
reload(module, **kwargs)
diff --git a/contrib/python/ipython/py2/IPython/lib/demo.py b/contrib/python/ipython/py2/IPython/lib/demo.py
index 7b047ad82a..b0f3503ed7 100644
--- a/contrib/python/ipython/py2/IPython/lib/demo.py
+++ b/contrib/python/ipython/py2/IPython/lib/demo.py
@@ -326,7 +326,7 @@ class Demo(object):
if index is None:
if self.finished:
- print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
+ print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
return None
index = self.block_index
else:
@@ -397,8 +397,8 @@ class Demo(object):
return
print(self.marquee('<%s> block # %s (%s remaining)' %
- (self.title,index,self.nblocks-index-1)))
- print(self.src_blocks_colored[index])
+ (self.title,index,self.nblocks-index-1)))
+ print(self.src_blocks_colored[index])
sys.stdout.flush()
def show_all(self):
@@ -412,11 +412,11 @@ class Demo(object):
for index,block in enumerate(self.src_blocks_colored):
if silent[index]:
print(marquee('<%s> SILENT block # %s (%s remaining)' %
- (title,index,nblocks-index-1)))
+ (title,index,nblocks-index-1)))
else:
print(marquee('<%s> block # %s (%s remaining)' %
- (title,index,nblocks-index-1)))
- print(block, end=' ')
+ (title,index,nblocks-index-1)))
+ print(block, end=' ')
sys.stdout.flush()
def run_cell(self,source):
@@ -442,17 +442,17 @@ class Demo(object):
self.block_index += 1
if self._silent[index]:
print(marquee('Executing silent block # %s (%s remaining)' %
- (index,self.nblocks-index-1)))
+ (index,self.nblocks-index-1)))
else:
self.pre_cmd()
self.show(index)
if self.auto_all or self._auto[index]:
- print(marquee('output:'))
+ print(marquee('output:'))
else:
- print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
+ print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
ans = py3compat.input().strip()
if ans:
- print(marquee('Block NOT executed'))
+ print(marquee('Block NOT executed'))
return
try:
save_argv = sys.argv
@@ -470,10 +470,10 @@ class Demo(object):
if self.block_index == self.nblocks:
mq1 = self.marquee('END OF DEMO')
if mq1:
- # avoid spurious print if empty marquees are used
- print()
- print(mq1)
- print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
+ # avoid spurious print if empty marquees are used
+ print()
+ print(mq1)
+ print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
self.finished = True
# These methods are meant to be overridden by subclasses who may wish to
diff --git a/contrib/python/ipython/py2/IPython/lib/display.py b/contrib/python/ipython/py2/IPython/lib/display.py
index 5a8d79ad47..9221e2e062 100644
--- a/contrib/python/ipython/py2/IPython/lib/display.py
+++ b/contrib/python/ipython/py2/IPython/lib/display.py
@@ -41,7 +41,7 @@ class Audio(DisplayObject):
filename : unicode
Path to a local file to load the data from.
embed : boolean
- Should the audio data be embedded using a data URI (True) or should
+ Should the audio data be embedded using a data URI (True) or should
the original source be referenced. Set this to True if you want the
audio to playable later with no internet connection in the notebook.
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhook.py b/contrib/python/ipython/py2/IPython/lib/inputhook.py
index e742264914..e6e8f2dbbc 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhook.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhook.py
@@ -1,7 +1,7 @@
# coding: utf-8
"""
-Deprecated since IPython 5.0
-
+Deprecated since IPython 5.0
+
Inputhook management for GUI event loop integration.
"""
@@ -19,13 +19,13 @@ import platform
import sys
from distutils.version import LooseVersion as V
-from warnings import warn
+from warnings import warn
+
+
+warn("`IPython.lib.inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
+
-
-warn("`IPython.lib.inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
-
-
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
@@ -105,10 +105,10 @@ else:
class InputHookManager(object):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Manage PyOS_InputHook for different GUI toolkits.
- Manage PyOS_InputHook for different GUI toolkits.
-
This class installs various hooks under ``PyOSInputHook`` to handle
GUI event loop integration.
"""
@@ -130,25 +130,25 @@ class InputHookManager(object):
self._current_gui = None
def get_pyos_inputhook(self):
- """DEPRECATED since IPython 5.0
-
- Return the current PyOS_InputHook as a ctypes.c_void_p."""
- warn("`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ """DEPRECATED since IPython 5.0
+
+ Return the current PyOS_InputHook as a ctypes.c_void_p."""
+ warn("`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
def get_pyos_inputhook_as_func(self):
- """DEPRECATED since IPython 5.0
-
- Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
- warn("`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ """DEPRECATED since IPython 5.0
+
+ Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
+ warn("`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
def set_inputhook(self, callback):
- """DEPRECATED since IPython 5.0
-
- Set PyOS_InputHook to callback and return the previous one."""
+ """DEPRECATED since IPython 5.0
+
+ Set PyOS_InputHook to callback and return the previous one."""
# On platforms with 'readline' support, it's all too likely to
# have a KeyboardInterrupt signal delivered *even before* an
# initial ``try:`` clause in the callback can be executed, so
@@ -164,10 +164,10 @@ class InputHookManager(object):
return original
def clear_inputhook(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Set PyOS_InputHook to NULL and return the previous one.
- Set PyOS_InputHook to NULL and return the previous one.
-
Parameters
----------
app : optional, ignored
@@ -176,8 +176,8 @@ class InputHookManager(object):
the actual value of the parameter is ignored. This uniform interface
makes it easier to have user-level entry points in the main IPython
app like :meth:`enable_gui`."""
- warn("`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
pyos_inputhook_ptr = self.get_pyos_inputhook()
original = self.get_pyos_inputhook_as_func()
pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
@@ -186,10 +186,10 @@ class InputHookManager(object):
return original
def clear_app_refs(self, gui=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Clear IPython's internal reference to an application instance.
- Clear IPython's internal reference to an application instance.
-
Whenever we create an app for a user on qt4 or wx, we hold a
reference to the app. This is needed because in some cases bad things
can happen if a user doesn't hold a reference themselves. This
@@ -202,17 +202,17 @@ class InputHookManager(object):
the app for that toolkit. References are not held for gtk or tk
as those toolkits don't have the notion of an app.
"""
- warn("`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if gui is None:
self.apps = {}
elif gui in self.apps:
del self.apps[gui]
def register(self, toolkitname, *aliases):
- """DEPRECATED since IPython 5.0
-
- Register a class to provide the event loop for a given GUI.
+ """DEPRECATED since IPython 5.0
+
+ Register a class to provide the event loop for a given GUI.
This is intended to be used as a class decorator. It should be passed
the names with which to register this GUI integration. The classes
@@ -225,8 +225,8 @@ class InputHookManager(object):
def enable(self, app=None):
...
"""
- warn("`register` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`register` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
def decorator(cls):
if ctypes is not None:
inst = cls(self)
@@ -237,18 +237,18 @@ class InputHookManager(object):
return decorator
def current_gui(self):
- """DEPRECATED since IPython 5.0
-
- Return a string indicating the currently active GUI or None."""
- warn("`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ """DEPRECATED since IPython 5.0
+
+ Return a string indicating the currently active GUI or None."""
+ warn("`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
return self._current_gui
def enable_gui(self, gui=None, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Switch amongst GUI input hooks by name.
- Switch amongst GUI input hooks by name.
-
This is a higher level method than :meth:`set_inputhook` - it uses the
GUI name to look up a registered object which enables the input hook
for that GUI.
@@ -271,8 +271,8 @@ class InputHookManager(object):
PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
one.
"""
- warn("`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if gui in (None, GUI_NONE):
return self.disable_gui()
@@ -289,28 +289,28 @@ class InputHookManager(object):
app = gui_hook.enable(app)
if app is not None:
app._in_event_loop = True
- self.apps[gui] = app
+ self.apps[gui] = app
return app
def disable_gui(self):
- """DEPRECATED since IPython 5.0
-
- Disable GUI event loop integration.
+ """DEPRECATED since IPython 5.0
+
+ Disable GUI event loop integration.
If an application was registered, this sets its ``_in_event_loop``
attribute to False. It then calls :meth:`clear_inputhook`.
"""
- warn("`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
gui = self._current_gui
if gui in self.apps:
self.apps[gui]._in_event_loop = False
return self.clear_inputhook()
class InputHookBase(object):
- """DEPRECATED since IPython 5.0
-
- Base class for input hooks for specific toolkits.
+ """DEPRECATED since IPython 5.0
+
+ Base class for input hooks for specific toolkits.
Subclasses should define an :meth:`enable` method with one argument, ``app``,
which will either be an instance of the toolkit's application class, or None.
@@ -326,20 +326,20 @@ inputhook_manager = InputHookManager()
@inputhook_manager.register('osx')
class NullInputHook(InputHookBase):
- """DEPRECATED since IPython 5.0
-
- A null inputhook that doesn't need to do anything"""
+ """DEPRECATED since IPython 5.0
+
+ A null inputhook that doesn't need to do anything"""
def enable(self, app=None):
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
@inputhook_manager.register('wx')
class WxInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with wxPython.
- Enable event loop integration with wxPython.
-
Parameters
----------
app : WX Application, optional.
@@ -359,8 +359,8 @@ class WxInputHook(InputHookBase):
import wx
app = wx.App(redirect=False, clearSigInt=False)
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import wx
wx_version = V(wx.__version__).version
@@ -383,14 +383,14 @@ class WxInputHook(InputHookBase):
return app
def disable(self):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Disable event loop integration with wxPython.
- Disable event loop integration with wxPython.
-
This restores appnapp on OS X
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if _use_appnope():
from appnope import nap
nap()
@@ -398,9 +398,9 @@ class WxInputHook(InputHookBase):
@inputhook_manager.register('qt', 'qt4')
class Qt4InputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with PyQt4.
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with PyQt4.
Parameters
----------
@@ -421,8 +421,8 @@ class Qt4InputHook(InputHookBase):
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
from IPython.lib.inputhookqt4 import create_inputhook_qt4
app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
self.manager.set_inputhook(inputhook_qt4)
@@ -433,14 +433,14 @@ class Qt4InputHook(InputHookBase):
return app
def disable_qt4(self):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Disable event loop integration with PyQt4.
- Disable event loop integration with PyQt4.
-
This restores appnapp on OS X
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if _use_appnope():
from appnope import nap
nap()
@@ -449,8 +449,8 @@ class Qt4InputHook(InputHookBase):
@inputhook_manager.register('qt5')
class Qt5InputHook(Qt4InputHook):
def enable(self, app=None):
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
os.environ['QT_API'] = 'pyqt5'
return Qt4InputHook.enable(self, app)
@@ -458,10 +458,10 @@ class Qt5InputHook(Qt4InputHook):
@inputhook_manager.register('gtk')
class GtkInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with PyGTK.
- Enable event loop integration with PyGTK.
-
Parameters
----------
app : ignored
@@ -475,8 +475,8 @@ class GtkInputHook(InputHookBase):
the PyGTK to integrate with terminal based applications like
IPython.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import gtk
try:
gtk.set_interactive(True)
@@ -489,10 +489,10 @@ class GtkInputHook(InputHookBase):
@inputhook_manager.register('tk')
class TkInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with Tk.
- Enable event loop integration with Tk.
-
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
@@ -506,8 +506,8 @@ class TkInputHook(InputHookBase):
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if app is None:
try:
from tkinter import Tk # Py 3
@@ -522,10 +522,10 @@ class TkInputHook(InputHookBase):
@inputhook_manager.register('glut')
class GlutInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with GLUT.
- Enable event loop integration with GLUT.
-
Parameters
----------
@@ -547,8 +547,8 @@ class GlutInputHook(InputHookBase):
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import OpenGL.GLUT as glut
from IPython.lib.inputhookglut import glut_display_mode, \
@@ -576,16 +576,16 @@ class GlutInputHook(InputHookBase):
def disable(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with glut.
+ """DEPRECATED since IPython 5.0
+
+ Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import OpenGL.GLUT as glut
from glut_support import glutMainLoopEvent
@@ -596,10 +596,10 @@ class GlutInputHook(InputHookBase):
@inputhook_manager.register('pyglet')
class PygletInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with pyglet.
- Enable event loop integration with pyglet.
-
Parameters
----------
app : ignored
@@ -614,8 +614,8 @@ class PygletInputHook(InputHookBase):
IPython.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
from IPython.lib.inputhookpyglet import inputhook_pyglet
self.manager.set_inputhook(inputhook_pyglet)
return app
@@ -624,10 +624,10 @@ class PygletInputHook(InputHookBase):
@inputhook_manager.register('gtk3')
class Gtk3InputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with Gtk3 (gir bindings).
- Enable event loop integration with Gtk3 (gir bindings).
-
Parameters
----------
app : ignored
@@ -641,8 +641,8 @@ class Gtk3InputHook(InputHookBase):
the Gtk3 to integrate with terminal based applications like
IPython.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
from IPython.lib.inputhookgtk3 import inputhook_gtk3
self.manager.set_inputhook(inputhook_gtk3)
diff --git a/contrib/python/ipython/py2/IPython/lib/latextools.py b/contrib/python/ipython/py2/IPython/lib/latextools.py
index 5b3c93dc63..c3230dd489 100644
--- a/contrib/python/ipython/py2/IPython/lib/latextools.py
+++ b/contrib/python/ipython/py2/IPython/lib/latextools.py
@@ -39,24 +39,24 @@ class LaTeXTool(SingletonConfigurable):
# for display style, the default ["matplotlib", "dvipng"] can
# be used. To NOT use dvipng so that other repr such as
# unicode pretty printing is used, you can use ["matplotlib"].
- ).tag(config=True)
+ ).tag(config=True)
use_breqn = Bool(
True,
help="Use breqn.sty to automatically break long equations. "
"This configuration takes effect only for dvipng backend.",
- ).tag(config=True)
+ ).tag(config=True)
packages = List(
['amsmath', 'amsthm', 'amssymb', 'bm'],
help="A list of packages to use for dvipng backend. "
"'breqn' will be automatically appended when use_breqn=True.",
- ).tag(config=True)
+ ).tag(config=True)
preamble = Unicode(
help="Additional preamble to use when generating LaTeX source "
"for dvipng backend.",
- ).tag(config=True)
+ ).tag(config=True)
def latex_to_png(s, encode=False, backend=None, wrap=False):
@@ -64,7 +64,7 @@ def latex_to_png(s, encode=False, backend=None, wrap=False):
Parameters
----------
- s : str
+ s : str
The raw string containing valid inline LaTeX.
encode : bool, optional
Should the PNG data base64 encoded to make it JSON'able.
@@ -97,24 +97,24 @@ def latex_to_png(s, encode=False, backend=None, wrap=False):
def latex_to_png_mpl(s, wrap):
try:
from matplotlib import mathtext
- from pyparsing import ParseFatalException
+ from pyparsing import ParseFatalException
except ImportError:
return None
-
+
# mpl mathtext doesn't support display math, force inline
s = s.replace('$$', '$')
if wrap:
s = u'${0}$'.format(s)
- try:
- mt = mathtext.MathTextParser('bitmap')
- f = BytesIO()
- mt.to_png(f, s, fontsize=12)
- return f.getvalue()
- except (ValueError, RuntimeError, ParseFatalException):
- return None
+ try:
+ mt = mathtext.MathTextParser('bitmap')
+ f = BytesIO()
+ mt.to_png(f, s, fontsize=12)
+ return f.getvalue()
+ except (ValueError, RuntimeError, ParseFatalException):
+ return None
+
-
def latex_to_png_dvipng(s, wrap):
try:
find_cmd('latex')
@@ -142,8 +142,8 @@ def latex_to_png_dvipng(s, wrap):
with open(outfile, "rb") as f:
return f.read()
- except subprocess.CalledProcessError:
- return None
+ except subprocess.CalledProcessError:
+ return None
finally:
shutil.rmtree(workdir)
diff --git a/contrib/python/ipython/py2/IPython/lib/lexers.py b/contrib/python/ipython/py2/IPython/lib/lexers.py
index 1b81e3db61..9160ae1245 100644
--- a/contrib/python/ipython/py2/IPython/lib/lexers.py
+++ b/contrib/python/ipython/py2/IPython/lib/lexers.py
@@ -44,7 +44,7 @@ from pygments.lexer import (
Lexer, DelegatingLexer, RegexLexer, do_insertions, bygroups, using,
)
from pygments.token import (
- Generic, Keyword, Literal, Name, Operator, Other, Text, Error,
+ Generic, Keyword, Literal, Name, Operator, Other, Text, Error,
)
from pygments.util import get_bool_opt
@@ -235,13 +235,13 @@ class IPythonConsoleLexer(Lexer):
# The regexps used to determine what is input and what is output.
# The default prompts for IPython are:
#
- # in = 'In [#]: '
- # continuation = ' .D.: '
- # template = 'Out[#]: '
+ # in = 'In [#]: '
+ # continuation = ' .D.: '
+ # template = 'Out[#]: '
+ #
+ # Where '#' is the 'prompt number' or 'execution count' and 'D'
+ # D is a number of dots matching the width of the execution count
#
- # Where '#' is the 'prompt number' or 'execution count' and 'D'
- # D is a number of dots matching the width of the execution count
- #
in1_regex = r'In \[[0-9]+\]: '
in2_regex = r' \.\.+\.: '
out_regex = r'Out\[[0-9]+\]: '
@@ -475,9 +475,9 @@ class IPythonConsoleLexer(Lexer):
self.insertions.append((len(self.buffer), [insertion]))
self.buffer += code
- for token in self.buffered_tokens():
- yield token
-
+ for token in self.buffered_tokens():
+ yield token
+
class IPyLexer(Lexer):
"""
Primary lexer for all IPython-like code.
diff --git a/contrib/python/ipython/py2/IPython/lib/pretty.py b/contrib/python/ipython/py2/IPython/lib/pretty.py
index 09d638cbcb..28eee523c5 100644
--- a/contrib/python/ipython/py2/IPython/lib/pretty.py
+++ b/contrib/python/ipython/py2/IPython/lib/pretty.py
@@ -85,7 +85,7 @@ import re
import datetime
from collections import deque
-from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
+from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
from IPython.utils.encoding import get_stream_enc
from io import StringIO
@@ -609,8 +609,8 @@ def _dict_pprinter_factory(start, end):
def inner(obj, p, cycle):
if cycle:
return p.text('{...}')
- step = len(start)
- p.begin_group(step, start)
+ step = len(start)
+ p.begin_group(step, start)
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
# From Python 3.7, dicts preserve order by definition, so we don't sort.
@@ -624,7 +624,7 @@ def _dict_pprinter_factory(start, end):
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
- p.end_group(step, end)
+ p.end_group(step, end)
return inner
@@ -634,11 +634,11 @@ def _super_pprint(obj, p, cycle):
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
- if PYPY: # In PyPy, super() objects don't have __self__ attributes
- dself = obj.__repr__.__self__
- p.pretty(None if dself is obj else dself)
- else:
- p.pretty(obj.__self__)
+ if PYPY: # In PyPy, super() objects don't have __self__ attributes
+ dself = obj.__repr__.__self__
+ p.pretty(None if dself is obj else dself)
+ else:
+ p.pretty(obj.__self__)
p.end_group(8, '>')
@@ -672,10 +672,10 @@ def _type_pprint(obj, p, cycle):
# Heap allocated types might not have the module attribute,
# and others may set it to None.
- # Checks for a __repr__ override in the metaclass. Can't compare the
- # type(obj).__repr__ directly because in PyPy the representation function
- # inherited from type isn't the same type.__repr__
- if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
+ # Checks for a __repr__ override in the metaclass. Can't compare the
+ # type(obj).__repr__ directly because in PyPy the representation function
+ # inherited from type isn't the same type.__repr__
+ if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
@@ -762,15 +762,15 @@ _type_pprinters = {
}
try:
- # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
- # using dict.setdefault avoids overwritting the dict printer
- _type_pprinters.setdefault(types.DictProxyType,
- _dict_pprinter_factory('dict_proxy({', '})'))
+ # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
+ # using dict.setdefault avoids overwritting the dict printer
+ _type_pprinters.setdefault(types.DictProxyType,
+ _dict_pprinter_factory('dict_proxy({', '})'))
_type_pprinters[types.ClassType] = _type_pprint
_type_pprinters[types.SliceType] = _repr_pprint
except AttributeError: # Python 3
- _type_pprinters[types.MappingProxyType] = \
- _dict_pprinter_factory('mappingproxy({', '})')
+ _type_pprinters[types.MappingProxyType] = \
+ _dict_pprinter_factory('mappingproxy({', '})')
_type_pprinters[slice] = _repr_pprint
try:
diff --git a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
index 2173954c20..8df9ace1f3 100644
--- a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
+++ b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
@@ -874,7 +874,7 @@ class IPythonDirective(Directive):
# EmbeddedSphinxShell is created, its interactive shell member
# is the same for each instance.
- if mplbackend and 'matplotlib.backends' not in sys.modules:
+ if mplbackend and 'matplotlib.backends' not in sys.modules:
import matplotlib
matplotlib.use(mplbackend)
diff --git a/contrib/python/ipython/py2/IPython/terminal/debugger.py b/contrib/python/ipython/py2/IPython/terminal/debugger.py
index 4be1bae6a8..c68a3204a6 100644
--- a/contrib/python/ipython/py2/IPython/terminal/debugger.py
+++ b/contrib/python/ipython/py2/IPython/terminal/debugger.py
@@ -1,46 +1,46 @@
import signal
import sys
-from IPython.core.debugger import Pdb
-
-from IPython.core.completer import IPCompleter
-from .ptutils import IPythonPTCompleter
+from IPython.core.debugger import Pdb
+
+from IPython.core.completer import IPCompleter
+from .ptutils import IPythonPTCompleter
from .shortcuts import suspend_to_bg, cursor_in_leading_ws
-
+
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import (Condition, HasFocus, HasSelection,
ViInsertMode, EmacsInsertMode)
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
-from prompt_toolkit.token import Token
-from prompt_toolkit.shortcuts import create_prompt_application
-from prompt_toolkit.interface import CommandLineInterface
-from prompt_toolkit.enums import EditingMode
-
-
-class TerminalPdb(Pdb):
- def __init__(self, *args, **kwargs):
- Pdb.__init__(self, *args, **kwargs)
- self._ptcomp = None
- self.pt_init()
-
- def pt_init(self):
- def get_prompt_tokens(cli):
- return [(Token.Prompt, self.prompt)]
-
+from prompt_toolkit.token import Token
+from prompt_toolkit.shortcuts import create_prompt_application
+from prompt_toolkit.interface import CommandLineInterface
+from prompt_toolkit.enums import EditingMode
+
+
+class TerminalPdb(Pdb):
+ def __init__(self, *args, **kwargs):
+ Pdb.__init__(self, *args, **kwargs)
+ self._ptcomp = None
+ self.pt_init()
+
+ def pt_init(self):
+ def get_prompt_tokens(cli):
+ return [(Token.Prompt, self.prompt)]
+
def patch_stdout(**kwargs):
return self.pt_cli.patch_stdout_context(**kwargs)
- if self._ptcomp is None:
- compl = IPCompleter(shell=self.shell,
- namespace={},
- global_namespace={},
- use_readline=False,
- parent=self.shell,
- )
+ if self._ptcomp is None:
+ compl = IPCompleter(shell=self.shell,
+ namespace={},
+ global_namespace={},
+ use_readline=False,
+ parent=self.shell,
+ )
self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout)
-
+
kbmanager = KeyBindingManager.for_prompt()
supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend
@@ -55,55 +55,55 @@ class TerminalPdb(Pdb):
))(display_completions_like_readline)
multicolumn = (self.shell.display_completions == 'multicolumn')
- self._pt_app = create_prompt_application(
- editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
+ self._pt_app = create_prompt_application(
+ editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
key_bindings_registry=kbmanager.registry,
- history=self.shell.debugger_history,
- completer= self._ptcomp,
- enable_history_search=True,
- mouse_support=self.shell.mouse_support,
+ history=self.shell.debugger_history,
+ completer= self._ptcomp,
+ enable_history_search=True,
+ mouse_support=self.shell.mouse_support,
get_prompt_tokens=get_prompt_tokens,
display_completions_in_columns=multicolumn,
style=self.shell.style
- )
- self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop)
-
- def cmdloop(self, intro=None):
- """Repeatedly issue a prompt, accept input, parse an initial prefix
- off the received input, and dispatch to action methods, passing them
- the remainder of the line as argument.
-
- override the same methods from cmd.Cmd to provide prompt toolkit replacement.
- """
- if not self.use_rawinput:
- raise ValueError('Sorry ipdb does not support use_rawinput=False')
-
- self.preloop()
-
- try:
- if intro is not None:
- self.intro = intro
- if self.intro:
- self.stdout.write(str(self.intro)+"\n")
- stop = None
- while not stop:
- if self.cmdqueue:
- line = self.cmdqueue.pop(0)
- else:
- self._ptcomp.ipy_completer.namespace = self.curframe_locals
- self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
- try:
- line = self.pt_cli.run(reset_current_buffer=True).text
- except EOFError:
- line = 'EOF'
- line = self.precmd(line)
- stop = self.onecmd(line)
- stop = self.postcmd(stop, line)
- self.postloop()
- except Exception:
- raise
-
-
+ )
+ self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop)
+
+ def cmdloop(self, intro=None):
+ """Repeatedly issue a prompt, accept input, parse an initial prefix
+ off the received input, and dispatch to action methods, passing them
+ the remainder of the line as argument.
+
+ override the same methods from cmd.Cmd to provide prompt toolkit replacement.
+ """
+ if not self.use_rawinput:
+ raise ValueError('Sorry ipdb does not support use_rawinput=False')
+
+ self.preloop()
+
+ try:
+ if intro is not None:
+ self.intro = intro
+ if self.intro:
+ self.stdout.write(str(self.intro)+"\n")
+ stop = None
+ while not stop:
+ if self.cmdqueue:
+ line = self.cmdqueue.pop(0)
+ else:
+ self._ptcomp.ipy_completer.namespace = self.curframe_locals
+ self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
+ try:
+ line = self.pt_cli.run(reset_current_buffer=True).text
+ except EOFError:
+ line = 'EOF'
+ line = self.precmd(line)
+ stop = self.onecmd(line)
+ stop = self.postcmd(stop, line)
+ self.postloop()
+ except Exception:
+ raise
+
+
def set_trace(frame=None):
"""
Start debugging from `frame`.
diff --git a/contrib/python/ipython/py2/IPython/terminal/embed.py b/contrib/python/ipython/py2/IPython/terminal/embed.py
index 9f8be00a77..5ad70431e4 100644
--- a/contrib/python/ipython/py2/IPython/terminal/embed.py
+++ b/contrib/python/ipython/py2/IPython/terminal/embed.py
@@ -14,7 +14,7 @@ import warnings
from IPython.core import ultratb, compilerop
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.core.interactiveshell import DummyMod, InteractiveShell
+from IPython.core.interactiveshell import DummyMod, InteractiveShell
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from IPython.terminal.ipapp import load_default_config
@@ -117,33 +117,33 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
display_banner = CBool(True)
exit_msg = Unicode()
- # When embedding, by default we don't change the terminal title
- term_title = Bool(False,
- help="Automatically set the terminal title"
- ).tag(config=True)
-
- _inactive_locations = set()
-
- @property
- def embedded_active(self):
+ # When embedding, by default we don't change the terminal title
+ term_title = Bool(False,
+ help="Automatically set the terminal title"
+ ).tag(config=True)
+
+ _inactive_locations = set()
+
+ @property
+ def embedded_active(self):
return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\
and (self._init_location_id not in InteractiveShellEmbed._inactive_locations)
-
+
def _disable_init_location(self):
"""Disable the current Instance creation location"""
InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
- @embedded_active.setter
- def embedded_active(self, value):
+ @embedded_active.setter
+ def embedded_active(self, value):
if value:
InteractiveShellEmbed._inactive_locations.discard(
self._call_location_id)
InteractiveShellEmbed._inactive_locations.discard(
self._init_location_id)
- else:
+ else:
InteractiveShellEmbed._inactive_locations.add(
self._call_location_id)
-
+
def __init__(self, **kw):
if kw.get('user_global_ns', None) is not None:
raise DeprecationWarning(
@@ -154,7 +154,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
frame = sys._getframe(1)
clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
self._init_location_id = clid
-
+
super(InteractiveShellEmbed,self).__init__(**kw)
# don't use the ipython crash handler so that user exceptions aren't
@@ -219,9 +219,9 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
else:
self.old_banner2 = ''
- if self.display_banner:
- self.show_banner()
-
+ if self.display_banner:
+ self.show_banner()
+
# Call the embedding code with a stack depth of 1 so it can skip over
# our call and get the original caller's namespaces.
self.mainloop(local_ns, module, stack_depth=stack_depth,
@@ -264,11 +264,11 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
"""
if (global_ns is not None) and (module is None):
- raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
+ raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
+
+ if (display_banner is not None):
+ warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
- if (display_banner is not None):
- warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
-
# Get locals and globals from caller
if ((local_ns is None or module is None or compile_flags is None)
and self.default_user_namespaces):
@@ -278,14 +278,14 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
local_ns = call_frame.f_locals
if module is None:
global_ns = call_frame.f_globals
- try:
- module = sys.modules[global_ns['__name__']]
- except KeyError:
- warnings.warn("Failed to get module %s" % \
- global_ns.get('__name__', 'unknown module')
- )
- module = DummyMod()
- module.__dict__ = global_ns
+ try:
+ module = sys.modules[global_ns['__name__']]
+ except KeyError:
+ warnings.warn("Failed to get module %s" % \
+ global_ns.get('__name__', 'unknown module')
+ )
+ module = DummyMod()
+ module.__dict__ = global_ns
if compile_flags is None:
compile_flags = (call_frame.f_code.co_flags &
compilerop.PyCF_MASK)
@@ -320,7 +320,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
self.set_completer_frame()
with self.builtin_trap, self.display_trap:
- self.interact()
+ self.interact()
# now, purge out the local namespace of IPython's hidden variables.
if local_ns is not None:
@@ -378,7 +378,7 @@ def embed(**kwargs):
if saved_shell_instance is not None:
cls = type(saved_shell_instance)
cls.clear_instance()
- frame = sys._getframe(1)
+ frame = sys._getframe(1)
shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
frame.f_code.co_filename, frame.f_lineno), **kwargs)
shell(header=header, stack_depth=2, compile_flags=compile_flags,
diff --git a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
index c5b0d7d921..f67cc6b502 100644
--- a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
+++ b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
@@ -1,68 +1,68 @@
-"""IPython terminal interface using prompt_toolkit"""
+"""IPython terminal interface using prompt_toolkit"""
from __future__ import print_function
import os
import sys
-import warnings
-from warnings import warn
+import warnings
+from warnings import warn
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
-from IPython.utils import io
+from IPython.utils import io
from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types
from IPython.utils.terminal import toggle_set_term_title, set_term_title
from IPython.utils.process import abbrev_cwd
from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union
from prompt_toolkit.document import Document
-from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
-from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
-from prompt_toolkit.history import InMemoryHistory
-from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
-from prompt_toolkit.interface import CommandLineInterface
-from prompt_toolkit.key_binding.manager import KeyBindingManager
-from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
-from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
+from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
+from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
+from prompt_toolkit.history import InMemoryHistory
+from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
+from prompt_toolkit.interface import CommandLineInterface
+from prompt_toolkit.key_binding.manager import KeyBindingManager
+from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
+from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
from pygments.styles import get_style_by_name
from pygments.style import Style
-from pygments.token import Token
-
-from .debugger import TerminalPdb, Pdb
-from .magics import TerminalMagics
+from pygments.token import Token
+
+from .debugger import TerminalPdb, Pdb
+from .magics import TerminalMagics
from .pt_inputhooks import get_inputhook_name_and_func
-from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
-from .ptutils import IPythonPTCompleter, IPythonPTLexer
-from .shortcuts import register_ipython_shortcuts
-
-DISPLAY_BANNER_DEPRECATED = object()
-
-
-from pygments.style import Style
-
-class _NoStyle(Style): pass
-
-
-
-_style_overrides_light_bg = {
- Token.Prompt: '#0000ff',
- Token.PromptNum: '#0000ee bold',
- Token.OutPrompt: '#cc0000',
- Token.OutPromptNum: '#bb0000 bold',
-}
-
-_style_overrides_linux = {
- Token.Prompt: '#00cc00',
- Token.PromptNum: '#00bb00 bold',
- Token.OutPrompt: '#cc0000',
- Token.OutPromptNum: '#bb0000 bold',
-}
-
-
-
+from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
+from .ptutils import IPythonPTCompleter, IPythonPTLexer
+from .shortcuts import register_ipython_shortcuts
+
+DISPLAY_BANNER_DEPRECATED = object()
+
+
+from pygments.style import Style
+
+class _NoStyle(Style): pass
+
+
+
+_style_overrides_light_bg = {
+ Token.Prompt: '#0000ff',
+ Token.PromptNum: '#0000ee bold',
+ Token.OutPrompt: '#cc0000',
+ Token.OutPromptNum: '#bb0000 bold',
+}
+
+_style_overrides_linux = {
+ Token.Prompt: '#00cc00',
+ Token.PromptNum: '#00bb00 bold',
+ Token.OutPrompt: '#cc0000',
+ Token.OutPromptNum: '#bb0000 bold',
+}
+
+
+
def get_default_editor():
try:
ed = os.environ['EDITOR']
- if not PY3:
+ if not PY3:
ed = ed.decode()
return ed
except KeyError:
@@ -76,153 +76,153 @@ def get_default_editor():
else:
return 'notepad' # same in Windows!
-# conservatively check for tty
-# overridden streams can result in things like:
-# - sys.stdin = None
-# - no isatty method
-for _name in ('stdin', 'stdout', 'stderr'):
- _stream = getattr(sys, _name)
- if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
- _is_tty = False
- break
-else:
- _is_tty = True
+# conservatively check for tty
+# overridden streams can result in things like:
+# - sys.stdin = None
+# - no isatty method
+for _name in ('stdin', 'stdout', 'stderr'):
+ _stream = getattr(sys, _name)
+ if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
+ _is_tty = False
+ break
+else:
+ _is_tty = True
-_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
+_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
-class TerminalInteractiveShell(InteractiveShell):
- space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
- 'to reserve for the completion menu'
- ).tag(config=True)
+class TerminalInteractiveShell(InteractiveShell):
+ space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
+ 'to reserve for the completion menu'
+ ).tag(config=True)
- def _space_for_menu_changed(self, old, new):
- self._update_layout()
+ def _space_for_menu_changed(self, old, new):
+ self._update_layout()
- pt_cli = None
- debugger_history = None
- _pt_app = None
+ pt_cli = None
+ debugger_history = None
+ _pt_app = None
- simple_prompt = Bool(_use_simple_prompt,
+ simple_prompt = Bool(_use_simple_prompt,
help="""Use `raw_input` for the REPL, without completion and prompt colors.
- Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
- IPython own testing machinery, and emacs inferior-shell integration through elpy.
+ Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
+ IPython own testing machinery, and emacs inferior-shell integration through elpy.
- This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
- environment variable is set, or the current terminal is not a tty.
+ This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
+ environment variable is set, or the current terminal is not a tty.
- """
- ).tag(config=True)
+ """
+ ).tag(config=True)
- @property
- def debugger_cls(self):
- return Pdb if self.simple_prompt else TerminalPdb
+ @property
+ def debugger_cls(self):
+ return Pdb if self.simple_prompt else TerminalPdb
- confirm_exit = Bool(True,
- help="""
- Set to confirm when you try to exit IPython with an EOF (Control-D
- in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
- you can force a direct exit without any confirmation.""",
- ).tag(config=True)
+ confirm_exit = Bool(True,
+ help="""
+ Set to confirm when you try to exit IPython with an EOF (Control-D
+ in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
+ you can force a direct exit without any confirmation.""",
+ ).tag(config=True)
- editing_mode = Unicode('emacs',
- help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
- ).tag(config=True)
+ editing_mode = Unicode('emacs',
+ help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
+ ).tag(config=True)
- mouse_support = Bool(False,
- help="Enable mouse support in the prompt"
- ).tag(config=True)
+ mouse_support = Bool(False,
+ help="Enable mouse support in the prompt"
+ ).tag(config=True)
# We don't load the list of styles for the help string, because loading
# Pygments plugins takes time and can cause unexpected errors.
highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
help="""The name or class of a Pygments style to use for syntax
highlighting. To see available styles, run `pygmentize -L styles`."""
- ).tag(config=True)
+ ).tag(config=True)
- @observe('highlighting_style')
- @observe('colors')
- def _highlighting_style_changed(self, change):
- self.refresh_style()
+ @observe('highlighting_style')
+ @observe('colors')
+ def _highlighting_style_changed(self, change):
+ self.refresh_style()
- def refresh_style(self):
+ def refresh_style(self):
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
- highlighting_style_overrides = Dict(
- help="Override highlighting format for specific tokens"
- ).tag(config=True)
+ highlighting_style_overrides = Dict(
+ help="Override highlighting format for specific tokens"
+ ).tag(config=True)
- true_color = Bool(False,
- help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
- "If your terminal supports true color, the following command "
- "should print 'TRUECOLOR' in orange: "
- "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
- ).tag(config=True)
+ true_color = Bool(False,
+ help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
+ "If your terminal supports true color, the following command "
+ "should print 'TRUECOLOR' in orange: "
+ "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
+ ).tag(config=True)
- editor = Unicode(get_default_editor(),
- help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
- ).tag(config=True)
+ editor = Unicode(get_default_editor(),
+ help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
+ ).tag(config=True)
- prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
+ prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
- prompts = Instance(Prompts)
+ prompts = Instance(Prompts)
- @default('prompts')
- def _prompts_default(self):
- return self.prompts_class(self)
+ @default('prompts')
+ def _prompts_default(self):
+ return self.prompts_class(self)
- @observe('prompts')
- def _(self, change):
- self._update_layout()
+ @observe('prompts')
+ def _(self, change):
+ self._update_layout()
- @default('displayhook_class')
- def _displayhook_class_default(self):
- return RichPromptDisplayHook
+ @default('displayhook_class')
+ def _displayhook_class_default(self):
+ return RichPromptDisplayHook
- term_title = Bool(True,
- help="Automatically set the terminal title"
- ).tag(config=True)
+ term_title = Bool(True,
+ help="Automatically set the terminal title"
+ ).tag(config=True)
display_completions = Enum(('column', 'multicolumn','readlinelike'),
- help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
- "'readlinelike'. These options are for `prompt_toolkit`, see "
- "`prompt_toolkit` documentation for more information."
- ),
- default_value='multicolumn').tag(config=True)
+ help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
+ "'readlinelike'. These options are for `prompt_toolkit`, see "
+ "`prompt_toolkit` documentation for more information."
+ ),
+ default_value='multicolumn').tag(config=True)
- highlight_matching_brackets = Bool(True,
+ highlight_matching_brackets = Bool(True,
help="Highlight matching brackets.",
- ).tag(config=True)
+ ).tag(config=True)
extra_open_editor_shortcuts = Bool(False,
help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
"This is in addition to the F2 binding, which is always enabled."
).tag(config=True)
- @observe('term_title')
- def init_term_title(self, change=None):
- # Enable or disable the terminal title.
- if self.term_title:
- toggle_set_term_title(True)
- set_term_title('IPython: ' + abbrev_cwd())
- else:
- toggle_set_term_title(False)
-
- def init_display_formatter(self):
- super(TerminalInteractiveShell, self).init_display_formatter()
- # terminal only supports plain text
- self.display_formatter.active_types = ['text/plain']
+ @observe('term_title')
+ def init_term_title(self, change=None):
+ # Enable or disable the terminal title.
+ if self.term_title:
+ toggle_set_term_title(True)
+ set_term_title('IPython: ' + abbrev_cwd())
+ else:
+ toggle_set_term_title(False)
+
+ def init_display_formatter(self):
+ super(TerminalInteractiveShell, self).init_display_formatter()
+ # terminal only supports plain text
+ self.display_formatter.active_types = ['text/plain']
# disable `_ipython_display_`
self.display_formatter.ipython_display_formatter.enabled = False
- def init_prompt_toolkit_cli(self):
- if self.simple_prompt:
- # Fall back to plain non-interactive output for tests.
- # This is very limited, and only accepts a single line.
- def prompt():
+ def init_prompt_toolkit_cli(self):
+ if self.simple_prompt:
+ # Fall back to plain non-interactive output for tests.
+ # This is very limited, and only accepts a single line.
+ def prompt():
isp = self.input_splitter
prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
@@ -231,82 +231,82 @@ class TerminalInteractiveShell(InteractiveShell):
isp.push(line)
prompt_text = prompt_continuation
return isp.source_reset()
- self.prompt_for_code = prompt
- return
+ self.prompt_for_code = prompt
+ return
- # Set up keyboard shortcuts
+ # Set up keyboard shortcuts
kbmanager = KeyBindingManager.for_prompt(
enable_open_in_editor=self.extra_open_editor_shortcuts,
)
- register_ipython_shortcuts(kbmanager.registry, self)
-
- # Pre-populate history from IPython's history database
- history = InMemoryHistory()
- last_cell = u""
- for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
- include_latest=True):
- # Ignore blank lines and consecutive duplicates
- cell = cell.rstrip()
- if cell and (cell != last_cell):
- history.append(cell)
+ register_ipython_shortcuts(kbmanager.registry, self)
+
+ # Pre-populate history from IPython's history database
+ history = InMemoryHistory()
+ last_cell = u""
+ for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
+ include_latest=True):
+ # Ignore blank lines and consecutive duplicates
+ cell = cell.rstrip()
+ if cell and (cell != last_cell):
+ history.append(cell)
last_cell = cell
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
self.style = DynamicStyle(lambda: self._style)
- editing_mode = getattr(EditingMode, self.editing_mode.upper())
+ editing_mode = getattr(EditingMode, self.editing_mode.upper())
def patch_stdout(**kwargs):
return self.pt_cli.patch_stdout_context(**kwargs)
- self._pt_app = create_prompt_application(
- editing_mode=editing_mode,
- key_bindings_registry=kbmanager.registry,
- history=history,
+ self._pt_app = create_prompt_application(
+ editing_mode=editing_mode,
+ key_bindings_registry=kbmanager.registry,
+ history=history,
completer=IPythonPTCompleter(shell=self,
patch_stdout=patch_stdout),
- enable_history_search=True,
+ enable_history_search=True,
style=self.style,
- mouse_support=self.mouse_support,
- **self._layout_options()
- )
- self._eventloop = create_eventloop(self.inputhook)
- self.pt_cli = CommandLineInterface(
- self._pt_app, eventloop=self._eventloop,
- output=create_output(true_color=self.true_color))
+ mouse_support=self.mouse_support,
+ **self._layout_options()
+ )
+ self._eventloop = create_eventloop(self.inputhook)
+ self.pt_cli = CommandLineInterface(
+ self._pt_app, eventloop=self._eventloop,
+ output=create_output(true_color=self.true_color))
def _make_style_from_name_or_cls(self, name_or_cls):
- """
- Small wrapper that make an IPython compatible style from a style name
+ """
+ Small wrapper that make an IPython compatible style from a style name
We need that to add style for prompt ... etc.
"""
- style_overrides = {}
+ style_overrides = {}
if name_or_cls == 'legacy':
- legacy = self.colors.lower()
- if legacy == 'linux':
- style_cls = get_style_by_name('monokai')
- style_overrides = _style_overrides_linux
- elif legacy == 'lightbg':
- style_overrides = _style_overrides_light_bg
- style_cls = get_style_by_name('pastie')
- elif legacy == 'neutral':
- # The default theme needs to be visible on both a dark background
- # and a light background, because we can't tell what the terminal
- # looks like. These tweaks to the default theme help with that.
- style_cls = get_style_by_name('default')
- style_overrides.update({
- Token.Number: '#007700',
- Token.Operator: 'noinherit',
- Token.String: '#BB6622',
- Token.Name.Function: '#2080D0',
- Token.Name.Class: 'bold #2080D0',
- Token.Name.Namespace: 'bold #2080D0',
- Token.Prompt: '#009900',
- Token.PromptNum: '#00ff00 bold',
- Token.OutPrompt: '#990000',
- Token.OutPromptNum: '#ff0000 bold',
- })
+ legacy = self.colors.lower()
+ if legacy == 'linux':
+ style_cls = get_style_by_name('monokai')
+ style_overrides = _style_overrides_linux
+ elif legacy == 'lightbg':
+ style_overrides = _style_overrides_light_bg
+ style_cls = get_style_by_name('pastie')
+ elif legacy == 'neutral':
+ # The default theme needs to be visible on both a dark background
+ # and a light background, because we can't tell what the terminal
+ # looks like. These tweaks to the default theme help with that.
+ style_cls = get_style_by_name('default')
+ style_overrides.update({
+ Token.Number: '#007700',
+ Token.Operator: 'noinherit',
+ Token.String: '#BB6622',
+ Token.Name.Function: '#2080D0',
+ Token.Name.Class: 'bold #2080D0',
+ Token.Name.Namespace: 'bold #2080D0',
+ Token.Prompt: '#009900',
+ Token.PromptNum: '#00ff00 bold',
+ Token.OutPrompt: '#990000',
+ Token.OutPromptNum: '#ff0000 bold',
+ })
# Hack: Due to limited color support on the Windows console
# the prompt colors will be wrong without this
@@ -317,111 +317,111 @@ class TerminalInteractiveShell(InteractiveShell):
Token.OutPrompt: '#ansidarkred',
Token.OutPromptNum: '#ansired bold',
})
- elif legacy =='nocolor':
- style_cls=_NoStyle
- style_overrides = {}
- else :
- raise ValueError('Got unknown colors: ', legacy)
- else :
+ elif legacy =='nocolor':
+ style_cls=_NoStyle
+ style_overrides = {}
+ else :
+ raise ValueError('Got unknown colors: ', legacy)
+ else :
if isinstance(name_or_cls, string_types):
style_cls = get_style_by_name(name_or_cls)
else:
style_cls = name_or_cls
- style_overrides = {
- Token.Prompt: '#009900',
- Token.PromptNum: '#00ff00 bold',
- Token.OutPrompt: '#990000',
- Token.OutPromptNum: '#ff0000 bold',
- }
- style_overrides.update(self.highlighting_style_overrides)
- style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
- style_dict=style_overrides)
-
- return style
-
- def _layout_options(self):
- """
- Return the current layout option for the current Terminal InteractiveShell
- """
- return {
- 'lexer':IPythonPTLexer(),
- 'reserve_space_for_menu':self.space_for_menu,
- 'get_prompt_tokens':self.prompts.in_prompt_tokens,
- 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
- 'multiline':True,
- 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
-
- # Highlight matching brackets, but only when this setting is
- # enabled, and only when the DEFAULT_BUFFER has the focus.
- 'extra_input_processors': [ConditionalProcessor(
- processor=HighlightMatchingBracketProcessor(chars='[](){}'),
- filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
- Condition(lambda cli: self.highlight_matching_brackets))],
- }
-
- def _update_layout(self):
+ style_overrides = {
+ Token.Prompt: '#009900',
+ Token.PromptNum: '#00ff00 bold',
+ Token.OutPrompt: '#990000',
+ Token.OutPromptNum: '#ff0000 bold',
+ }
+ style_overrides.update(self.highlighting_style_overrides)
+ style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
+ style_dict=style_overrides)
+
+ return style
+
+ def _layout_options(self):
"""
- Ask for a re computation of the application layout, if for example ,
- some configuration options have changed.
- """
- if self._pt_app:
- self._pt_app.layout = create_prompt_layout(**self._layout_options())
-
- def prompt_for_code(self):
- document = self.pt_cli.run(
- pre_run=self.pre_prompt, reset_current_buffer=True)
- return document.text
-
- def enable_win_unicode_console(self):
+ Return the current layout option for the current Terminal InteractiveShell
+ """
+ return {
+ 'lexer':IPythonPTLexer(),
+ 'reserve_space_for_menu':self.space_for_menu,
+ 'get_prompt_tokens':self.prompts.in_prompt_tokens,
+ 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
+ 'multiline':True,
+ 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
+
+ # Highlight matching brackets, but only when this setting is
+ # enabled, and only when the DEFAULT_BUFFER has the focus.
+ 'extra_input_processors': [ConditionalProcessor(
+ processor=HighlightMatchingBracketProcessor(chars='[](){}'),
+ filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
+ Condition(lambda cli: self.highlight_matching_brackets))],
+ }
+
+ def _update_layout(self):
+ """
+ Ask for a re computation of the application layout, if for example ,
+ some configuration options have changed.
+ """
+ if self._pt_app:
+ self._pt_app.layout = create_prompt_layout(**self._layout_options())
+
+ def prompt_for_code(self):
+ document = self.pt_cli.run(
+ pre_run=self.pre_prompt, reset_current_buffer=True)
+ return document.text
+
+ def enable_win_unicode_console(self):
if sys.version_info >= (3, 6):
# Since PEP 528, Python uses the unicode APIs for the Windows
# console by default, so WUC shouldn't be needed.
return
- import win_unicode_console
+ import win_unicode_console
- if PY3:
- win_unicode_console.enable()
+ if PY3:
+ win_unicode_console.enable()
else:
- # https://github.com/ipython/ipython/issues/9768
- from win_unicode_console.streams import (TextStreamWrapper,
- stdout_text_transcoded, stderr_text_transcoded)
+ # https://github.com/ipython/ipython/issues/9768
+ from win_unicode_console.streams import (TextStreamWrapper,
+ stdout_text_transcoded, stderr_text_transcoded)
- class LenientStrStreamWrapper(TextStreamWrapper):
- def write(self, s):
- if isinstance(s, bytes):
- s = s.decode(self.encoding, 'replace')
+ class LenientStrStreamWrapper(TextStreamWrapper):
+ def write(self, s):
+ if isinstance(s, bytes):
+ s = s.decode(self.encoding, 'replace')
- self.base.write(s)
+ self.base.write(s)
- stdout_text_str = LenientStrStreamWrapper(stdout_text_transcoded)
- stderr_text_str = LenientStrStreamWrapper(stderr_text_transcoded)
+ stdout_text_str = LenientStrStreamWrapper(stdout_text_transcoded)
+ stderr_text_str = LenientStrStreamWrapper(stderr_text_transcoded)
- win_unicode_console.enable(stdout=stdout_text_str,
- stderr=stderr_text_str)
+ win_unicode_console.enable(stdout=stdout_text_str,
+ stderr=stderr_text_str)
- def init_io(self):
- if sys.platform not in {'win32', 'cli'}:
- return
+ def init_io(self):
+ if sys.platform not in {'win32', 'cli'}:
+ return
- self.enable_win_unicode_console()
+ self.enable_win_unicode_console()
- import colorama
- colorama.init()
+ import colorama
+ colorama.init()
- # For some reason we make these wrappers around stdout/stderr.
- # For now, we need to reset them so all output gets coloured.
- # https://github.com/ipython/ipython/issues/8669
- # io.std* are deprecated, but don't show our own deprecation warnings
- # during initialization of the deprecated API.
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
- io.stdout = io.IOStream(sys.stdout)
- io.stderr = io.IOStream(sys.stderr)
+ # For some reason we make these wrappers around stdout/stderr.
+ # For now, we need to reset them so all output gets coloured.
+ # https://github.com/ipython/ipython/issues/8669
+ # io.std* are deprecated, but don't show our own deprecation warnings
+ # during initialization of the deprecated API.
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', DeprecationWarning)
+ io.stdout = io.IOStream(sys.stdout)
+ io.stderr = io.IOStream(sys.stderr)
- def init_magics(self):
- super(TerminalInteractiveShell, self).init_magics()
- self.register_magics(TerminalMagics)
+ def init_magics(self):
+ super(TerminalInteractiveShell, self).init_magics()
+ self.register_magics(TerminalMagics)
def init_alias(self):
# The parent class defines aliases that can be safely used with any
@@ -432,25 +432,25 @@ class TerminalInteractiveShell(InteractiveShell):
# need direct access to the console in a way that we can't emulate in
# GUI or web frontend
if os.name == 'posix':
- for cmd in ['clear', 'more', 'less', 'man']:
- self.alias_manager.soft_define_alias(cmd, cmd)
+ for cmd in ['clear', 'more', 'less', 'man']:
+ self.alias_manager.soft_define_alias(cmd, cmd)
- def __init__(self, *args, **kwargs):
- super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
- self.init_prompt_toolkit_cli()
- self.init_term_title()
- self.keep_running = True
+ def __init__(self, *args, **kwargs):
+ super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
+ self.init_prompt_toolkit_cli()
+ self.init_term_title()
+ self.keep_running = True
- self.debugger_history = InMemoryHistory()
+ self.debugger_history = InMemoryHistory()
- def ask_exit(self):
- self.keep_running = False
+ def ask_exit(self):
+ self.keep_running = False
- rl_next_input = None
+ rl_next_input = None
- def pre_prompt(self):
- if self.rl_next_input:
+ def pre_prompt(self):
+ if self.rl_next_input:
# We can't set the buffer here, because it will be reset just after
# this. Adding a callable to pre_run_callables does what we need
# after the buffer is reset.
@@ -463,37 +463,37 @@ class TerminalInteractiveShell(InteractiveShell):
# Older version of prompt_toolkit; it's OK to set the document
# directly here.
set_doc()
- self.rl_next_input = None
+ self.rl_next_input = None
- def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
+ def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
- if display_banner is not DISPLAY_BANNER_DEPRECATED:
- warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
+ if display_banner is not DISPLAY_BANNER_DEPRECATED:
+ warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
- self.keep_running = True
- while self.keep_running:
- print(self.separate_in, end='')
+ self.keep_running = True
+ while self.keep_running:
+ print(self.separate_in, end='')
try:
- code = self.prompt_for_code()
- except EOFError:
- if (not self.confirm_exit) \
- or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
- self.ask_exit()
+ code = self.prompt_for_code()
+ except EOFError:
+ if (not self.confirm_exit) \
+ or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
+ self.ask_exit()
else:
- if code:
- self.run_cell(code, store_history=True)
-
- def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
- # An extra layer of protection in case someone mashing Ctrl-C breaks
- # out of our internal code.
- if display_banner is not DISPLAY_BANNER_DEPRECATED:
- warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
- while True:
+ if code:
+ self.run_cell(code, store_history=True)
+
+ def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
+ # An extra layer of protection in case someone mashing Ctrl-C breaks
+ # out of our internal code.
+ if display_banner is not DISPLAY_BANNER_DEPRECATED:
+ warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
+ while True:
try:
- self.interact()
- break
+ self.interact()
+ break
except KeyboardInterrupt as e:
print("\n%s escaped interact()\n" % type(e).__name__)
finally:
@@ -504,49 +504,49 @@ class TerminalInteractiveShell(InteractiveShell):
if hasattr(self, '_eventloop'):
self._eventloop.stop()
- _inputhook = None
- def inputhook(self, context):
- if self._inputhook is not None:
- self._inputhook(context)
+ _inputhook = None
+ def inputhook(self, context):
+ if self._inputhook is not None:
+ self._inputhook(context)
active_eventloop = None
- def enable_gui(self, gui=None):
- if gui:
+ def enable_gui(self, gui=None):
+ if gui:
self.active_eventloop, self._inputhook =\
get_inputhook_name_and_func(gui)
- else:
+ else:
self.active_eventloop = self._inputhook = None
- # Run !system commands directly, not through pipes, so terminal programs
- # work correctly.
- system = InteractiveShell.system_raw
+ # Run !system commands directly, not through pipes, so terminal programs
+ # work correctly.
+ system = InteractiveShell.system_raw
- def auto_rewrite_input(self, cmd):
- """Overridden from the parent class to use fancy rewriting prompt"""
- if not self.show_rewritten_input:
- return
+ def auto_rewrite_input(self, cmd):
+ """Overridden from the parent class to use fancy rewriting prompt"""
+ if not self.show_rewritten_input:
+ return
- tokens = self.prompts.rewrite_prompt_tokens()
- if self.pt_cli:
- self.pt_cli.print_tokens(tokens)
- print(cmd)
+ tokens = self.prompts.rewrite_prompt_tokens()
+ if self.pt_cli:
+ self.pt_cli.print_tokens(tokens)
+ print(cmd)
else:
- prompt = ''.join(s for t, s in tokens)
- print(prompt, cmd, sep='')
+ prompt = ''.join(s for t, s in tokens)
+ print(prompt, cmd, sep='')
- _prompts_before = None
- def switch_doctest_mode(self, mode):
- """Switch prompts to classic for %doctest_mode"""
- if mode:
- self._prompts_before = self.prompts
- self.prompts = ClassicPrompts(self)
- elif self._prompts_before:
- self.prompts = self._prompts_before
- self._prompts_before = None
- self._update_layout()
+ _prompts_before = None
+ def switch_doctest_mode(self, mode):
+ """Switch prompts to classic for %doctest_mode"""
+ if mode:
+ self._prompts_before = self.prompts
+ self.prompts = ClassicPrompts(self)
+ elif self._prompts_before:
+ self.prompts = self._prompts_before
+ self._prompts_before = None
+ self._update_layout()
-InteractiveShellABC.register(TerminalInteractiveShell)
+InteractiveShellABC.register(TerminalInteractiveShell)
-if __name__ == '__main__':
- TerminalInteractiveShell.instance().interact()
+if __name__ == '__main__':
+ TerminalInteractiveShell.instance().interact()
diff --git a/contrib/python/ipython/py2/IPython/terminal/ipapp.py b/contrib/python/ipython/py2/IPython/terminal/ipapp.py
index a1181c1b0b..6b25aaa3e3 100755
--- a/contrib/python/ipython/py2/IPython/terminal/ipapp.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ipapp.py
@@ -14,7 +14,7 @@ from __future__ import print_function
import logging
import os
import sys
-import warnings
+import warnings
from traitlets.config.loader import Config
from traitlets.config.application import boolean_flag, catch_config_error, Application
@@ -32,7 +32,7 @@ from IPython.core.shellapp import (
InteractiveShellApp, shell_flags, shell_aliases
)
from IPython.extensions.storemagic import StoreMagics
-from .interactiveshell import TerminalInteractiveShell
+from .interactiveshell import TerminalInteractiveShell
from IPython.paths import get_ipython_dir
from traitlets import (
Bool, List, Dict, default, observe, Type
@@ -101,11 +101,11 @@ addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
'Turn on auto editing of files with syntax errors.',
'Turn off auto editing of files with syntax errors.'
)
-addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
- "Force simple minimal prompt using `raw_input`",
- "Use a rich interactive prompt with prompt_toolkit",
-)
-
+addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
+ "Force simple minimal prompt using `raw_input`",
+ "Use a rich interactive prompt with prompt_toolkit",
+)
+
addflag('banner', 'TerminalIPythonApp.display_banner',
"Display a banner upon starting IPython.",
"Don't display a banner upon starting IPython."
@@ -123,7 +123,7 @@ addflag('term-title', 'TerminalInteractiveShell.term_title',
classic_config = Config()
classic_config.InteractiveShell.cache_size = 0
classic_config.PlainTextFormatter.pprint = False
-classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
+classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
classic_config.InteractiveShell.separate_in = ''
classic_config.InteractiveShell.separate_out = ''
classic_config.InteractiveShell.separate_out2 = ''
@@ -192,7 +192,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
).tag(config=True)
- @default('classes')
+ @default('classes')
def _classes_default(self):
"""This has to be in a method, for TerminalIPythonApp to be available."""
return [
@@ -250,33 +250,33 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
# *do* autocreate requested profile, but don't create the config file.
auto_create=Bool(True)
# configurables
- quick = Bool(False,
+ quick = Bool(False,
help="""Start IPython quickly by skipping the loading of config files."""
- ).tag(config=True)
- @observe('quick')
- def _quick_changed(self, change):
- if change['new']:
+ ).tag(config=True)
+ @observe('quick')
+ def _quick_changed(self, change):
+ if change['new']:
self.load_config_file = lambda *a, **kw: None
- display_banner = Bool(True,
+ display_banner = Bool(True,
help="Whether to display a banner upon starting IPython."
- ).tag(config=True)
+ ).tag(config=True)
# if there is code of files to run from the cmd line, don't interact
# unless the --i flag (App.force_interact) is true.
- force_interact = Bool(False,
+ force_interact = Bool(False,
help="""If a command or file is given via the command-line,
e.g. 'ipython foo.py', start an interactive shell after executing the
file or command."""
- ).tag(config=True)
- @observe('force_interact')
- def _force_interact_changed(self, change):
- if change['new']:
+ ).tag(config=True)
+ @observe('force_interact')
+ def _force_interact_changed(self, change):
+ if change['new']:
self.interact = True
- @observe('file_to_run', 'code_to_run', 'module_to_run')
- def _file_to_run_changed(self, change):
- new = change['new']
+ @observe('file_to_run', 'code_to_run', 'module_to_run')
+ def _file_to_run_changed(self, change):
+ new = change['new']
if new:
self.something_to_run = True
if new and not self.force_interact:
@@ -295,7 +295,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
# warn and transform into current syntax
argv = argv[:] # copy, don't clobber
idx = argv.index('-pylab')
- warnings.warn("`-pylab` flag has been deprecated.\n"
+ warnings.warn("`-pylab` flag has been deprecated.\n"
" Use `--matplotlib <backend>` and import pylab manually.")
argv[idx] = '--pylab'
@@ -328,7 +328,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
# based app, because we call shell.show_banner() by hand below
# so the banner shows *before* all extension loading stuff.
self.shell = self.interactive_shell_class.instance(parent=self,
- profile_dir=self.profile_dir,
+ profile_dir=self.profile_dir,
ipython_dir=self.ipython_dir, user_ns=self.user_ns)
self.shell.configurables.append(self)
@@ -342,7 +342,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
def _pylab_changed(self, name, old, new):
"""Replace --pylab='inline' with --pylab='auto'"""
if new == 'inline':
- warnings.warn("'inline' not available as pylab backend, "
+ warnings.warn("'inline' not available as pylab backend, "
"using 'auto' instead.")
self.pylab = 'auto'
diff --git a/contrib/python/ipython/py2/IPython/terminal/magics.py b/contrib/python/ipython/py2/IPython/terminal/magics.py
index 60f465b0dc..3a844a0397 100644
--- a/contrib/python/ipython/py2/IPython/terminal/magics.py
+++ b/contrib/python/ipython/py2/IPython/terminal/magics.py
@@ -1,208 +1,208 @@
-"""Extra magics for terminal use."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-from logging import error
-import os
-import sys
-
-from IPython.core.error import TryNext, UsageError
-from IPython.core.inputsplitter import IPythonInputSplitter
-from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.lib.clipboard import ClipboardEmpty
-from IPython.utils.text import SList, strip_email_quotes
-from IPython.utils import py3compat
-
-def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
- """ Yield pasted lines until the user enters the given sentinel value.
- """
- if not quiet:
- print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
- % sentinel)
- prompt = ":"
- else:
- prompt = ""
- while True:
- try:
- l = py3compat.str_to_unicode(l_input(prompt))
- if l == sentinel:
- return
- else:
- yield l
- except EOFError:
- print('<EOF>')
- return
-
-
-@magics_class
-class TerminalMagics(Magics):
- def __init__(self, shell):
- super(TerminalMagics, self).__init__(shell)
- self.input_splitter = IPythonInputSplitter()
-
- def store_or_execute(self, block, name):
- """ Execute a block, or store it in a variable, per the user's request.
- """
- if name:
- # If storing it for further editing
- self.shell.user_ns[name] = SList(block.splitlines())
- print("Block assigned to '%s'" % name)
- else:
- b = self.preclean_input(block)
- self.shell.user_ns['pasted_block'] = b
- self.shell.using_paste_magics = True
- try:
- self.shell.run_cell(b)
- finally:
- self.shell.using_paste_magics = False
-
- def preclean_input(self, block):
- lines = block.splitlines()
- while lines and not lines[0].strip():
- lines = lines[1:]
- return strip_email_quotes('\n'.join(lines))
-
- def rerun_pasted(self, name='pasted_block'):
- """ Rerun a previously pasted command.
- """
- b = self.shell.user_ns.get(name)
-
- # Sanity checks
- if b is None:
- raise UsageError('No previous pasted block available')
- if not isinstance(b, py3compat.string_types):
- raise UsageError(
- "Variable 'pasted_block' is not a string, can't execute")
-
- print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
- self.shell.run_cell(b)
-
- @line_magic
- def autoindent(self, parameter_s = ''):
+"""Extra magics for terminal use."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+from logging import error
+import os
+import sys
+
+from IPython.core.error import TryNext, UsageError
+from IPython.core.inputsplitter import IPythonInputSplitter
+from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.lib.clipboard import ClipboardEmpty
+from IPython.utils.text import SList, strip_email_quotes
+from IPython.utils import py3compat
+
+def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
+ """ Yield pasted lines until the user enters the given sentinel value.
+ """
+ if not quiet:
+ print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
+ % sentinel)
+ prompt = ":"
+ else:
+ prompt = ""
+ while True:
+ try:
+ l = py3compat.str_to_unicode(l_input(prompt))
+ if l == sentinel:
+ return
+ else:
+ yield l
+ except EOFError:
+ print('<EOF>')
+ return
+
+
+@magics_class
+class TerminalMagics(Magics):
+ def __init__(self, shell):
+ super(TerminalMagics, self).__init__(shell)
+ self.input_splitter = IPythonInputSplitter()
+
+ def store_or_execute(self, block, name):
+ """ Execute a block, or store it in a variable, per the user's request.
+ """
+ if name:
+ # If storing it for further editing
+ self.shell.user_ns[name] = SList(block.splitlines())
+ print("Block assigned to '%s'" % name)
+ else:
+ b = self.preclean_input(block)
+ self.shell.user_ns['pasted_block'] = b
+ self.shell.using_paste_magics = True
+ try:
+ self.shell.run_cell(b)
+ finally:
+ self.shell.using_paste_magics = False
+
+ def preclean_input(self, block):
+ lines = block.splitlines()
+ while lines and not lines[0].strip():
+ lines = lines[1:]
+ return strip_email_quotes('\n'.join(lines))
+
+ def rerun_pasted(self, name='pasted_block'):
+ """ Rerun a previously pasted command.
+ """
+ b = self.shell.user_ns.get(name)
+
+ # Sanity checks
+ if b is None:
+ raise UsageError('No previous pasted block available')
+ if not isinstance(b, py3compat.string_types):
+ raise UsageError(
+ "Variable 'pasted_block' is not a string, can't execute")
+
+ print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
+ self.shell.run_cell(b)
+
+ @line_magic
+ def autoindent(self, parameter_s = ''):
"""Toggle autoindent on/off (deprecated)"""
print("%autoindent is deprecated since IPython 5: you can now paste "
"multiple lines without turning autoindentation off.")
- self.shell.set_autoindent()
- print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
-
- @line_magic
- def cpaste(self, parameter_s=''):
- """Paste & execute a pre-formatted code block from clipboard.
-
- You must terminate the block with '--' (two minus-signs) or Ctrl-D
- alone on the line. You can also provide your own sentinel with '%paste
- -s %%' ('%%' is the new sentinel for this operation).
-
- The block is dedented prior to execution to enable execution of method
- definitions. '>' and '+' characters at the beginning of a line are
- ignored, to allow pasting directly from e-mails, diff files and
- doctests (the '...' continuation prompt is also stripped). The
- executed block is also assigned to variable named 'pasted_block' for
- later editing with '%edit pasted_block'.
-
- You can also pass a variable name as an argument, e.g. '%cpaste foo'.
- This assigns the pasted block to variable 'foo' as string, without
- dedenting or executing it (preceding >>> and + is still stripped)
-
- '%cpaste -r' re-executes the block previously entered by cpaste.
- '%cpaste -q' suppresses any additional output messages.
-
- Do not be alarmed by garbled output on Windows (it's a readline bug).
- Just press enter and type -- (and press enter again) and the block
- will be what was just pasted.
-
- IPython statements (magics, shell escapes) are not supported (yet).
-
- See also
- --------
- paste: automatically pull code from clipboard.
-
- Examples
- --------
- ::
-
- In [8]: %cpaste
- Pasting code; enter '--' alone on the line to stop.
- :>>> a = ["world!", "Hello"]
- :>>> print " ".join(sorted(a))
- :--
- Hello world!
- """
- opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
- if 'r' in opts:
- self.rerun_pasted()
- return
-
- quiet = ('q' in opts)
-
- sentinel = opts.get('s', u'--')
- block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
- self.store_or_execute(block, name)
-
- @line_magic
- def paste(self, parameter_s=''):
- """Paste & execute a pre-formatted code block from clipboard.
-
- The text is pulled directly from the clipboard without user
- intervention and printed back on the screen before execution (unless
- the -q flag is given to force quiet mode).
-
- The block is dedented prior to execution to enable execution of method
- definitions. '>' and '+' characters at the beginning of a line are
- ignored, to allow pasting directly from e-mails, diff files and
- doctests (the '...' continuation prompt is also stripped). The
- executed block is also assigned to variable named 'pasted_block' for
- later editing with '%edit pasted_block'.
-
- You can also pass a variable name as an argument, e.g. '%paste foo'.
- This assigns the pasted block to variable 'foo' as string, without
- executing it (preceding >>> and + is still stripped).
-
- Options:
-
- -r: re-executes the block previously entered by cpaste.
-
- -q: quiet mode: do not echo the pasted text back to the terminal.
-
- IPython statements (magics, shell escapes) are not supported (yet).
-
- See also
- --------
- cpaste: manually paste code into terminal until you mark its end.
- """
- opts, name = self.parse_options(parameter_s, 'rq', mode='string')
- if 'r' in opts:
- self.rerun_pasted()
- return
- try:
- block = self.shell.hooks.clipboard_get()
- except TryNext as clipboard_exc:
- message = getattr(clipboard_exc, 'args')
- if message:
- error(message[0])
- else:
- error('Could not get text from the clipboard.')
- return
- except ClipboardEmpty:
- raise UsageError("The clipboard appears to be empty")
-
- # By default, echo back to terminal unless quiet mode is requested
- if 'q' not in opts:
- write = self.shell.write
- write(self.shell.pycolorize(block))
- if not block.endswith('\n'):
- write('\n')
- write("## -- End pasted text --\n")
-
- self.store_or_execute(block, name)
-
- # Class-level: add a '%cls' magic only on Windows
- if sys.platform == 'win32':
- @line_magic
- def cls(self, s):
- """Clear screen.
- """
- os.system("cls")
+ self.shell.set_autoindent()
+ print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
+
+ @line_magic
+ def cpaste(self, parameter_s=''):
+ """Paste & execute a pre-formatted code block from clipboard.
+
+ You must terminate the block with '--' (two minus-signs) or Ctrl-D
+ alone on the line. You can also provide your own sentinel with '%paste
+ -s %%' ('%%' is the new sentinel for this operation).
+
+ The block is dedented prior to execution to enable execution of method
+ definitions. '>' and '+' characters at the beginning of a line are
+ ignored, to allow pasting directly from e-mails, diff files and
+ doctests (the '...' continuation prompt is also stripped). The
+ executed block is also assigned to variable named 'pasted_block' for
+ later editing with '%edit pasted_block'.
+
+ You can also pass a variable name as an argument, e.g. '%cpaste foo'.
+ This assigns the pasted block to variable 'foo' as string, without
+ dedenting or executing it (preceding >>> and + is still stripped)
+
+ '%cpaste -r' re-executes the block previously entered by cpaste.
+ '%cpaste -q' suppresses any additional output messages.
+
+ Do not be alarmed by garbled output on Windows (it's a readline bug).
+ Just press enter and type -- (and press enter again) and the block
+ will be what was just pasted.
+
+ IPython statements (magics, shell escapes) are not supported (yet).
+
+ See also
+ --------
+ paste: automatically pull code from clipboard.
+
+ Examples
+ --------
+ ::
+
+ In [8]: %cpaste
+ Pasting code; enter '--' alone on the line to stop.
+ :>>> a = ["world!", "Hello"]
+ :>>> print " ".join(sorted(a))
+ :--
+ Hello world!
+ """
+ opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
+ if 'r' in opts:
+ self.rerun_pasted()
+ return
+
+ quiet = ('q' in opts)
+
+ sentinel = opts.get('s', u'--')
+ block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
+ self.store_or_execute(block, name)
+
+ @line_magic
+ def paste(self, parameter_s=''):
+ """Paste & execute a pre-formatted code block from clipboard.
+
+ The text is pulled directly from the clipboard without user
+ intervention and printed back on the screen before execution (unless
+ the -q flag is given to force quiet mode).
+
+ The block is dedented prior to execution to enable execution of method
+ definitions. '>' and '+' characters at the beginning of a line are
+ ignored, to allow pasting directly from e-mails, diff files and
+ doctests (the '...' continuation prompt is also stripped). The
+ executed block is also assigned to variable named 'pasted_block' for
+ later editing with '%edit pasted_block'.
+
+ You can also pass a variable name as an argument, e.g. '%paste foo'.
+ This assigns the pasted block to variable 'foo' as string, without
+ executing it (preceding >>> and + is still stripped).
+
+ Options:
+
+ -r: re-executes the block previously entered by cpaste.
+
+ -q: quiet mode: do not echo the pasted text back to the terminal.
+
+ IPython statements (magics, shell escapes) are not supported (yet).
+
+ See also
+ --------
+ cpaste: manually paste code into terminal until you mark its end.
+ """
+ opts, name = self.parse_options(parameter_s, 'rq', mode='string')
+ if 'r' in opts:
+ self.rerun_pasted()
+ return
+ try:
+ block = self.shell.hooks.clipboard_get()
+ except TryNext as clipboard_exc:
+ message = getattr(clipboard_exc, 'args')
+ if message:
+ error(message[0])
+ else:
+ error('Could not get text from the clipboard.')
+ return
+ except ClipboardEmpty:
+ raise UsageError("The clipboard appears to be empty")
+
+ # By default, echo back to terminal unless quiet mode is requested
+ if 'q' not in opts:
+ write = self.shell.write
+ write(self.shell.pycolorize(block))
+ if not block.endswith('\n'):
+ write('\n')
+ write("## -- End pasted text --\n")
+
+ self.store_or_execute(block, name)
+
+ # Class-level: add a '%cls' magic only on Windows
+ if sys.platform == 'win32':
+ @line_magic
+ def cls(self, s):
+ """Clear screen.
+ """
+ os.system("cls")
diff --git a/contrib/python/ipython/py2/IPython/terminal/prompts.py b/contrib/python/ipython/py2/IPython/terminal/prompts.py
index a2203fe417..43c2170503 100644
--- a/contrib/python/ipython/py2/IPython/terminal/prompts.py
+++ b/contrib/python/ipython/py2/IPython/terminal/prompts.py
@@ -1,80 +1,80 @@
-"""Terminal input and output prompts."""
-from __future__ import print_function
-
-from pygments.token import Token
-import sys
-
-from IPython.core.displayhook import DisplayHook
-
-from prompt_toolkit.layout.utils import token_list_width
-
-class Prompts(object):
- def __init__(self, shell):
- self.shell = shell
-
- def in_prompt_tokens(self, cli=None):
- return [
- (Token.Prompt, 'In ['),
- (Token.PromptNum, str(self.shell.execution_count)),
- (Token.Prompt, ']: '),
- ]
-
- def _width(self):
- return token_list_width(self.in_prompt_tokens())
-
- def continuation_prompt_tokens(self, cli=None, width=None):
- if width is None:
- width = self._width()
- return [
- (Token.Prompt, (' ' * (width - 5)) + '...: '),
- ]
-
- def rewrite_prompt_tokens(self):
- width = self._width()
- return [
- (Token.Prompt, ('-' * (width - 2)) + '> '),
- ]
-
- def out_prompt_tokens(self):
- return [
- (Token.OutPrompt, 'Out['),
- (Token.OutPromptNum, str(self.shell.execution_count)),
- (Token.OutPrompt, ']: '),
- ]
-
-class ClassicPrompts(Prompts):
- def in_prompt_tokens(self, cli=None):
- return [
- (Token.Prompt, '>>> '),
- ]
-
- def continuation_prompt_tokens(self, cli=None, width=None):
- return [
- (Token.Prompt, '... ')
- ]
-
- def rewrite_prompt_tokens(self):
- return []
-
- def out_prompt_tokens(self):
- return []
-
-class RichPromptDisplayHook(DisplayHook):
- """Subclass of base display hook using coloured prompt"""
- def write_output_prompt(self):
- sys.stdout.write(self.shell.separate_out)
+"""Terminal input and output prompts."""
+from __future__ import print_function
+
+from pygments.token import Token
+import sys
+
+from IPython.core.displayhook import DisplayHook
+
+from prompt_toolkit.layout.utils import token_list_width
+
+class Prompts(object):
+ def __init__(self, shell):
+ self.shell = shell
+
+ def in_prompt_tokens(self, cli=None):
+ return [
+ (Token.Prompt, 'In ['),
+ (Token.PromptNum, str(self.shell.execution_count)),
+ (Token.Prompt, ']: '),
+ ]
+
+ def _width(self):
+ return token_list_width(self.in_prompt_tokens())
+
+ def continuation_prompt_tokens(self, cli=None, width=None):
+ if width is None:
+ width = self._width()
+ return [
+ (Token.Prompt, (' ' * (width - 5)) + '...: '),
+ ]
+
+ def rewrite_prompt_tokens(self):
+ width = self._width()
+ return [
+ (Token.Prompt, ('-' * (width - 2)) + '> '),
+ ]
+
+ def out_prompt_tokens(self):
+ return [
+ (Token.OutPrompt, 'Out['),
+ (Token.OutPromptNum, str(self.shell.execution_count)),
+ (Token.OutPrompt, ']: '),
+ ]
+
+class ClassicPrompts(Prompts):
+ def in_prompt_tokens(self, cli=None):
+ return [
+ (Token.Prompt, '>>> '),
+ ]
+
+ def continuation_prompt_tokens(self, cli=None, width=None):
+ return [
+ (Token.Prompt, '... ')
+ ]
+
+ def rewrite_prompt_tokens(self):
+ return []
+
+ def out_prompt_tokens(self):
+ return []
+
+class RichPromptDisplayHook(DisplayHook):
+ """Subclass of base display hook using coloured prompt"""
+ def write_output_prompt(self):
+ sys.stdout.write(self.shell.separate_out)
# If we're not displaying a prompt, it effectively ends with a newline,
# because the output will be left-aligned.
self.prompt_end_newline = True
- if self.do_full_cache:
- tokens = self.shell.prompts.out_prompt_tokens()
+ if self.do_full_cache:
+ tokens = self.shell.prompts.out_prompt_tokens()
prompt_txt = ''.join(s for t, s in tokens)
if prompt_txt and not prompt_txt.endswith('\n'):
# Ask for a newline before multiline output
self.prompt_end_newline = False
- if self.shell.pt_cli:
- self.shell.pt_cli.print_tokens(tokens)
- else:
+ if self.shell.pt_cli:
+ self.shell.pt_cli.print_tokens(tokens)
+ else:
sys.stdout.write(prompt_txt)
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py
index 95fdad0b59..3766973e82 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py
@@ -1,49 +1,49 @@
-import importlib
-import os
-
-aliases = {
- 'qt4': 'qt',
- 'gtk2': 'gtk',
-}
-
-backends = [
- 'qt', 'qt4', 'qt5',
- 'gtk', 'gtk2', 'gtk3',
- 'tk',
- 'wx',
- 'pyglet', 'glut',
- 'osx',
-]
-
-registered = {}
-
-def register(name, inputhook):
- """Register the function *inputhook* as an event loop integration."""
- registered[name] = inputhook
-
-class UnknownBackend(KeyError):
- def __init__(self, name):
- self.name = name
-
- def __str__(self):
- return ("No event loop integration for {!r}. "
- "Supported event loops are: {}").format(self.name,
- ', '.join(backends + sorted(registered)))
-
+import importlib
+import os
+
+aliases = {
+ 'qt4': 'qt',
+ 'gtk2': 'gtk',
+}
+
+backends = [
+ 'qt', 'qt4', 'qt5',
+ 'gtk', 'gtk2', 'gtk3',
+ 'tk',
+ 'wx',
+ 'pyglet', 'glut',
+ 'osx',
+]
+
+registered = {}
+
+def register(name, inputhook):
+ """Register the function *inputhook* as an event loop integration."""
+ registered[name] = inputhook
+
+class UnknownBackend(KeyError):
+ def __init__(self, name):
+ self.name = name
+
+ def __str__(self):
+ return ("No event loop integration for {!r}. "
+ "Supported event loops are: {}").format(self.name,
+ ', '.join(backends + sorted(registered)))
+
def get_inputhook_name_and_func(gui):
- if gui in registered:
+ if gui in registered:
return gui, registered[gui]
-
- if gui not in backends:
- raise UnknownBackend(gui)
-
- if gui in aliases:
+
+ if gui not in backends:
+ raise UnknownBackend(gui)
+
+ if gui in aliases:
return get_inputhook_name_and_func(aliases[gui])
-
+
gui_mod = gui
- if gui == 'qt5':
- os.environ['QT_API'] = 'pyqt5'
+ if gui == 'qt5':
+ os.environ['QT_API'] = 'pyqt5'
gui_mod = 'qt'
-
+
mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod)
return gui, mod.inputhook
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py
index d6b1387649..f336e6830f 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py
@@ -1,141 +1,141 @@
-"""GLUT Input hook for interactive use with prompt_toolkit
-"""
-from __future__ import print_function
-
-
-# GLUT is quite an old library and it is difficult to ensure proper
-# integration within IPython since original GLUT does not allow to handle
-# events one by one. Instead, it requires for the mainloop to be entered
-# and never returned (there is not even a function to exit he
-# mainloop). Fortunately, there are alternatives such as freeglut
-# (available for linux and windows) and the OSX implementation gives
-# access to a glutCheckLoop() function that blocks itself until a new
-# event is received. This means we have to setup the idle callback to
-# ensure we got at least one event that will unblock the function.
-#
-# Furthermore, it is not possible to install these handlers without a window
-# being first created. We choose to make this window invisible. This means that
-# display mode options are set at this level and user won't be able to change
-# them later without modifying the code. This should probably be made available
-# via IPython options system.
-
-import sys
-import time
-import signal
-import OpenGL.GLUT as glut
-import OpenGL.platform as platform
-from timeit import default_timer as clock
-
-# Frame per second : 60
-# Should probably be an IPython option
-glut_fps = 60
-
-# Display mode : double buffeed + rgba + depth
-# Should probably be an IPython option
-glut_display_mode = (glut.GLUT_DOUBLE |
- glut.GLUT_RGBA |
- glut.GLUT_DEPTH)
-
-glutMainLoopEvent = None
-if sys.platform == 'darwin':
- try:
- glutCheckLoop = platform.createBaseFunction(
- 'glutCheckLoop', dll=platform.GLUT, resultType=None,
- argTypes=[],
- doc='glutCheckLoop( ) -> None',
- argNames=(),
- )
- except AttributeError:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions'''
- '''Consider installing freeglut.''')
- glutMainLoopEvent = glutCheckLoop
-elif glut.HAVE_FREEGLUT:
- glutMainLoopEvent = glut.glutMainLoopEvent
-else:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions. '''
- '''Consider installing freeglut.''')
-
-
-def glut_display():
- # Dummy display function
- pass
-
-def glut_idle():
- # Dummy idle function
- pass
-
-def glut_close():
- # Close function only hides the current window
- glut.glutHideWindow()
- glutMainLoopEvent()
-
-def glut_int_handler(signum, frame):
- # Catch sigint and print the defaultipyt message
- signal.signal(signal.SIGINT, signal.default_int_handler)
- print('\nKeyboardInterrupt')
- # Need to reprint the prompt at this stage
-
-# Initialisation code
-glut.glutInit( sys.argv )
-glut.glutInitDisplayMode( glut_display_mode )
-# This is specific to freeglut
-if bool(glut.glutSetOption):
- glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
- glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
-glut.glutCreateWindow( b'ipython' )
-glut.glutReshapeWindow( 1, 1 )
-glut.glutHideWindow( )
-glut.glutWMCloseFunc( glut_close )
-glut.glutDisplayFunc( glut_display )
-glut.glutIdleFunc( glut_idle )
-
-
-def inputhook(context):
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
-
- signal.signal(signal.SIGINT, glut_int_handler)
-
- try:
- t = clock()
-
- # Make sure the default window is set after a window has been closed
- if glut.glutGetWindow() == 0:
- glut.glutSetWindow( 1 )
- glutMainLoopEvent()
- return 0
-
- while not context.input_is_ready():
- glutMainLoopEvent()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
+"""GLUT Input hook for interactive use with prompt_toolkit
+"""
+from __future__ import print_function
+
+
+# GLUT is quite an old library and it is difficult to ensure proper
+# integration within IPython since original GLUT does not allow to handle
+# events one by one. Instead, it requires for the mainloop to be entered
+# and never returned (there is not even a function to exit he
+# mainloop). Fortunately, there are alternatives such as freeglut
+# (available for linux and windows) and the OSX implementation gives
+# access to a glutCheckLoop() function that blocks itself until a new
+# event is received. This means we have to setup the idle callback to
+# ensure we got at least one event that will unblock the function.
+#
+# Furthermore, it is not possible to install these handlers without a window
+# being first created. We choose to make this window invisible. This means that
+# display mode options are set at this level and user won't be able to change
+# them later without modifying the code. This should probably be made available
+# via IPython options system.
+
+import sys
+import time
+import signal
+import OpenGL.GLUT as glut
+import OpenGL.platform as platform
+from timeit import default_timer as clock
+
+# Frame per second : 60
+# Should probably be an IPython option
+glut_fps = 60
+
+# Display mode : double buffeed + rgba + depth
+# Should probably be an IPython option
+glut_display_mode = (glut.GLUT_DOUBLE |
+ glut.GLUT_RGBA |
+ glut.GLUT_DEPTH)
+
+glutMainLoopEvent = None
+if sys.platform == 'darwin':
+ try:
+ glutCheckLoop = platform.createBaseFunction(
+ 'glutCheckLoop', dll=platform.GLUT, resultType=None,
+ argTypes=[],
+ doc='glutCheckLoop( ) -> None',
+ argNames=(),
+ )
+ except AttributeError:
+ raise RuntimeError(
+ '''Your glut implementation does not allow interactive sessions'''
+ '''Consider installing freeglut.''')
+ glutMainLoopEvent = glutCheckLoop
+elif glut.HAVE_FREEGLUT:
+ glutMainLoopEvent = glut.glutMainLoopEvent
+else:
+ raise RuntimeError(
+ '''Your glut implementation does not allow interactive sessions. '''
+ '''Consider installing freeglut.''')
+
+
+def glut_display():
+ # Dummy display function
+ pass
+
+def glut_idle():
+ # Dummy idle function
+ pass
+
+def glut_close():
+ # Close function only hides the current window
+ glut.glutHideWindow()
+ glutMainLoopEvent()
+
+def glut_int_handler(signum, frame):
+ # Catch sigint and print the defaultipyt message
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+ print('\nKeyboardInterrupt')
+ # Need to reprint the prompt at this stage
+
+# Initialisation code
+glut.glutInit( sys.argv )
+glut.glutInitDisplayMode( glut_display_mode )
+# This is specific to freeglut
+if bool(glut.glutSetOption):
+ glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
+ glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
+glut.glutCreateWindow( b'ipython' )
+glut.glutReshapeWindow( 1, 1 )
+glut.glutHideWindow( )
+glut.glutWMCloseFunc( glut_close )
+glut.glutDisplayFunc( glut_display )
+glut.glutIdleFunc( glut_idle )
+
+
+def inputhook(context):
+ """Run the pyglet event loop by processing pending events only.
+
+ This keeps processing pending events until stdin is ready. After
+ processing all pending events, a call to time.sleep is inserted. This is
+ needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
+ though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+
+ signal.signal(signal.SIGINT, glut_int_handler)
+
+ try:
+ t = clock()
+
+ # Make sure the default window is set after a window has been closed
+ if glut.glutGetWindow() == 0:
+ glut.glutSetWindow( 1 )
+ glutMainLoopEvent()
+ return 0
+
+ while not context.input_is_ready():
+ glutMainLoopEvent()
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ except KeyboardInterrupt:
+ pass
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py
index ac7529ca00..8f27e12c46 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py
@@ -1,59 +1,59 @@
-# Code borrowed from python-prompt-toolkit examples
-# https://github.com/jonathanslenders/python-prompt-toolkit/blob/77cdcfbc7f4b4c34a9d2f9a34d422d7152f16209/examples/inputhook.py
-
-# Copyright (c) 2014, Jonathan Slenders
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without modification,
-# are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright notice, this
-# list of conditions and the following disclaimer in the documentation and/or
-# other materials provided with the distribution.
-#
-# * Neither the name of the {organization} nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
-# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""
-PyGTK input hook for prompt_toolkit.
-
-Listens on the pipe prompt_toolkit sets up for a notification that it should
-return control to the terminal event loop.
-"""
-from __future__ import absolute_import
-
-import gtk, gobject
-
-# Enable threading in GTK. (Otherwise, GTK will keep the GIL.)
-gtk.gdk.threads_init()
-
-def inputhook(context):
- """
- When the eventloop of prompt-toolkit is idle, call this inputhook.
-
- This will run the GTK main loop until the file descriptor
- `context.fileno()` becomes ready.
-
- :param context: An `InputHookContext` instance.
- """
- def _main_quit(*a, **kw):
- gtk.main_quit()
- return False
-
- gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
- gtk.main()
+# Code borrowed from python-prompt-toolkit examples
+# https://github.com/jonathanslenders/python-prompt-toolkit/blob/77cdcfbc7f4b4c34a9d2f9a34d422d7152f16209/examples/inputhook.py
+
+# Copyright (c) 2014, Jonathan Slenders
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice, this
+# list of conditions and the following disclaimer in the documentation and/or
+# other materials provided with the distribution.
+#
+# * Neither the name of the {organization} nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""
+PyGTK input hook for prompt_toolkit.
+
+Listens on the pipe prompt_toolkit sets up for a notification that it should
+return control to the terminal event loop.
+"""
+from __future__ import absolute_import
+
+import gtk, gobject
+
+# Enable threading in GTK. (Otherwise, GTK will keep the GIL.)
+gtk.gdk.threads_init()
+
+def inputhook(context):
+ """
+ When the eventloop of prompt-toolkit is idle, call this inputhook.
+
+ This will run the GTK main loop until the file descriptor
+ `context.fileno()` becomes ready.
+
+ :param context: An `InputHookContext` instance.
+ """
+ def _main_quit(*a, **kw):
+ gtk.main_quit()
+ return False
+
+ gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
+ gtk.main()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py
index 40d6673359..5c6c545457 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py
@@ -1,12 +1,12 @@
-"""prompt_toolkit input hook for GTK 3
-"""
-
-from gi.repository import Gtk, GLib
-
-def _main_quit(*args, **kwargs):
- Gtk.main_quit()
- return False
-
-def inputhook(context):
- GLib.io_add_watch(context.fileno(), GLib.IO_IN, _main_quit)
- Gtk.main()
+"""prompt_toolkit input hook for GTK 3
+"""
+
+from gi.repository import Gtk, GLib
+
+def _main_quit(*args, **kwargs):
+ Gtk.main_quit()
+ return False
+
+def inputhook(context):
+ GLib.io_add_watch(context.fileno(), GLib.IO_IN, _main_quit)
+ Gtk.main()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py
index b916ee0540..53f4e3838b 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py
@@ -1,137 +1,137 @@
-"""Inputhook for OS X
-
-Calls NSApp / CoreFoundation APIs via ctypes.
-"""
-
-# obj-c boilerplate from appnope, used under BSD 2-clause
-
-import ctypes
-import ctypes.util
-from threading import Event
-
-objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
-
-void_p = ctypes.c_void_p
-
-objc.objc_getClass.restype = void_p
-objc.sel_registerName.restype = void_p
-objc.objc_msgSend.restype = void_p
-objc.objc_msgSend.argtypes = [void_p, void_p]
-
-msg = objc.objc_msgSend
-
-def _utf8(s):
- """ensure utf8 bytes"""
- if not isinstance(s, bytes):
- s = s.encode('utf8')
- return s
-
-def n(name):
- """create a selector name (for ObjC methods)"""
- return objc.sel_registerName(_utf8(name))
-
-def C(classname):
- """get an ObjC Class by name"""
- return objc.objc_getClass(_utf8(classname))
-
-# end obj-c boilerplate from appnope
-
-# CoreFoundation C-API calls we will use:
-CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
-
-CFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate
-CFFileDescriptorCreate.restype = void_p
-CFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]
-
-CFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor
-CFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int
-CFFileDescriptorGetNativeDescriptor.argtypes = [void_p]
-
-CFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks
-CFFileDescriptorEnableCallBacks.restype = None
-CFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]
-
-CFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource
-CFFileDescriptorCreateRunLoopSource.restype = void_p
-CFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]
-
-CFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent
-CFRunLoopGetCurrent.restype = void_p
-
-CFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource
-CFRunLoopAddSource.restype = None
-CFRunLoopAddSource.argtypes = [void_p, void_p, void_p]
-
-CFRelease = CoreFoundation.CFRelease
-CFRelease.restype = None
-CFRelease.argtypes = [void_p]
-
-CFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate
-CFFileDescriptorInvalidate.restype = None
-CFFileDescriptorInvalidate.argtypes = [void_p]
-
-# From CFFileDescriptor.h
-kCFFileDescriptorReadCallBack = 1
-kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')
-
-
-def _NSApp():
- """Return the global NSApplication instance (NSApp)"""
- return msg(C('NSApplication'), n('sharedApplication'))
-
-
-def _wake(NSApp):
- """Wake the Application"""
- event = msg(C('NSEvent'),
- n('otherEventWithType:location:modifierFlags:'
- 'timestamp:windowNumber:context:subtype:data1:data2:'),
- 15, # Type
- 0, # location
- 0, # flags
- 0, # timestamp
- 0, # window
- None, # context
- 0, # subtype
- 0, # data1
- 0, # data2
- )
- msg(NSApp, n('postEvent:atStart:'), void_p(event), True)
-
-
-_triggered = Event()
-
-def _input_callback(fdref, flags, info):
- """Callback to fire when there's input to be read"""
- _triggered.set()
- CFFileDescriptorInvalidate(fdref)
- CFRelease(fdref)
- NSApp = _NSApp()
- msg(NSApp, n('stop:'), NSApp)
- _wake(NSApp)
-
-_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)
-_c_input_callback = _c_callback_func_type(_input_callback)
-
-
-def _stop_on_read(fd):
- """Register callback to stop eventloop when there's data on fd"""
- _triggered.clear()
- fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)
- CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)
- source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)
- loop = CFRunLoopGetCurrent()
- CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
- CFRelease(source)
-
-
-def inputhook(context):
- """Inputhook for Cocoa (NSApp)"""
- NSApp = _NSApp()
- _stop_on_read(context.fileno())
- msg(NSApp, n('run'))
- if not _triggered.is_set():
- # app closed without firing callback,
- # probably due to last window being closed.
- # Run the loop manually in this case,
- # since there may be events still to process (#9734)
- CoreFoundation.CFRunLoopRun()
+"""Inputhook for OS X
+
+Calls NSApp / CoreFoundation APIs via ctypes.
+"""
+
+# obj-c boilerplate from appnope, used under BSD 2-clause
+
+import ctypes
+import ctypes.util
+from threading import Event
+
+objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
+
+void_p = ctypes.c_void_p
+
+objc.objc_getClass.restype = void_p
+objc.sel_registerName.restype = void_p
+objc.objc_msgSend.restype = void_p
+objc.objc_msgSend.argtypes = [void_p, void_p]
+
+msg = objc.objc_msgSend
+
+def _utf8(s):
+ """ensure utf8 bytes"""
+ if not isinstance(s, bytes):
+ s = s.encode('utf8')
+ return s
+
+def n(name):
+ """create a selector name (for ObjC methods)"""
+ return objc.sel_registerName(_utf8(name))
+
+def C(classname):
+ """get an ObjC Class by name"""
+ return objc.objc_getClass(_utf8(classname))
+
+# end obj-c boilerplate from appnope
+
+# CoreFoundation C-API calls we will use:
+CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
+
+CFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate
+CFFileDescriptorCreate.restype = void_p
+CFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]
+
+CFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor
+CFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int
+CFFileDescriptorGetNativeDescriptor.argtypes = [void_p]
+
+CFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks
+CFFileDescriptorEnableCallBacks.restype = None
+CFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]
+
+CFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource
+CFFileDescriptorCreateRunLoopSource.restype = void_p
+CFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]
+
+CFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent
+CFRunLoopGetCurrent.restype = void_p
+
+CFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource
+CFRunLoopAddSource.restype = None
+CFRunLoopAddSource.argtypes = [void_p, void_p, void_p]
+
+CFRelease = CoreFoundation.CFRelease
+CFRelease.restype = None
+CFRelease.argtypes = [void_p]
+
+CFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate
+CFFileDescriptorInvalidate.restype = None
+CFFileDescriptorInvalidate.argtypes = [void_p]
+
+# From CFFileDescriptor.h
+kCFFileDescriptorReadCallBack = 1
+kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')
+
+
+def _NSApp():
+ """Return the global NSApplication instance (NSApp)"""
+ return msg(C('NSApplication'), n('sharedApplication'))
+
+
+def _wake(NSApp):
+ """Wake the Application"""
+ event = msg(C('NSEvent'),
+ n('otherEventWithType:location:modifierFlags:'
+ 'timestamp:windowNumber:context:subtype:data1:data2:'),
+ 15, # Type
+ 0, # location
+ 0, # flags
+ 0, # timestamp
+ 0, # window
+ None, # context
+ 0, # subtype
+ 0, # data1
+ 0, # data2
+ )
+ msg(NSApp, n('postEvent:atStart:'), void_p(event), True)
+
+
+_triggered = Event()
+
+def _input_callback(fdref, flags, info):
+ """Callback to fire when there's input to be read"""
+ _triggered.set()
+ CFFileDescriptorInvalidate(fdref)
+ CFRelease(fdref)
+ NSApp = _NSApp()
+ msg(NSApp, n('stop:'), NSApp)
+ _wake(NSApp)
+
+_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)
+_c_input_callback = _c_callback_func_type(_input_callback)
+
+
+def _stop_on_read(fd):
+ """Register callback to stop eventloop when there's data on fd"""
+ _triggered.clear()
+ fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)
+ CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)
+ source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)
+ loop = CFRunLoopGetCurrent()
+ CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
+ CFRelease(source)
+
+
+def inputhook(context):
+ """Inputhook for Cocoa (NSApp)"""
+ NSApp = _NSApp()
+ _stop_on_read(context.fileno())
+ msg(NSApp, n('run'))
+ if not _triggered.is_set():
+ # app closed without firing callback,
+ # probably due to last window being closed.
+ # Run the loop manually in this case,
+ # since there may be events still to process (#9734)
+ CoreFoundation.CFRunLoopRun()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py
index 4fbf790b57..1c5ec44250 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py
@@ -1,68 +1,68 @@
-"""Enable pyglet to be used interacively with prompt_toolkit
-"""
-from __future__ import absolute_import
-
-import os
-import sys
-import time
-from timeit import default_timer as clock
-import pyglet
-
-# On linux only, window.flip() has a bug that causes an AttributeError on
-# window close. For details, see:
-# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
-
-if sys.platform.startswith('linux'):
- def flip(window):
- try:
- window.flip()
- except AttributeError:
- pass
-else:
- def flip(window):
- window.flip()
-
-
-def inputhook(context):
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- t = clock()
- while not context.input_is_ready():
- pyglet.clock.tick()
- for window in pyglet.app.windows:
- window.switch_to()
- window.dispatch_events()
- window.dispatch_event('on_draw')
- flip(window)
-
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
+"""Enable pyglet to be used interacively with prompt_toolkit
+"""
+from __future__ import absolute_import
+
+import os
+import sys
+import time
+from timeit import default_timer as clock
+import pyglet
+
+# On linux only, window.flip() has a bug that causes an AttributeError on
+# window close. For details, see:
+# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
+
+if sys.platform.startswith('linux'):
+ def flip(window):
+ try:
+ window.flip()
+ except AttributeError:
+ pass
+else:
+ def flip(window):
+ window.flip()
+
+
+def inputhook(context):
+ """Run the pyglet event loop by processing pending events only.
+
+ This keeps processing pending events until stdin is ready. After
+ processing all pending events, a call to time.sleep is inserted. This is
+ needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
+ though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+ try:
+ t = clock()
+ while not context.input_is_ready():
+ pyglet.clock.tick()
+ for window in pyglet.app.windows:
+ window.switch_to()
+ window.dispatch_events()
+ window.dispatch_event('on_draw')
+ flip(window)
+
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ except KeyboardInterrupt:
+ pass
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py
index 5667cd8478..7395ac39eb 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py
@@ -1,16 +1,16 @@
-import sys
+import sys
import os
-from IPython.external.qt_for_kernel import QtCore, QtGui
-
-# If we create a QApplication, keep a reference to it so that it doesn't get
-# garbage collected.
-_appref = None
+from IPython.external.qt_for_kernel import QtCore, QtGui
+
+# If we create a QApplication, keep a reference to it so that it doesn't get
+# garbage collected.
+_appref = None
_already_warned = False
-
-def inputhook(context):
- global _appref
- app = QtCore.QCoreApplication.instance()
- if not app:
+
+def inputhook(context):
+ global _appref
+ app = QtCore.QCoreApplication.instance()
+ if not app:
if sys.platform == 'linux':
if not os.environ.get('DISPLAY') \
and not os.environ.get('WAYLAND_DISPLAY'):
@@ -24,26 +24,26 @@ def inputhook(context):
'variable. Deactivate Qt5 code.'
)
return
- _appref = app = QtGui.QApplication([" "])
- event_loop = QtCore.QEventLoop(app)
-
- if sys.platform == 'win32':
- # The QSocketNotifier method doesn't appear to work on Windows.
- # Use polling instead.
- timer = QtCore.QTimer()
- timer.timeout.connect(event_loop.quit)
- while not context.input_is_ready():
- timer.start(50) # 50 ms
- event_loop.exec_()
- timer.stop()
- else:
- # On POSIX platforms, we can use a file descriptor to quit the event
- # loop when there is input ready to read.
+ _appref = app = QtGui.QApplication([" "])
+ event_loop = QtCore.QEventLoop(app)
+
+ if sys.platform == 'win32':
+ # The QSocketNotifier method doesn't appear to work on Windows.
+ # Use polling instead.
+ timer = QtCore.QTimer()
+ timer.timeout.connect(event_loop.quit)
+ while not context.input_is_ready():
+ timer.start(50) # 50 ms
+ event_loop.exec_()
+ timer.stop()
+ else:
+ # On POSIX platforms, we can use a file descriptor to quit the event
+ # loop when there is input ready to read.
notifier = QtCore.QSocketNotifier(context.fileno(),
QtCore.QSocketNotifier.Read)
# connect the callback we care about before we turn it on
notifier.activated.connect(event_loop.exit)
- notifier.setEnabled(True)
+ notifier.setEnabled(True)
# only start the event loop we are not already flipped
if not context.input_is_ready():
event_loop.exec_()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py
index 7d13001a65..db205b0d2c 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py
@@ -1,95 +1,95 @@
-# Code borrowed from ptpython
-# https://github.com/jonathanslenders/ptpython/blob/86b71a89626114b18898a0af463978bdb32eeb70/ptpython/eventloop.py
-
-# Copyright (c) 2015, Jonathan Slenders
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without modification,
-# are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright notice, this
-# list of conditions and the following disclaimer in the documentation and/or
-# other materials provided with the distribution.
-#
-# * Neither the name of the {organization} nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
-# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""
-Wrapper around the eventloop that gives some time to the Tkinter GUI to process
-events when it's loaded and while we are waiting for input at the REPL. This
-way we don't block the UI of for instance ``turtle`` and other Tk libraries.
-
-(Normally Tkinter registeres it's callbacks in ``PyOS_InputHook`` to integrate
-in readline. ``prompt-toolkit`` doesn't understand that input hook, but this
-will fix it for Tk.)
-"""
-import time
-
-from IPython.utils.py3compat import PY3
-
-import _tkinter
-if PY3:
- import tkinter
-else:
- import Tkinter as tkinter # Python 2
-
-def inputhook(inputhook_context):
- """
- Inputhook for Tk.
- Run the Tk eventloop until prompt-toolkit needs to process the next input.
- """
- # Get the current TK application.
- root = tkinter._default_root
-
- def wait_using_filehandler():
- """
- Run the TK eventloop until the file handler that we got from the
- inputhook becomes readable.
- """
- # Add a handler that sets the stop flag when `prompt-toolkit` has input
- # to process.
- stop = [False]
- def done(*a):
- stop[0] = True
-
- root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
-
- # Run the TK event loop as long as we don't receive input.
- while root.dooneevent(_tkinter.ALL_EVENTS):
- if stop[0]:
- break
-
- root.deletefilehandler(inputhook_context.fileno())
-
- def wait_using_polling():
- """
- Windows TK doesn't support 'createfilehandler'.
- So, run the TK eventloop and poll until input is ready.
- """
- while not inputhook_context.input_is_ready():
- while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
- pass
- # Sleep to make the CPU idle, but not too long, so that the UI
- # stays responsive.
- time.sleep(.01)
-
- if root is not None:
- if hasattr(root, 'createfilehandler'):
- wait_using_filehandler()
- else:
- wait_using_polling()
+# Code borrowed from ptpython
+# https://github.com/jonathanslenders/ptpython/blob/86b71a89626114b18898a0af463978bdb32eeb70/ptpython/eventloop.py
+
+# Copyright (c) 2015, Jonathan Slenders
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice, this
+# list of conditions and the following disclaimer in the documentation and/or
+# other materials provided with the distribution.
+#
+# * Neither the name of the {organization} nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""
+Wrapper around the eventloop that gives some time to the Tkinter GUI to process
+events when it's loaded and while we are waiting for input at the REPL. This
+way we don't block the UI of for instance ``turtle`` and other Tk libraries.
+
+(Normally Tkinter registeres it's callbacks in ``PyOS_InputHook`` to integrate
+in readline. ``prompt-toolkit`` doesn't understand that input hook, but this
+will fix it for Tk.)
+"""
+import time
+
+from IPython.utils.py3compat import PY3
+
+import _tkinter
+if PY3:
+ import tkinter
+else:
+ import Tkinter as tkinter # Python 2
+
+def inputhook(inputhook_context):
+ """
+ Inputhook for Tk.
+ Run the Tk eventloop until prompt-toolkit needs to process the next input.
+ """
+ # Get the current TK application.
+ root = tkinter._default_root
+
+ def wait_using_filehandler():
+ """
+ Run the TK eventloop until the file handler that we got from the
+ inputhook becomes readable.
+ """
+ # Add a handler that sets the stop flag when `prompt-toolkit` has input
+ # to process.
+ stop = [False]
+ def done(*a):
+ stop[0] = True
+
+ root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
+
+ # Run the TK event loop as long as we don't receive input.
+ while root.dooneevent(_tkinter.ALL_EVENTS):
+ if stop[0]:
+ break
+
+ root.deletefilehandler(inputhook_context.fileno())
+
+ def wait_using_polling():
+ """
+ Windows TK doesn't support 'createfilehandler'.
+ So, run the TK eventloop and poll until input is ready.
+ """
+ while not inputhook_context.input_is_ready():
+ while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
+ pass
+ # Sleep to make the CPU idle, but not too long, so that the UI
+ # stays responsive.
+ time.sleep(.01)
+
+ if root is not None:
+ if hasattr(root, 'createfilehandler'):
+ wait_using_filehandler()
+ else:
+ wait_using_polling()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py
index 6dde092500..4371b21cb4 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py
@@ -1,148 +1,148 @@
-"""Enable wxPython to be used interacively in prompt_toolkit
-"""
-from __future__ import absolute_import
-
-import sys
-import signal
-import time
-from timeit import default_timer as clock
-import wx
-
-
-def inputhook_wx1(context):
- """Run the wx event loop by processing pending events only.
-
- This approach seems to work, but its performance is not great as it
- relies on having PyOS_InputHook called regularly.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # Make a temporary event loop and process system events until
- # there are no more waiting, then allow idle events (which
- # will also deal with pending or posted wx events.)
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- while evtloop.Pending():
- evtloop.Dispatch()
- app.ProcessIdle()
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-class EventLoopTimer(wx.Timer):
-
- def __init__(self, func):
- self.func = func
- wx.Timer.__init__(self)
-
- def Notify(self):
- self.func()
-
-class EventLoopRunner(object):
-
- def Run(self, time, input_is_ready):
- self.input_is_ready = input_is_ready
- self.evtloop = wx.EventLoop()
- self.timer = EventLoopTimer(self.check_stdin)
- self.timer.Start(time)
- self.evtloop.Run()
-
- def check_stdin(self):
- if self.input_is_ready():
- self.timer.Stop()
- self.evtloop.Exit()
-
-def inputhook_wx2(context):
- """Run the wx event loop, polling for stdin.
-
- This version runs the wx eventloop for an undetermined amount of time,
- during which it periodically checks to see if anything is ready on
- stdin. If anything is ready on stdin, the event loop exits.
-
- The argument to elr.Run controls how often the event loop looks at stdin.
- This determines the responsiveness at the keyboard. A setting of 1000
- enables a user to type at most 1 char per second. I have found that a
- setting of 10 gives good keyboard response. We can shorten it further,
- but eventually performance would suffer from calling select/kbhit too
- often.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
- elr = EventLoopRunner()
- # As this time is made shorter, keyboard response improves, but idle
- # CPU load goes up. 10 ms seems like a good compromise.
- elr.Run(time=10, # CHANGE time here to control polling interval
- input_is_ready=context.input_is_ready)
- except KeyboardInterrupt:
- pass
- return 0
-
-def inputhook_wx3(context):
- """Run the wx event loop by processing pending events only.
-
- This is like inputhook_wx1, but it keeps processing pending events
- until stdin is ready. After processing all pending events, a call to
- time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
- This sleep time should be tuned though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # The import of wx on Linux sets the handler for signal.SIGINT
- # to 0. This is a bug in wx or gtk. We fix by just setting it
- # back to the Python default.
- if not callable(signal.getsignal(signal.SIGINT)):
- signal.signal(signal.SIGINT, signal.default_int_handler)
-
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- t = clock()
- while not context.input_is_ready():
- while evtloop.Pending():
- t = clock()
- evtloop.Dispatch()
- app.ProcessIdle()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-if sys.platform == 'darwin':
- # On OSX, evtloop.Pending() always returns True, regardless of there being
- # any events pending. As such we can't use implementations 1 or 3 of the
- # inputhook as those depend on a pending/dispatch loop.
- inputhook = inputhook_wx2
-else:
- # This is our default implementation
- inputhook = inputhook_wx3
+"""Enable wxPython to be used interacively in prompt_toolkit
+"""
+from __future__ import absolute_import
+
+import sys
+import signal
+import time
+from timeit import default_timer as clock
+import wx
+
+
+def inputhook_wx1(context):
+ """Run the wx event loop by processing pending events only.
+
+ This approach seems to work, but its performance is not great as it
+ relies on having PyOS_InputHook called regularly.
+ """
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+
+ # Make a temporary event loop and process system events until
+ # there are no more waiting, then allow idle events (which
+ # will also deal with pending or posted wx events.)
+ evtloop = wx.EventLoop()
+ ea = wx.EventLoopActivator(evtloop)
+ while evtloop.Pending():
+ evtloop.Dispatch()
+ app.ProcessIdle()
+ del ea
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+class EventLoopTimer(wx.Timer):
+
+ def __init__(self, func):
+ self.func = func
+ wx.Timer.__init__(self)
+
+ def Notify(self):
+ self.func()
+
+class EventLoopRunner(object):
+
+ def Run(self, time, input_is_ready):
+ self.input_is_ready = input_is_ready
+ self.evtloop = wx.EventLoop()
+ self.timer = EventLoopTimer(self.check_stdin)
+ self.timer.Start(time)
+ self.evtloop.Run()
+
+ def check_stdin(self):
+ if self.input_is_ready():
+ self.timer.Stop()
+ self.evtloop.Exit()
+
+def inputhook_wx2(context):
+ """Run the wx event loop, polling for stdin.
+
+ This version runs the wx eventloop for an undetermined amount of time,
+ during which it periodically checks to see if anything is ready on
+ stdin. If anything is ready on stdin, the event loop exits.
+
+ The argument to elr.Run controls how often the event loop looks at stdin.
+ This determines the responsiveness at the keyboard. A setting of 1000
+ enables a user to type at most 1 char per second. I have found that a
+ setting of 10 gives good keyboard response. We can shorten it further,
+ but eventually performance would suffer from calling select/kbhit too
+ often.
+ """
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+ elr = EventLoopRunner()
+ # As this time is made shorter, keyboard response improves, but idle
+ # CPU load goes up. 10 ms seems like a good compromise.
+ elr.Run(time=10, # CHANGE time here to control polling interval
+ input_is_ready=context.input_is_ready)
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+def inputhook_wx3(context):
+ """Run the wx event loop by processing pending events only.
+
+ This is like inputhook_wx1, but it keeps processing pending events
+ until stdin is ready. After processing all pending events, a call to
+ time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
+ This sleep time should be tuned though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+
+ # The import of wx on Linux sets the handler for signal.SIGINT
+ # to 0. This is a bug in wx or gtk. We fix by just setting it
+ # back to the Python default.
+ if not callable(signal.getsignal(signal.SIGINT)):
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+
+ evtloop = wx.EventLoop()
+ ea = wx.EventLoopActivator(evtloop)
+ t = clock()
+ while not context.input_is_ready():
+ while evtloop.Pending():
+ t = clock()
+ evtloop.Dispatch()
+ app.ProcessIdle()
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ del ea
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+if sys.platform == 'darwin':
+ # On OSX, evtloop.Pending() always returns True, regardless of there being
+ # any events pending. As such we can't use implementations 1 or 3 of the
+ # inputhook as those depend on a pending/dispatch loop.
+ inputhook = inputhook_wx2
+else:
+ # This is our default implementation
+ inputhook = inputhook_wx3
diff --git a/contrib/python/ipython/py2/IPython/terminal/ptshell.py b/contrib/python/ipython/py2/IPython/terminal/ptshell.py
index aad111b041..666d3c5b51 100644
--- a/contrib/python/ipython/py2/IPython/terminal/ptshell.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ptshell.py
@@ -1,8 +1,8 @@
-raise DeprecationWarning("""DEPRECATED:
-
-After Popular request and decision from the BDFL:
-`IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell`
-during the beta cycle (after IPython 5.0.beta3) Sorry about that.
-
-This file will be removed in 5.0 rc or final.
-""")
+raise DeprecationWarning("""DEPRECATED:
+
+After Popular request and decision from the BDFL:
+`IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell`
+during the beta cycle (after IPython 5.0.beta3) Sorry about that.
+
+This file will be removed in 5.0 rc or final.
+""")
diff --git a/contrib/python/ipython/py2/IPython/terminal/ptutils.py b/contrib/python/ipython/py2/IPython/terminal/ptutils.py
index 90def9d209..c9ff705642 100644
--- a/contrib/python/ipython/py2/IPython/terminal/ptutils.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ptutils.py
@@ -1,47 +1,47 @@
-"""prompt-toolkit utilities
-
-Everything in this module is a private API,
-not to be used outside IPython.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import unicodedata
-from wcwidth import wcwidth
-
-from IPython.utils.py3compat import PY3
-
-from IPython.core.completer import IPCompleter
-from prompt_toolkit.completion import Completer, Completion
-from prompt_toolkit.layout.lexers import Lexer
-from prompt_toolkit.layout.lexers import PygmentsLexer
-
-import pygments.lexers as pygments_lexers
-
-
-class IPythonPTCompleter(Completer):
- """Adaptor to provide IPython completions to prompt_toolkit"""
+"""prompt-toolkit utilities
+
+Everything in this module is a private API,
+not to be used outside IPython.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import unicodedata
+from wcwidth import wcwidth
+
+from IPython.utils.py3compat import PY3
+
+from IPython.core.completer import IPCompleter
+from prompt_toolkit.completion import Completer, Completion
+from prompt_toolkit.layout.lexers import Lexer
+from prompt_toolkit.layout.lexers import PygmentsLexer
+
+import pygments.lexers as pygments_lexers
+
+
+class IPythonPTCompleter(Completer):
+ """Adaptor to provide IPython completions to prompt_toolkit"""
def __init__(self, ipy_completer=None, shell=None, patch_stdout=None):
- if shell is None and ipy_completer is None:
- raise TypeError("Please pass shell=an InteractiveShell instance.")
- self._ipy_completer = ipy_completer
- self.shell = shell
+ if shell is None and ipy_completer is None:
+ raise TypeError("Please pass shell=an InteractiveShell instance.")
+ self._ipy_completer = ipy_completer
+ self.shell = shell
if patch_stdout is None:
raise TypeError("Please pass patch_stdout")
self.patch_stdout = patch_stdout
-
- @property
- def ipy_completer(self):
- if self._ipy_completer:
- return self._ipy_completer
- else:
- return self.shell.Completer
-
- def get_completions(self, document, complete_event):
- if not document.current_line.strip():
- return
-
+
+ @property
+ def ipy_completer(self):
+ if self._ipy_completer:
+ return self._ipy_completer
+ else:
+ return self.shell.Completer
+
+ def get_completions(self, document, complete_event):
+ if not document.current_line.strip():
+ return
+
# Some bits of our completion system may print stuff (e.g. if a module
# is imported). This context manager ensures that doesn't interfere with
# the prompt.
@@ -50,66 +50,66 @@ class IPythonPTCompleter(Completer):
line_buffer=document.current_line,
cursor_pos=document.cursor_position_col
)
- start_pos = -len(used)
- for m in matches:
- if not m:
- # Guard against completion machinery giving us an empty string.
- continue
-
- m = unicodedata.normalize('NFC', m)
-
- # When the first character of the completion has a zero length,
- # then it's probably a decomposed unicode character. E.g. caused by
- # the "\dot" completion. Try to compose again with the previous
- # character.
- if wcwidth(m[0]) == 0:
- if document.cursor_position + start_pos > 0:
- char_before = document.text[document.cursor_position + start_pos - 1]
- m = unicodedata.normalize('NFC', char_before + m)
-
- # Yield the modified completion instead, if this worked.
- if wcwidth(m[0:1]) == 1:
- yield Completion(m, start_position=start_pos - 1)
- continue
-
- # TODO: Use Jedi to determine meta_text
- # (Jedi currently has a bug that results in incorrect information.)
- # meta_text = ''
- # yield Completion(m, start_position=start_pos,
- # display_meta=meta_text)
- yield Completion(m, start_position=start_pos)
-
-class IPythonPTLexer(Lexer):
- """
- Wrapper around PythonLexer and BashLexer.
- """
- def __init__(self):
- l = pygments_lexers
- self.python_lexer = PygmentsLexer(l.Python3Lexer if PY3 else l.PythonLexer)
- self.shell_lexer = PygmentsLexer(l.BashLexer)
-
- self.magic_lexers = {
- 'HTML': PygmentsLexer(l.HtmlLexer),
- 'html': PygmentsLexer(l.HtmlLexer),
- 'javascript': PygmentsLexer(l.JavascriptLexer),
- 'js': PygmentsLexer(l.JavascriptLexer),
- 'perl': PygmentsLexer(l.PerlLexer),
- 'ruby': PygmentsLexer(l.RubyLexer),
- 'latex': PygmentsLexer(l.TexLexer),
- }
-
- def lex_document(self, cli, document):
- text = document.text.lstrip()
-
- lexer = self.python_lexer
-
- if text.startswith('!') or text.startswith('%%bash'):
- lexer = self.shell_lexer
-
- elif text.startswith('%%'):
- for magic, l in self.magic_lexers.items():
- if text.startswith('%%' + magic):
- lexer = l
- break
-
- return lexer.lex_document(cli, document)
+ start_pos = -len(used)
+ for m in matches:
+ if not m:
+ # Guard against completion machinery giving us an empty string.
+ continue
+
+ m = unicodedata.normalize('NFC', m)
+
+ # When the first character of the completion has a zero length,
+ # then it's probably a decomposed unicode character. E.g. caused by
+ # the "\dot" completion. Try to compose again with the previous
+ # character.
+ if wcwidth(m[0]) == 0:
+ if document.cursor_position + start_pos > 0:
+ char_before = document.text[document.cursor_position + start_pos - 1]
+ m = unicodedata.normalize('NFC', char_before + m)
+
+ # Yield the modified completion instead, if this worked.
+ if wcwidth(m[0:1]) == 1:
+ yield Completion(m, start_position=start_pos - 1)
+ continue
+
+ # TODO: Use Jedi to determine meta_text
+ # (Jedi currently has a bug that results in incorrect information.)
+ # meta_text = ''
+ # yield Completion(m, start_position=start_pos,
+ # display_meta=meta_text)
+ yield Completion(m, start_position=start_pos)
+
+class IPythonPTLexer(Lexer):
+ """
+ Wrapper around PythonLexer and BashLexer.
+ """
+ def __init__(self):
+ l = pygments_lexers
+ self.python_lexer = PygmentsLexer(l.Python3Lexer if PY3 else l.PythonLexer)
+ self.shell_lexer = PygmentsLexer(l.BashLexer)
+
+ self.magic_lexers = {
+ 'HTML': PygmentsLexer(l.HtmlLexer),
+ 'html': PygmentsLexer(l.HtmlLexer),
+ 'javascript': PygmentsLexer(l.JavascriptLexer),
+ 'js': PygmentsLexer(l.JavascriptLexer),
+ 'perl': PygmentsLexer(l.PerlLexer),
+ 'ruby': PygmentsLexer(l.RubyLexer),
+ 'latex': PygmentsLexer(l.TexLexer),
+ }
+
+ def lex_document(self, cli, document):
+ text = document.text.lstrip()
+
+ lexer = self.python_lexer
+
+ if text.startswith('!') or text.startswith('%%bash'):
+ lexer = self.shell_lexer
+
+ elif text.startswith('%%'):
+ for magic, l in self.magic_lexers.items():
+ if text.startswith('%%' + magic):
+ lexer = l
+ break
+
+ return lexer.lex_document(cli, document)
diff --git a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py
index 2769cf8e8e..8f0ae43e84 100644
--- a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py
+++ b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py
@@ -1,101 +1,101 @@
-import signal
-import sys
-
-from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
-from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
- ViInsertMode, EmacsInsertMode, HasCompletions)
-from prompt_toolkit.filters.cli import ViMode
-from prompt_toolkit.keys import Keys
-from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
-
-from IPython.utils.decorators import undoc
-
-@Condition
-def cursor_in_leading_ws(cli):
- before = cli.application.buffer.document.current_line_before_cursor
- return (not before) or before.isspace()
-
-def register_ipython_shortcuts(registry, shell):
- """Set up the prompt_toolkit keyboard shortcuts for IPython"""
- insert_mode = ViInsertMode() | EmacsInsertMode()
-
- # Ctrl+J == Enter, seemingly
- registry.add_binding(Keys.ControlJ,
- filter=(HasFocus(DEFAULT_BUFFER)
- & ~HasSelection()
- & insert_mode
- ))(newline_or_execute_outer(shell))
-
- registry.add_binding(Keys.ControlBackslash)(force_exit)
-
- registry.add_binding(Keys.ControlP,
- filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
- ))(previous_history_or_previous_completion)
-
- registry.add_binding(Keys.ControlN,
- filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
- ))(next_history_or_next_completion)
-
- registry.add_binding(Keys.ControlG,
- filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()
- ))(dismiss_completion)
-
- registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)
- )(reset_buffer)
-
- registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)
- )(reset_search_buffer)
-
- supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
- registry.add_binding(Keys.ControlZ, filter=supports_suspend
- )(suspend_to_bg)
-
- # Ctrl+I == Tab
- registry.add_binding(Keys.ControlI,
- filter=(HasFocus(DEFAULT_BUFFER)
- & ~HasSelection()
- & insert_mode
- & cursor_in_leading_ws
- ))(indent_buffer)
-
- registry.add_binding(Keys.ControlO,
- filter=(HasFocus(DEFAULT_BUFFER)
- & EmacsInsertMode()))(newline_with_copy_margin)
-
+import signal
+import sys
+
+from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
+from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
+ ViInsertMode, EmacsInsertMode, HasCompletions)
+from prompt_toolkit.filters.cli import ViMode
+from prompt_toolkit.keys import Keys
+from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
+
+from IPython.utils.decorators import undoc
+
+@Condition
+def cursor_in_leading_ws(cli):
+ before = cli.application.buffer.document.current_line_before_cursor
+ return (not before) or before.isspace()
+
+def register_ipython_shortcuts(registry, shell):
+ """Set up the prompt_toolkit keyboard shortcuts for IPython"""
+ insert_mode = ViInsertMode() | EmacsInsertMode()
+
+ # Ctrl+J == Enter, seemingly
+ registry.add_binding(Keys.ControlJ,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & ~HasSelection()
+ & insert_mode
+ ))(newline_or_execute_outer(shell))
+
+ registry.add_binding(Keys.ControlBackslash)(force_exit)
+
+ registry.add_binding(Keys.ControlP,
+ filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
+ ))(previous_history_or_previous_completion)
+
+ registry.add_binding(Keys.ControlN,
+ filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
+ ))(next_history_or_next_completion)
+
+ registry.add_binding(Keys.ControlG,
+ filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()
+ ))(dismiss_completion)
+
+ registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)
+ )(reset_buffer)
+
+ registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)
+ )(reset_search_buffer)
+
+ supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
+ registry.add_binding(Keys.ControlZ, filter=supports_suspend
+ )(suspend_to_bg)
+
+ # Ctrl+I == Tab
+ registry.add_binding(Keys.ControlI,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & ~HasSelection()
+ & insert_mode
+ & cursor_in_leading_ws
+ ))(indent_buffer)
+
+ registry.add_binding(Keys.ControlO,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & EmacsInsertMode()))(newline_with_copy_margin)
+
registry.add_binding(Keys.F2,
filter=HasFocus(DEFAULT_BUFFER)
)(open_input_in_editor)
- if shell.display_completions == 'readlinelike':
- registry.add_binding(Keys.ControlI,
- filter=(HasFocus(DEFAULT_BUFFER)
- & ~HasSelection()
- & insert_mode
- & ~cursor_in_leading_ws
- ))(display_completions_like_readline)
-
- if sys.platform == 'win32':
- registry.add_binding(Keys.ControlV,
- filter=(
- HasFocus(
- DEFAULT_BUFFER) & ~ViMode()
- ))(win_paste)
-
-
-def newline_or_execute_outer(shell):
- def newline_or_execute(event):
- """When the user presses return, insert a newline or execute the code."""
- b = event.current_buffer
- d = b.document
-
- if b.complete_state:
- cc = b.complete_state.current_completion
- if cc:
- b.apply_completion(cc)
- else:
- b.cancel_completion()
- return
-
+ if shell.display_completions == 'readlinelike':
+ registry.add_binding(Keys.ControlI,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & ~HasSelection()
+ & insert_mode
+ & ~cursor_in_leading_ws
+ ))(display_completions_like_readline)
+
+ if sys.platform == 'win32':
+ registry.add_binding(Keys.ControlV,
+ filter=(
+ HasFocus(
+ DEFAULT_BUFFER) & ~ViMode()
+ ))(win_paste)
+
+
+def newline_or_execute_outer(shell):
+ def newline_or_execute(event):
+ """When the user presses return, insert a newline or execute the code."""
+ b = event.current_buffer
+ d = b.document
+
+ if b.complete_state:
+ cc = b.complete_state.current_completion
+ if cc:
+ b.apply_completion(cc)
+ else:
+ b.cancel_completion()
+ return
+
# If there's only one line, treat it as if the cursor is at the end.
# See https://github.com/ipython/ipython/issues/10425
if d.line_count == 1:
@@ -108,99 +108,99 @@ def newline_or_execute_outer(shell):
d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
):
b.insert_text('\n' + (' ' * (indent or 0)))
- return
-
- if (status != 'incomplete') and b.accept_action.is_returnable:
- b.accept_action.validate_and_handle(event.cli, b)
- else:
- b.insert_text('\n' + (' ' * (indent or 0)))
- return newline_or_execute
-
-
-def previous_history_or_previous_completion(event):
- """
- Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
-
- If completer is open this still select previous completion.
- """
- event.current_buffer.auto_up()
-
-
-def next_history_or_next_completion(event):
- """
- Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
-
- If completer is open this still select next completion.
- """
- event.current_buffer.auto_down()
-
-
-def dismiss_completion(event):
- b = event.current_buffer
- if b.complete_state:
- b.cancel_completion()
-
-
-def reset_buffer(event):
- b = event.current_buffer
- if b.complete_state:
- b.cancel_completion()
- else:
- b.reset()
-
-
-def reset_search_buffer(event):
- if event.current_buffer.document.text:
- event.current_buffer.reset()
- else:
- event.cli.push_focus(DEFAULT_BUFFER)
-
-def suspend_to_bg(event):
- event.cli.suspend_to_background()
-
-def force_exit(event):
- """
- Force exit (with a non-zero return value)
- """
- sys.exit("Quit")
-
-def indent_buffer(event):
- event.current_buffer.insert_text(' ' * 4)
-
-def newline_with_copy_margin(event):
- """
- Preserve margin and cursor position when using
- Control-O to insert a newline in EMACS mode
- """
- b = event.current_buffer
- cursor_start_pos = b.document.cursor_position_col
- b.newline(copy_margin=True)
- b.cursor_up(count=1)
- cursor_end_pos = b.document.cursor_position_col
- if cursor_start_pos != cursor_end_pos:
- pos_diff = cursor_start_pos - cursor_end_pos
- b.cursor_right(count=pos_diff)
-
+ return
+
+ if (status != 'incomplete') and b.accept_action.is_returnable:
+ b.accept_action.validate_and_handle(event.cli, b)
+ else:
+ b.insert_text('\n' + (' ' * (indent or 0)))
+ return newline_or_execute
+
+
+def previous_history_or_previous_completion(event):
+ """
+ Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
+
+ If completer is open this still select previous completion.
+ """
+ event.current_buffer.auto_up()
+
+
+def next_history_or_next_completion(event):
+ """
+ Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
+
+ If completer is open this still select next completion.
+ """
+ event.current_buffer.auto_down()
+
+
+def dismiss_completion(event):
+ b = event.current_buffer
+ if b.complete_state:
+ b.cancel_completion()
+
+
+def reset_buffer(event):
+ b = event.current_buffer
+ if b.complete_state:
+ b.cancel_completion()
+ else:
+ b.reset()
+
+
+def reset_search_buffer(event):
+ if event.current_buffer.document.text:
+ event.current_buffer.reset()
+ else:
+ event.cli.push_focus(DEFAULT_BUFFER)
+
+def suspend_to_bg(event):
+ event.cli.suspend_to_background()
+
+def force_exit(event):
+ """
+ Force exit (with a non-zero return value)
+ """
+ sys.exit("Quit")
+
+def indent_buffer(event):
+ event.current_buffer.insert_text(' ' * 4)
+
+def newline_with_copy_margin(event):
+ """
+ Preserve margin and cursor position when using
+ Control-O to insert a newline in EMACS mode
+ """
+ b = event.current_buffer
+ cursor_start_pos = b.document.cursor_position_col
+ b.newline(copy_margin=True)
+ b.cursor_up(count=1)
+ cursor_end_pos = b.document.cursor_position_col
+ if cursor_start_pos != cursor_end_pos:
+ pos_diff = cursor_start_pos - cursor_end_pos
+ b.cursor_right(count=pos_diff)
+
def open_input_in_editor(event):
event.cli.current_buffer.tempfile_suffix = ".py"
event.cli.current_buffer.open_in_editor(event.cli)
-
-
-if sys.platform == 'win32':
- from IPython.core.error import TryNext
- from IPython.lib.clipboard import (ClipboardEmpty,
- win32_clipboard_get,
- tkinter_clipboard_get)
-
- @undoc
- def win_paste(event):
- try:
- text = win32_clipboard_get()
- except TryNext:
- try:
- text = tkinter_clipboard_get()
- except (TryNext, ClipboardEmpty):
- return
- except ClipboardEmpty:
- return
- event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
+
+
+if sys.platform == 'win32':
+ from IPython.core.error import TryNext
+ from IPython.lib.clipboard import (ClipboardEmpty,
+ win32_clipboard_get,
+ tkinter_clipboard_get)
+
+ @undoc
+ def win_paste(event):
+ try:
+ text = win32_clipboard_get()
+ except TryNext:
+ try:
+ text = tkinter_clipboard_get()
+ except (TryNext, ClipboardEmpty):
+ return
+ except ClipboardEmpty:
+ return
+ event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
diff --git a/contrib/python/ipython/py2/IPython/testing/decorators.py b/contrib/python/ipython/py2/IPython/testing/decorators.py
index 26c6478f9e..c9807ce70e 100644
--- a/contrib/python/ipython/py2/IPython/testing/decorators.py
+++ b/contrib/python/ipython/py2/IPython/testing/decorators.py
@@ -48,7 +48,7 @@ from .ipunittest import ipdoctest, ipdocstring
from IPython.external.decorators import *
# For onlyif_cmd_exists decorator
-from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
+from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
#-----------------------------------------------------------------------------
# Classes and functions
@@ -339,7 +339,7 @@ skip_known_failure = knownfailureif(True,'This test is known to fail')
known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
'This test is known to fail on Python 3.')
-cpython2_only = skipif(PY3 or PYPY, "This test only runs on CPython 2.")
+cpython2_only = skipif(PY3 or PYPY, "This test only runs on CPython 2.")
py2_only = skipif(PY3, "This test only runs on Python 2.")
py3_only = skipif(PY2, "This test only runs on Python 3.")
diff --git a/contrib/python/ipython/py2/IPython/testing/globalipapp.py b/contrib/python/ipython/py2/IPython/testing/globalipapp.py
index adcb1dd587..3983393112 100644
--- a/contrib/python/ipython/py2/IPython/testing/globalipapp.py
+++ b/contrib/python/ipython/py2/IPython/testing/globalipapp.py
@@ -8,11 +8,11 @@ done.
from __future__ import absolute_import
from __future__ import print_function
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import sys
-import warnings
+import warnings
from . import tools
@@ -34,9 +34,9 @@ class StreamProxy(io.IOStream):
"""
def __init__(self, name):
- warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
- stacklevel=2,
- )
+ warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
+ stacklevel=2,
+ )
self.name=name
@property
@@ -88,7 +88,7 @@ def start_ipython():
# Create custom argv and namespaces for our IPython to be test-friendly
config = tools.default_config()
- config.TerminalInteractiveShell.simple_prompt = True
+ config.TerminalInteractiveShell.simple_prompt = True
# Create and initialize our test-friendly IPython instance.
shell = TerminalInteractiveShell.instance(config=config,
@@ -128,8 +128,8 @@ def start_ipython():
# Override paging, so we don't require user interaction during the tests.
def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
- if isinstance(strng, dict):
- strng = strng.get('text/plain', '')
+ if isinstance(strng, dict):
+ strng = strng.get('text/plain', '')
print(strng)
page.orig_page = page.pager_page
diff --git a/contrib/python/ipython/py2/IPython/testing/iptest.py b/contrib/python/ipython/py2/IPython/testing/iptest.py
index 10d08b9e5a..4018264125 100644
--- a/contrib/python/ipython/py2/IPython/testing/iptest.py
+++ b/contrib/python/ipython/py2/IPython/testing/iptest.py
@@ -44,10 +44,10 @@ pjoin = path.join
# Enable printing all warnings raise by IPython's modules
-warnings.filterwarnings('ignore', message='.*Matplotlib is building the font cache.*', category=UserWarning, module='.*')
-if sys.version_info > (3,0):
- warnings.filterwarnings('error', message='.*', category=ResourceWarning, module='.*')
-warnings.filterwarnings('error', message=".*{'config': True}.*", category=DeprecationWarning, module='IPy.*')
+warnings.filterwarnings('ignore', message='.*Matplotlib is building the font cache.*', category=UserWarning, module='.*')
+if sys.version_info > (3,0):
+ warnings.filterwarnings('error', message='.*', category=ResourceWarning, module='.*')
+warnings.filterwarnings('error', message=".*{'config': True}.*", category=DeprecationWarning, module='IPy.*')
warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*')
warnings.filterwarnings('error', message='.*apply_wrapper.*', category=DeprecationWarning, module='.*')
@@ -217,7 +217,7 @@ test_group_names.append('autoreload')
def check_exclusions_exist():
from IPython.paths import get_ipython_package_dir
- from warnings import warn
+ from warnings import warn
parent = os.path.dirname(get_ipython_package_dir())
for sec in test_sections:
for pattern in sec.exclusions:
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py b/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
index 8eec1231a9..bc750e0efd 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
@@ -26,8 +26,8 @@ import os
import re
import sys
-from testpath import modified_env
-
+from testpath import modified_env
+
from inspect import getmodule
# We are overriding the default doctest runner, so we need to import a few
@@ -41,7 +41,7 @@ from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
# Third-party modules
from nose.plugins import doctests, Plugin
-from nose.util import anyp, tolist
+from nose.util import anyp, tolist
# Our own imports
from IPython.utils.py3compat import builtin_mod, PY3, getcwd
@@ -140,7 +140,7 @@ class DocTestFinder(doctest.DocTestFinder):
# doctests in extension modules.
# Local shorthands
- from inspect import isroutine, isclass
+ from inspect import isroutine, isclass
# Look for tests in a module's contained objects.
if inspect.ismodule(obj) and self._recurse:
@@ -586,10 +586,10 @@ class IPDocTestRunner(doctest.DocTestRunner,object):
test.globs.update(_ip.user_ns)
- # Override terminal size to standardise traceback format
- with modified_env({'COLUMNS': '80', 'LINES': '24'}):
- return super(IPDocTestRunner,self).run(test,
- compileflags,out,clear_globs)
+ # Override terminal size to standardise traceback format
+ with modified_env({'COLUMNS': '80', 'LINES': '24'}):
+ return super(IPDocTestRunner,self).run(test,
+ compileflags,out,clear_globs)
class DocFileCase(doctest.DocFileCase):
diff --git a/contrib/python/ipython/py2/IPython/testing/skipdoctest.py b/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
index 499ce28e07..564ca54027 100644
--- a/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
@@ -36,8 +36,8 @@ def skip_doctest_py3(f):
"""Decorator - skip the doctest under Python 3."""
f.skip_doctest = (sys.version_info[0] >= 3)
return f
-
-def skip_doctest_py2(f):
- """Decorator - skip the doctest under Python 3."""
- f.skip_doctest = (sys.version_info[0] < 3)
- return f
+
+def skip_doctest_py2(f):
+ """Decorator - skip the doctest under Python 3."""
+ f.skip_doctest = (sys.version_info[0] < 3)
+ return f
diff --git a/contrib/python/ipython/py2/IPython/testing/tools.py b/contrib/python/ipython/py2/IPython/testing/tools.py
index fbe91abcca..23bf6a68cb 100644
--- a/contrib/python/ipython/py2/IPython/testing/tools.py
+++ b/contrib/python/ipython/py2/IPython/testing/tools.py
@@ -196,7 +196,7 @@ def ipexec(fname, options=None, commands=()):
"""
if options is None: options = []
- cmdargs = default_argv() + options
+ cmdargs = default_argv() + options
test_dir = os.path.dirname(__file__)
@@ -291,13 +291,13 @@ class TempFileMixin(object):
# delete it. I have no clue why
pass
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_value, traceback):
- self.tearDown()
-
-
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.tearDown()
+
+
pair_fail_msg = ("Testing {0}\n\n"
"In:\n"
" {1!r}\n"
diff --git a/contrib/python/ipython/py2/IPython/utils/PyColorize.py b/contrib/python/ipython/py2/IPython/utils/PyColorize.py
index 66d52f34dd..124eb2d4e3 100644
--- a/contrib/python/ipython/py2/IPython/utils/PyColorize.py
+++ b/contrib/python/ipython/py2/IPython/utils/PyColorize.py
@@ -54,8 +54,8 @@ except AttributeError:
from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
from IPython.utils.py3compat import PY3
-from .colorable import Colorable
-
+from .colorable import Colorable
+
if PY3:
from io import StringIO
else:
@@ -122,40 +122,40 @@ LinuxColors = ColorScheme(
'normal' : Colors.Normal # color off (usu. Colors.Normal)
} )
-NeutralColors = ColorScheme(
- 'Neutral',{
- 'header' : Colors.Red,
- token.NUMBER : Colors.Cyan,
- token.OP : Colors.Blue,
- token.STRING : Colors.Blue,
- tokenize.COMMENT : Colors.Red,
- token.NAME : Colors.Normal,
- token.ERRORTOKEN : Colors.Red,
-
- _KEYWORD : Colors.Green,
- _TEXT : Colors.Blue,
-
- 'in_prompt' : InputTermColors.Blue,
- 'in_number' : InputTermColors.LightBlue,
- 'in_prompt2' : InputTermColors.Blue,
- 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
-
- 'out_prompt' : Colors.Red,
- 'out_number' : Colors.LightRed,
-
- 'normal' : Colors.Normal # color off (usu. Colors.Normal)
- } )
-
-# Hack: the 'neutral' colours are not very visible on a dark background on
-# Windows. Since Windows command prompts have a dark background by default, and
-# relatively few users are likely to alter that, we will use the 'Linux' colours,
-# designed for a dark background, as the default on Windows. Changing it here
-# avoids affecting the prompt colours rendered by prompt_toolkit, where the
-# neutral defaults do work OK.
-
-if os.name == 'nt':
- NeutralColors = LinuxColors.copy(name='Neutral')
-
+NeutralColors = ColorScheme(
+ 'Neutral',{
+ 'header' : Colors.Red,
+ token.NUMBER : Colors.Cyan,
+ token.OP : Colors.Blue,
+ token.STRING : Colors.Blue,
+ tokenize.COMMENT : Colors.Red,
+ token.NAME : Colors.Normal,
+ token.ERRORTOKEN : Colors.Red,
+
+ _KEYWORD : Colors.Green,
+ _TEXT : Colors.Blue,
+
+ 'in_prompt' : InputTermColors.Blue,
+ 'in_number' : InputTermColors.LightBlue,
+ 'in_prompt2' : InputTermColors.Blue,
+ 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
+
+ 'out_prompt' : Colors.Red,
+ 'out_number' : Colors.LightRed,
+
+ 'normal' : Colors.Normal # color off (usu. Colors.Normal)
+ } )
+
+# Hack: the 'neutral' colours are not very visible on a dark background on
+# Windows. Since Windows command prompts have a dark background by default, and
+# relatively few users are likely to alter that, we will use the 'Linux' colours,
+# designed for a dark background, as the default on Windows. Changing it here
+# avoids affecting the prompt colours rendered by prompt_toolkit, where the
+# neutral defaults do work OK.
+
+if os.name == 'nt':
+ NeutralColors = LinuxColors.copy(name='Neutral')
+
LightBGColors = ColorScheme(
'LightBG',{
'header' : Colors.Red,
@@ -166,7 +166,7 @@ LightBGColors = ColorScheme(
token.NAME : Colors.Normal,
token.ERRORTOKEN : Colors.Red,
-
+
_KEYWORD : Colors.Green,
_TEXT : Colors.Blue,
@@ -182,21 +182,21 @@ LightBGColors = ColorScheme(
} )
# Build table of color schemes (needed by the parser)
-ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
+ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
_scheme_default)
-class Parser(Colorable):
+class Parser(Colorable):
""" Format colored Python source.
"""
- def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
+ def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
""" Create a parser with a specified color table and output channel.
Call format() to process code.
"""
-
- super(Parser, self).__init__(parent=parent)
-
+
+ super(Parser, self).__init__(parent=parent)
+
self.color_table = color_table and color_table or ANSICodeColors
self.out = out
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_common.py b/contrib/python/ipython/py2/IPython/utils/_process_common.py
index e1b305f734..9ede30d3f8 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_common.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_common.py
@@ -17,7 +17,7 @@ of subprocess utilities, and it contains tools that are common to all of them.
import subprocess
import shlex
import sys
-import os
+import os
from IPython.utils import py3compat
@@ -70,14 +70,14 @@ def process_handler(cmd, callback, stderr=subprocess.PIPE):
sys.stderr.flush()
# On win32, close_fds can't be true when using pipes for stdin/out/err
close_fds = sys.platform != 'win32'
- # Determine if cmd should be run with system shell.
- shell = isinstance(cmd, py3compat.string_types)
- # On POSIX systems run shell commands with user-preferred shell.
- executable = None
- if shell and os.name == 'posix' and 'SHELL' in os.environ:
- executable = os.environ['SHELL']
- p = subprocess.Popen(cmd, shell=shell,
- executable=executable,
+ # Determine if cmd should be run with system shell.
+ shell = isinstance(cmd, py3compat.string_types)
+ # On POSIX systems run shell commands with user-preferred shell.
+ executable = None
+ if shell and os.name == 'posix' and 'SHELL' in os.environ:
+ executable = os.environ['SHELL']
+ p = subprocess.Popen(cmd, shell=shell,
+ executable=executable,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr,
diff --git a/contrib/python/ipython/py2/IPython/utils/colorable.py b/contrib/python/ipython/py2/IPython/utils/colorable.py
index 1d5b6b4abe..9f7c5ac213 100644
--- a/contrib/python/ipython/py2/IPython/utils/colorable.py
+++ b/contrib/python/ipython/py2/IPython/utils/colorable.py
@@ -1,26 +1,26 @@
-#*****************************************************************************
-# Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-from __future__ import absolute_import
-
-"""
-Color managing related utilities
-"""
-
-import pygments
-
-from traitlets.config import Configurable
-from traitlets import Unicode
-
-
-available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
-
-class Colorable(Configurable):
- """
- A subclass of configurable for all the classes that have a `default_scheme`
- """
- default_style=Unicode('lightbg').tag(config=True)
-
+#*****************************************************************************
+# Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+from __future__ import absolute_import
+
+"""
+Color managing related utilities
+"""
+
+import pygments
+
+from traitlets.config import Configurable
+from traitlets import Unicode
+
+
+available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
+
+class Colorable(Configurable):
+ """
+ A subclass of configurable for all the classes that have a `default_scheme`
+ """
+ default_style=Unicode('lightbg').tag(config=True)
+
diff --git a/contrib/python/ipython/py2/IPython/utils/contexts.py b/contrib/python/ipython/py2/IPython/utils/contexts.py
index 14f4b47ba6..4d379b0eda 100644
--- a/contrib/python/ipython/py2/IPython/utils/contexts.py
+++ b/contrib/python/ipython/py2/IPython/utils/contexts.py
@@ -2,8 +2,8 @@
"""Miscellaneous context managers.
"""
-import warnings
-
+import warnings
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
@@ -61,14 +61,14 @@ class preserve_keys(object):
class NoOpContext(object):
- """
- Deprecated
-
- Context manager that does nothing."""
-
- def __init__(self):
- warnings.warn("""NoOpContext is deprecated since IPython 5.0 """,
- DeprecationWarning, stacklevel=2)
-
+ """
+ Deprecated
+
+ Context manager that does nothing."""
+
+ def __init__(self):
+ warnings.warn("""NoOpContext is deprecated since IPython 5.0 """,
+ DeprecationWarning, stacklevel=2)
+
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
diff --git a/contrib/python/ipython/py2/IPython/utils/dir2.py b/contrib/python/ipython/py2/IPython/utils/dir2.py
index 352c079178..f6f164f9b1 100644
--- a/contrib/python/ipython/py2/IPython/utils/dir2.py
+++ b/contrib/python/ipython/py2/IPython/utils/dir2.py
@@ -2,10 +2,10 @@
"""A fancy version of Python's builtin :func:`dir` function.
"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
-import inspect
+import inspect
from .py3compat import string_types
@@ -46,36 +46,36 @@ def dir2(obj):
words = [w for w in words if isinstance(w, string_types)]
return sorted(words)
-
-
-def get_real_method(obj, name):
- """Like getattr, but with a few extra sanity checks:
-
- - If obj is a class, ignore its methods
- - Check if obj is a proxy that claims to have all attributes
- - Catch attribute access failing with any exception
- - Check that the attribute is a callable object
-
- Returns the method or None.
- """
- if inspect.isclass(obj):
- return None
-
- try:
- canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
- except Exception:
- return None
-
- if canary is not None:
- # It claimed to have an attribute it should never have
- return None
-
- try:
- m = getattr(obj, name, None)
- except Exception:
- return None
-
- if callable(m):
- return m
-
- return None
+
+
+def get_real_method(obj, name):
+ """Like getattr, but with a few extra sanity checks:
+
+ - If obj is a class, ignore its methods
+ - Check if obj is a proxy that claims to have all attributes
+ - Catch attribute access failing with any exception
+ - Check that the attribute is a callable object
+
+ Returns the method or None.
+ """
+ if inspect.isclass(obj):
+ return None
+
+ try:
+ canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
+ except Exception:
+ return None
+
+ if canary is not None:
+ # It claimed to have an attribute it should never have
+ return None
+
+ try:
+ m = getattr(obj, name, None)
+ except Exception:
+ return None
+
+ if callable(m):
+ return m
+
+ return None
diff --git a/contrib/python/ipython/py2/IPython/utils/io.py b/contrib/python/ipython/py2/IPython/utils/io.py
index 817ecff278..036d6e3926 100644
--- a/contrib/python/ipython/py2/IPython/utils/io.py
+++ b/contrib/python/ipython/py2/IPython/utils/io.py
@@ -14,19 +14,19 @@ import atexit
import os
import sys
import tempfile
-import warnings
+import warnings
from warnings import warn
-
-from IPython.utils.decorators import undoc
+
+from IPython.utils.decorators import undoc
from .capture import CapturedIO, capture_output
from .py3compat import string_types, input, PY3
-@undoc
+@undoc
class IOStream:
- def __init__(self, stream, fallback=None):
- warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
- DeprecationWarning, stacklevel=2)
+ def __init__(self, stream, fallback=None):
+ warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
+ DeprecationWarning, stacklevel=2)
if not hasattr(stream,'write') or not hasattr(stream,'flush'):
if fallback is not None:
stream = fallback
@@ -52,8 +52,8 @@ class IOStream:
return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
def write(self,data):
- warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
- DeprecationWarning, stacklevel=2)
+ warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
+ DeprecationWarning, stacklevel=2)
try:
self._swrite(data)
except:
@@ -68,8 +68,8 @@ class IOStream:
file=sys.stderr)
def writelines(self, lines):
- warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
- DeprecationWarning, stacklevel=2)
+ warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
+ DeprecationWarning, stacklevel=2)
if isinstance(lines, string_types):
lines = [lines]
for line in lines:
@@ -87,17 +87,17 @@ class IOStream:
pass
# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
-devnull = open(os.devnull, 'w')
+devnull = open(os.devnull, 'w')
atexit.register(devnull.close)
-# io.std* are deprecated, but don't show our own deprecation warnings
-# during initialization of the deprecated API.
-with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
- stdin = IOStream(sys.stdin, fallback=devnull)
- stdout = IOStream(sys.stdout, fallback=devnull)
- stderr = IOStream(sys.stderr, fallback=devnull)
-
+# io.std* are deprecated, but don't show our own deprecation warnings
+# during initialization of the deprecated API.
+with warnings.catch_warnings():
+ warnings.simplefilter('ignore', DeprecationWarning)
+ stdin = IOStream(sys.stdin, fallback=devnull)
+ stdout = IOStream(sys.stdout, fallback=devnull)
+ stderr = IOStream(sys.stderr, fallback=devnull)
+
class Tee(object):
"""A class to duplicate an output stream to stdout/err.
diff --git a/contrib/python/ipython/py2/IPython/utils/path.py b/contrib/python/ipython/py2/IPython/utils/path.py
index f7b7666642..fa850812c7 100644
--- a/contrib/python/ipython/py2/IPython/utils/path.py
+++ b/contrib/python/ipython/py2/IPython/utils/path.py
@@ -72,21 +72,21 @@ def get_long_path_name(path):
def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
-
- This function has been deprecated and should not be used any more:
- unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
+
+ This function has been deprecated and should not be used any more:
+ unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
"""
- warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
+ warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
"be used anymore", DeprecationWarning, stacklevel=2)
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name
-
+
def compress_user(path):
"""Reverse of :func:`os.path.expanduser`
- """
+ """
path = py3compat.unicode_to_str(path, sys.getfilesystemencoding())
home = os.path.expanduser('~')
if path.startswith(home):
@@ -101,9 +101,9 @@ def get_py_filename(name, force_win32=None):
"""
name = os.path.expanduser(name)
- if force_win32 is not None:
- warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
- "since IPython 5.0 and should not be used anymore",
+ if force_win32 is not None:
+ warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
+ "since IPython 5.0 and should not be used anymore",
DeprecationWarning, stacklevel=2)
if not os.path.isfile(name) and not name.endswith('.py'):
name += '.py'
diff --git a/contrib/python/ipython/py2/IPython/utils/py3compat.py b/contrib/python/ipython/py2/IPython/utils/py3compat.py
index 4d37054559..88602e5342 100644
--- a/contrib/python/ipython/py2/IPython/utils/py3compat.py
+++ b/contrib/python/ipython/py2/IPython/utils/py3compat.py
@@ -6,7 +6,7 @@ import sys
import re
import shutil
import types
-import platform
+import platform
from .encoding import DEFAULT_ENCODING
@@ -293,7 +293,7 @@ else:
PY2 = not PY3
-PYPY = platform.python_implementation() == "PyPy"
+PYPY = platform.python_implementation() == "PyPy"
def annotate(**kwargs):
diff --git a/contrib/python/ipython/py2/IPython/utils/terminal.py b/contrib/python/ipython/py2/IPython/utils/terminal.py
index 397a3e86fb..e92c410c79 100644
--- a/contrib/python/ipython/py2/IPython/utils/terminal.py
+++ b/contrib/python/ipython/py2/IPython/utils/terminal.py
@@ -11,16 +11,16 @@ Authors:
from __future__ import absolute_import
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import os
import sys
import warnings
-try:
- from shutil import get_terminal_size as _get_terminal_size
-except ImportError:
- # use backport on Python 2
+try:
+ from shutil import get_terminal_size as _get_terminal_size
+except ImportError:
+ # use backport on Python 2
try:
from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
except ImportError:
@@ -121,5 +121,5 @@ def freeze_term_title():
ignore_termtitle = True
-def get_terminal_size(defaultx=80, defaulty=25):
- return _get_terminal_size((defaultx, defaulty))
+def get_terminal_size(defaultx=80, defaulty=25):
+ return _get_terminal_size((defaultx, defaulty))
diff --git a/contrib/python/ipython/py2/IPython/utils/text.py b/contrib/python/ipython/py2/IPython/utils/text.py
index 63588fb322..5ed1a845e3 100644
--- a/contrib/python/ipython/py2/IPython/utils/text.py
+++ b/contrib/python/ipython/py2/IPython/utils/text.py
@@ -14,11 +14,11 @@ import re
import sys
import textwrap
from string import Formatter
-try:
- from pathlib import Path
-except ImportError:
- # Python 2 backport
- from pathlib2 import Path
+try:
+ from pathlib import Path
+except ImportError:
+ # Python 2 backport
+ from pathlib2 import Path
from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
from IPython.utils import py3compat
@@ -72,7 +72,7 @@ class LSString(str):
try:
return self.__paths
except AttributeError:
- self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
+ self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
return self.__paths
p = paths = property(get_paths)
@@ -130,7 +130,7 @@ class SList(list):
try:
return self.__paths
except AttributeError:
- self.__paths = [Path(p) for p in self if os.path.exists(p)]
+ self.__paths = [Path(p) for p in self if os.path.exists(p)]
return self.__paths
p = paths = property(get_paths)
diff --git a/contrib/python/ipython/py2/IPython/utils/tokenutil.py b/contrib/python/ipython/py2/IPython/utils/tokenutil.py
index e01f5e7b32..f52d3b7658 100644
--- a/contrib/python/ipython/py2/IPython/utils/tokenutil.py
+++ b/contrib/python/ipython/py2/IPython/utils/tokenutil.py
@@ -31,7 +31,7 @@ def line_at_cursor(cell, cursor_pos=0):
Parameters
----------
- cell: str
+ cell: str
multiline block of text
cursor_pos: integer
the cursor position
diff --git a/contrib/python/ipython/py2/IPython/utils/warn.py b/contrib/python/ipython/py2/IPython/utils/warn.py
index ae5424a038..dd4852227b 100644
--- a/contrib/python/ipython/py2/IPython/utils/warn.py
+++ b/contrib/python/ipython/py2/IPython/utils/warn.py
@@ -9,17 +9,17 @@ Utilities for warnings. Shoudn't we just use the built in warnings module.
from __future__ import print_function
import sys
-import warnings
+import warnings
-warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
+warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
def warn(msg,level=2,exit_val=1):
- """Deprecated
+ """Deprecated
+
+ Standard warning printer. Gives formatting consistency.
- Standard warning printer. Gives formatting consistency.
+ Output is sent to sys.stderr.
- Output is sent to sys.stderr.
-
Options:
-level(2): allows finer control:
@@ -31,35 +31,35 @@ def warn(msg,level=2,exit_val=1):
-exit_val (1): exit value returned by sys.exit() for a level 4
warning. Ignored for all other levels."""
-
- warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
+
+ warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
if level>0:
header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
- print(header[level], msg, sep='', file=sys.stderr)
+ print(header[level], msg, sep='', file=sys.stderr)
if level == 4:
- print('Exiting.\n', file=sys.stderr)
+ print('Exiting.\n', file=sys.stderr)
sys.exit(exit_val)
def info(msg):
- """Deprecated
-
- Equivalent to warn(msg,level=1)."""
+ """Deprecated
+
+ Equivalent to warn(msg,level=1)."""
warn(msg,level=1)
def error(msg):
- """Deprecated
-
- Equivalent to warn(msg,level=3)."""
+ """Deprecated
+
+ Equivalent to warn(msg,level=3)."""
warn(msg,level=3)
def fatal(msg,exit_val=1):
- """Deprecated
-
- Equivalent to warn(msg,exit_val=exit_val,level=4)."""
+ """Deprecated
+
+ Equivalent to warn(msg,exit_val=exit_val,level=4)."""
warn(msg,exit_val=exit_val,level=4)
diff --git a/contrib/python/ipython/ya.make b/contrib/python/ipython/ya.make
index 3809a3103a..b1dd8c5e23 100644
--- a/contrib/python/ipython/ya.make
+++ b/contrib/python/ipython/ya.make
@@ -3,7 +3,7 @@ PY23_LIBRARY()
LICENSE(Service-Py23-Proxy)
OWNER(g:python-contrib)
-
+
IF (PYTHON2)
PEERDIR(contrib/python/ipython/py2)
ELSE()
diff --git a/contrib/python/jedi/ya.make b/contrib/python/jedi/ya.make
index 13a87aa8ae..eff2fef2a7 100644
--- a/contrib/python/jedi/ya.make
+++ b/contrib/python/jedi/ya.make
@@ -5,7 +5,7 @@ LICENSE(MIT)
OWNER(g:python-contrib borman)
VERSION(0.13.3)
-
+
PEERDIR(
contrib/python/parso
contrib/python/setuptools
diff --git a/contrib/python/pexpect/ya.make b/contrib/python/pexpect/ya.make
index 437dd443ea..a5bb92fcac 100644
--- a/contrib/python/pexpect/ya.make
+++ b/contrib/python/pexpect/ya.make
@@ -3,11 +3,11 @@ PY23_LIBRARY()
LICENSE(ISC)
OWNER(g:python-contrib borman)
-
+
VERSION(4.8.0)
PEERDIR(
- contrib/python/ptyprocess
+ contrib/python/ptyprocess
)
NO_LINT()
diff --git a/contrib/python/pickleshare/ya.make b/contrib/python/pickleshare/ya.make
index cbb2c17737..e24c2cdad7 100644
--- a/contrib/python/pickleshare/ya.make
+++ b/contrib/python/pickleshare/ya.make
@@ -5,7 +5,7 @@ PY23_LIBRARY()
OWNER(borman g:python-contrib)
VERSION(0.7.5)
-
+
LICENSE(MIT)
IF (PYTHON2)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/__init__.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/__init__.py
index bc2bec7eb5..6478ba4f9a 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/__init__.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/__init__.py
@@ -15,8 +15,8 @@ Probably, to get started, you meight also want to have a look at
"""
from .interface import CommandLineInterface
from .application import AbortAction, Application
-from .shortcuts import prompt, prompt_async
+from .shortcuts import prompt, prompt_async
-# Don't forget to update in `docs/conf.py`!
+# Don't forget to update in `docs/conf.py`!
__version__ = '1.0.18'
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/application.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/application.py
index 7a7afa3074..272d8bbcbb 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/application.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/application.py
@@ -3,18 +3,18 @@ from __future__ import unicode_literals
from .buffer import Buffer, AcceptAction
from .buffer_mapping import BufferMapping
from .clipboard import Clipboard, InMemoryClipboard
-from .enums import DEFAULT_BUFFER, EditingMode
+from .enums import DEFAULT_BUFFER, EditingMode
from .filters import CLIFilter, to_cli_filter
from .key_binding.bindings.basic import load_basic_bindings
from .key_binding.bindings.emacs import load_emacs_bindings
-from .key_binding.bindings.vi import load_vi_bindings
+from .key_binding.bindings.vi import load_vi_bindings
from .key_binding.registry import BaseRegistry
from .key_binding.defaults import load_key_bindings
from .layout import Window
from .layout.containers import Container
from .layout.controls import BufferControl
from .styles import DEFAULT_STYLE, Style
-import six
+import six
__all__ = (
'AbortAction',
@@ -57,7 +57,7 @@ class Application(object):
:param on_exit: What to do when Control-D is pressed.
:param use_alternate_screen: When True, run the application on the alternate screen buffer.
:param get_title: Callable that returns the current title to be displayed in the terminal.
- :param erase_when_done: (bool) Clear the application output when it finishes.
+ :param erase_when_done: (bool) Clear the application output when it finishes.
:param reverse_vi_search_direction: Normally, in Vi mode, a '/' searches
forward and a '?' searches backward. In readline mode, this is usually
reversed.
@@ -68,10 +68,10 @@ class Application(object):
boolean). When True, enable mouse support.
:param paste_mode: :class:`~prompt_toolkit.filters.CLIFilter` or boolean.
:param ignore_case: :class:`~prompt_toolkit.filters.CLIFilter` or boolean.
- :param editing_mode: :class:`~prompt_toolkit.enums.EditingMode`.
+ :param editing_mode: :class:`~prompt_toolkit.enums.EditingMode`.
- Callbacks (all of these should accept a
- :class:`~prompt_toolkit.interface.CommandLineInterface` object as input.)
+ Callbacks (all of these should accept a
+ :class:`~prompt_toolkit.interface.CommandLineInterface` object as input.)
:param on_input_timeout: Called when there is no input for x seconds.
(Fired when any eventloop.onInputTimeout is fired.)
@@ -81,8 +81,8 @@ class Application(object):
:param on_buffer_changed: Called when the content of a buffer has been changed.
:param on_initialize: Called after the
:class:`~prompt_toolkit.interface.CommandLineInterface` initializes.
- :param on_render: Called right after rendering.
- :param on_invalidate: Called when the UI has been invalidated.
+ :param on_render: Called right after rendering.
+ :param on_invalidate: Called when the UI has been invalidated.
"""
def __init__(self, layout=None, buffer=None, buffers=None,
initial_focussed_buffer=DEFAULT_BUFFER,
@@ -92,13 +92,13 @@ class Application(object):
use_alternate_screen=False, mouse_support=False,
get_title=None,
- paste_mode=False, ignore_case=False, editing_mode=EditingMode.EMACS,
- erase_when_done=False,
+ paste_mode=False, ignore_case=False, editing_mode=EditingMode.EMACS,
+ erase_when_done=False,
reverse_vi_search_direction=False,
on_input_timeout=None, on_start=None, on_stop=None,
- on_reset=None, on_initialize=None, on_buffer_changed=None,
- on_render=None, on_invalidate=None):
+ on_reset=None, on_initialize=None, on_buffer_changed=None,
+ on_render=None, on_invalidate=None):
paste_mode = to_cli_filter(paste_mode)
ignore_case = to_cli_filter(ignore_case)
@@ -116,28 +116,28 @@ class Application(object):
assert get_title is None or callable(get_title)
assert isinstance(paste_mode, CLIFilter)
assert isinstance(ignore_case, CLIFilter)
- assert isinstance(editing_mode, six.string_types)
- assert on_input_timeout is None or callable(on_input_timeout)
+ assert isinstance(editing_mode, six.string_types)
+ assert on_input_timeout is None or callable(on_input_timeout)
assert style is None or isinstance(style, Style)
- assert isinstance(erase_when_done, bool)
-
- assert on_start is None or callable(on_start)
- assert on_stop is None or callable(on_stop)
- assert on_reset is None or callable(on_reset)
- assert on_buffer_changed is None or callable(on_buffer_changed)
- assert on_initialize is None or callable(on_initialize)
- assert on_render is None or callable(on_render)
- assert on_invalidate is None or callable(on_invalidate)
-
+ assert isinstance(erase_when_done, bool)
+
+ assert on_start is None or callable(on_start)
+ assert on_stop is None or callable(on_stop)
+ assert on_reset is None or callable(on_reset)
+ assert on_buffer_changed is None or callable(on_buffer_changed)
+ assert on_initialize is None or callable(on_initialize)
+ assert on_render is None or callable(on_render)
+ assert on_invalidate is None or callable(on_invalidate)
+
self.layout = layout or Window(BufferControl())
# Make sure that the 'buffers' dictionary is a BufferMapping.
- # NOTE: If no buffer is given, we create a default Buffer, with IGNORE as
- # default accept_action. This is what makes sense for most users
- # creating full screen applications. Doing nothing is the obvious
- # default. Those creating a REPL would use the shortcuts module that
- # passes in RETURN_DOCUMENT.
- self.buffer = buffer or Buffer(accept_action=AcceptAction.IGNORE)
+ # NOTE: If no buffer is given, we create a default Buffer, with IGNORE as
+ # default accept_action. This is what makes sense for most users
+ # creating full screen applications. Doing nothing is the obvious
+ # default. Those creating a REPL would use the shortcuts module that
+ # passes in RETURN_DOCUMENT.
+ self.buffer = buffer or Buffer(accept_action=AcceptAction.IGNORE)
if not buffers or not isinstance(buffers, BufferMapping):
self.buffers = BufferMapping(buffers, initial=initial_focussed_buffer)
else:
@@ -166,21 +166,21 @@ class Application(object):
self.paste_mode = paste_mode
self.ignore_case = ignore_case
- self.editing_mode = editing_mode
- self.erase_when_done = erase_when_done
+ self.editing_mode = editing_mode
+ self.erase_when_done = erase_when_done
self.reverse_vi_search_direction = reverse_vi_search_direction
- def dummy_handler(cli):
- " Dummy event handler. "
-
- self.on_input_timeout = on_input_timeout or dummy_handler
- self.on_start = on_start or dummy_handler
- self.on_stop = on_stop or dummy_handler
- self.on_reset = on_reset or dummy_handler
- self.on_initialize = on_initialize or dummy_handler
- self.on_buffer_changed = on_buffer_changed or dummy_handler
- self.on_render = on_render or dummy_handler
- self.on_invalidate = on_invalidate or dummy_handler
+ def dummy_handler(cli):
+ " Dummy event handler. "
+
+ self.on_input_timeout = on_input_timeout or dummy_handler
+ self.on_start = on_start or dummy_handler
+ self.on_stop = on_stop or dummy_handler
+ self.on_reset = on_reset or dummy_handler
+ self.on_initialize = on_initialize or dummy_handler
+ self.on_buffer_changed = on_buffer_changed or dummy_handler
+ self.on_render = on_render or dummy_handler
+ self.on_invalidate = on_invalidate or dummy_handler
# List of 'extra' functions to execute before a CommandLineInterface.run.
# Note: It's important to keep this here, and not in the
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py
index f0332d939d..f5df289827 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py
@@ -13,14 +13,14 @@ from .filters import to_simple_filter
from .history import History, InMemoryHistory
from .search_state import SearchState
from .selection import SelectionType, SelectionState, PasteMode
-from .utils import Event
-from .cache import FastDictCache
+from .utils import Event
+from .cache import FastDictCache
from .validation import ValidationError
-from six.moves import range
-
+from six.moves import range
+
import os
-import re
+import re
import shlex
import six
import subprocess
@@ -32,10 +32,10 @@ __all__ = (
'Buffer',
'indent',
'unindent',
- 'reshape_text',
+ 'reshape_text',
)
-
+
class EditReadOnlyBuffer(Exception):
" Attempt editing of read-only :class:`.Buffer`. "
@@ -165,24 +165,24 @@ class CompletionState(object):
return self.current_completions[self.complete_index]
-_QUOTED_WORDS_RE = re.compile(r"""(\s+|".*?"|'.*?')""")
-
-
-class YankNthArgState(object):
- """
- For yank-last-arg/yank-nth-arg: Keep track of where we are in the history.
- """
- def __init__(self, history_position=0, n=-1, previous_inserted_word=''):
- self.history_position = history_position
- self.previous_inserted_word = previous_inserted_word
- self.n = n
-
- def __repr__(self):
- return '%s(history_position=%r, n=%r, previous_inserted_word=%r)' % (
- self.__class__.__name__, self.history_position, self.n,
- self.previous_inserted_word)
-
-
+_QUOTED_WORDS_RE = re.compile(r"""(\s+|".*?"|'.*?')""")
+
+
+class YankNthArgState(object):
+ """
+ For yank-last-arg/yank-nth-arg: Keep track of where we are in the history.
+ """
+ def __init__(self, history_position=0, n=-1, previous_inserted_word=''):
+ self.history_position = history_position
+ self.previous_inserted_word = previous_inserted_word
+ self.n = n
+
+ def __repr__(self):
+ return '%s(history_position=%r, n=%r, previous_inserted_word=%r)' % (
+ self.__class__.__name__, self.history_position, self.n,
+ self.previous_inserted_word)
+
+
class Buffer(object):
"""
The core data structure that holds the text and cursor position of the
@@ -196,9 +196,9 @@ class Buffer(object):
Events:
- :param on_text_changed: When the buffer text changes. (Callable on None.)
- :param on_text_insert: When new text is inserted. (Callable on None.)
- :param on_cursor_position_changed: When the cursor moves. (Callable on None.)
+ :param on_text_changed: When the buffer text changes. (Callable on None.)
+ :param on_text_insert: When new text is inserted. (Callable on None.)
+ :param on_cursor_position_changed: When the cursor moves. (Callable on None.)
Filters:
@@ -234,9 +234,9 @@ class Buffer(object):
assert completer is None or isinstance(completer, Completer)
assert auto_suggest is None or isinstance(auto_suggest, AutoSuggest)
assert history is None or isinstance(history, History)
- assert on_text_changed is None or callable(on_text_changed)
- assert on_text_insert is None or callable(on_text_insert)
- assert on_cursor_position_changed is None or callable(on_cursor_position_changed)
+ assert on_text_changed is None or callable(on_text_changed)
+ assert on_text_insert is None or callable(on_text_insert)
+ assert on_cursor_position_changed is None or callable(on_cursor_position_changed)
self.completer = completer
self.auto_suggest = auto_suggest
@@ -250,9 +250,9 @@ class Buffer(object):
self.enable_history_search = enable_history_search
self.read_only = read_only
- # Text width. (For wrapping, used by the Vi 'gq' operator.)
- self.text_width = 0
-
+ # Text width. (For wrapping, used by the Vi 'gq' operator.)
+ self.text_width = 0
+
#: The command buffer history.
# Note that we shouldn't use a lazy 'or' here. bool(history) could be
# False when empty.
@@ -261,13 +261,13 @@ class Buffer(object):
self.__cursor_position = 0
# Events
- self.on_text_changed = Event(self, on_text_changed)
- self.on_text_insert = Event(self, on_text_insert)
- self.on_cursor_position_changed = Event(self, on_cursor_position_changed)
+ self.on_text_changed = Event(self, on_text_changed)
+ self.on_text_insert = Event(self, on_text_insert)
+ self.on_cursor_position_changed = Event(self, on_cursor_position_changed)
+
+ # Document cache. (Avoid creating new Document instances.)
+ self._document_cache = FastDictCache(Document, size=10)
- # Document cache. (Avoid creating new Document instances.)
- self._document_cache = FastDictCache(Document, size=10)
-
self.reset(initial_document=initial_document)
def reset(self, initial_document=None, append_to_history=False):
@@ -290,20 +290,20 @@ class Buffer(object):
# State of the selection.
self.selection_state = None
- # Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode,
- # we can insert text on multiple lines at once. This is implemented by
- # using multiple cursors.)
- self.multiple_cursor_positions = []
-
- # When doing consecutive up/down movements, prefer to stay at this column.
- self.preferred_column = None
-
+ # Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode,
+ # we can insert text on multiple lines at once. This is implemented by
+ # using multiple cursors.)
+ self.multiple_cursor_positions = []
+
+ # When doing consecutive up/down movements, prefer to stay at this column.
+ self.preferred_column = None
+
# State of complete browser
self.complete_state = None # For interactive completion through Ctrl-N/Ctrl-P.
- # State of Emacs yank-nth-arg completion.
- self.yank_nth_arg_state = None # for yank-nth-arg.
-
+ # State of Emacs yank-nth-arg completion.
+ self.yank_nth_arg_state = None # for yank-nth-arg.
+
# Remember the document that we had *right before* the last paste
# operation. This is used for rotating through the kill ring.
self.document_before_paste = None
@@ -332,24 +332,24 @@ class Buffer(object):
def _set_text(self, value):
""" set text at current working_index. Return whether it changed. """
- working_index = self.working_index
- working_lines = self._working_lines
-
- original_value = working_lines[working_index]
- working_lines[working_index] = value
-
- # Return True when this text has been changed.
- if len(value) != len(original_value):
- # For Python 2, it seems that when two strings have a different
- # length and one is a prefix of the other, Python still scans
- # character by character to see whether the strings are different.
- # (Some benchmarking showed significant differences for big
- # documents. >100,000 of lines.)
- return True
- elif value != original_value:
- return True
- return False
-
+ working_index = self.working_index
+ working_lines = self._working_lines
+
+ original_value = working_lines[working_index]
+ working_lines[working_index] = value
+
+ # Return True when this text has been changed.
+ if len(value) != len(original_value):
+ # For Python 2, it seems that when two strings have a different
+ # length and one is a prefix of the other, Python still scans
+ # character by character to see whether the strings are different.
+ # (Some benchmarking showed significant differences for big
+ # documents. >100,000 of lines.)
+ return True
+ elif value != original_value:
+ return True
+ return False
+
def _set_cursor_position(self, value):
""" Set cursor position. Return whether it changed. """
original_position = self.__cursor_position
@@ -415,11 +415,11 @@ class Buffer(object):
self.validation_error = None
self.validation_state = ValidationState.UNKNOWN
self.complete_state = None
- self.yank_nth_arg_state = None
+ self.yank_nth_arg_state = None
self.document_before_paste = None
self.selection_state = None
self.suggestion = None
- self.preferred_column = None
+ self.preferred_column = None
# fire 'on_text_changed' event.
self.on_text_changed.fire()
@@ -429,13 +429,13 @@ class Buffer(object):
self.validation_error = None
self.validation_state = ValidationState.UNKNOWN
self.complete_state = None
- self.yank_nth_arg_state = None
+ self.yank_nth_arg_state = None
self.document_before_paste = None
- # Unset preferred_column. (Will be set after the cursor movement, if
- # required.)
- self.preferred_column = None
-
+ # Unset preferred_column. (Will be set after the cursor movement, if
+ # required.)
+ self.preferred_column = None
+
# Note that the cursor position can change if we have a selection the
# new position of the cursor determines the end of the selection.
@@ -446,10 +446,10 @@ class Buffer(object):
def document(self):
"""
Return :class:`~prompt_toolkit.document.Document` instance from the
- current text, cursor position and selection state.
+ current text, cursor position and selection state.
"""
- return self._document_cache[
- self.text, self.cursor_position, self.selection_state]
+ return self._document_cache[
+ self.text, self.cursor_position, self.selection_state]
@document.setter
def document(self, value):
@@ -534,20 +534,20 @@ class Buffer(object):
return '\n'.join(lines)
- def transform_current_line(self, transform_callback):
- """
- Apply the given transformation function to the current line.
-
- :param transform_callback: callable that takes a string and return a new string.
- """
- document = self.document
- a = document.cursor_position + document.get_start_of_line_position()
- b = document.cursor_position + document.get_end_of_line_position()
- self.text = (
- document.text[:a] +
- transform_callback(document.text[a:b]) +
- document.text[b:])
-
+ def transform_current_line(self, transform_callback):
+ """
+ Apply the given transformation function to the current line.
+
+ :param transform_callback: callable that takes a string and return a new string.
+ """
+ document = self.document
+ a = document.cursor_position + document.get_start_of_line_position()
+ b = document.cursor_position + document.get_end_of_line_position()
+ self.text = (
+ document.text[:a] +
+ transform_callback(document.text[a:b]) +
+ document.text[b:])
+
def transform_region(self, from_, to, transform_callback):
"""
Transform a part of the input string.
@@ -573,23 +573,23 @@ class Buffer(object):
def cursor_up(self, count=1):
""" (for multiline edit). Move cursor to the previous line. """
- original_column = self.preferred_column or self.document.cursor_position_col
- self.cursor_position += self.document.get_cursor_up_position(
- count=count, preferred_column=original_column)
+ original_column = self.preferred_column or self.document.cursor_position_col
+ self.cursor_position += self.document.get_cursor_up_position(
+ count=count, preferred_column=original_column)
+
+ # Remember the original column for the next up/down movement.
+ self.preferred_column = original_column
- # Remember the original column for the next up/down movement.
- self.preferred_column = original_column
-
def cursor_down(self, count=1):
""" (for multiline edit). Move cursor to the next line. """
- original_column = self.preferred_column or self.document.cursor_position_col
- self.cursor_position += self.document.get_cursor_down_position(
- count=count, preferred_column=original_column)
+ original_column = self.preferred_column or self.document.cursor_position_col
+ self.cursor_position += self.document.get_cursor_down_position(
+ count=count, preferred_column=original_column)
+
+ # Remember the original column for the next up/down movement.
+ self.preferred_column = original_column
- # Remember the original column for the next up/down movement.
- self.preferred_column = original_column
-
- def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
+ def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
@@ -597,15 +597,15 @@ class Buffer(object):
if self.complete_state:
self.complete_previous(count=count)
elif self.document.cursor_position_row > 0:
- self.cursor_up(count=count)
+ self.cursor_up(count=count)
elif not self.selection_state:
self.history_backward(count=count)
- # Go to the start of the line?
- if go_to_start_of_line_if_history_changes:
- self.cursor_position += self.document.get_start_of_line_position()
-
- def auto_down(self, count=1, go_to_start_of_line_if_history_changes=False):
+ # Go to the start of the line?
+ if go_to_start_of_line_if_history_changes:
+ self.cursor_position += self.document.get_start_of_line_position()
+
+ def auto_down(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're not on the last line (of a multiline input) go a line down,
otherwise go forward in history. (If nothing is selected.)
@@ -613,18 +613,18 @@ class Buffer(object):
if self.complete_state:
self.complete_next(count=count)
elif self.document.cursor_position_row < self.document.line_count - 1:
- self.cursor_down(count=count)
+ self.cursor_down(count=count)
elif not self.selection_state:
self.history_forward(count=count)
- # Go to the start of the line?
- if go_to_start_of_line_if_history_changes:
- self.cursor_position += self.document.get_start_of_line_position()
-
+ # Go to the start of the line?
+ if go_to_start_of_line_if_history_changes:
+ self.cursor_position += self.document.get_start_of_line_position()
+
def delete_before_cursor(self, count=1):
"""
- Delete specified number of characters before cursor and return the
- deleted text.
+ Delete specified number of characters before cursor and return the
+ deleted text.
"""
assert count >= 0
deleted = ''
@@ -642,7 +642,7 @@ class Buffer(object):
def delete(self, count=1):
"""
- Delete specified number of characters and Return the deleted text.
+ Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
@@ -652,7 +652,7 @@ class Buffer(object):
else:
return ''
- def join_next_line(self, separator=' '):
+ def join_next_line(self, separator=' '):
"""
Join the next line to the current one by deleting the line ending after
the current line.
@@ -662,10 +662,10 @@ class Buffer(object):
self.delete()
# Remove spaces.
- self.text = (self.document.text_before_cursor + separator +
+ self.text = (self.document.text_before_cursor + separator +
self.document.text_after_cursor.lstrip(' '))
- def join_selected_lines(self, separator=' '):
+ def join_selected_lines(self, separator=' '):
"""
Join the selected lines.
"""
@@ -679,7 +679,7 @@ class Buffer(object):
after = self.text[to:]
# Replace leading spaces with just one space.
- lines = [l.lstrip(' ') + separator for l in lines]
+ lines = [l.lstrip(' ') + separator for l in lines]
# Set new document.
self.document = Document(text=before + ''.join(lines) + after,
@@ -906,63 +906,63 @@ class Buffer(object):
if found_something:
self.cursor_position = len(self.text)
- def yank_nth_arg(self, n=None, _yank_last_arg=False):
- """
- Pick nth word from previous history entry (depending on current
- `yank_nth_arg_state`) and insert it at current position. Rotate through
- history if called repeatedly. If no `n` has been given, take the first
- argument. (The second word.)
-
- :param n: (None or int), The index of the word from the previous line
- to take.
- """
- assert n is None or isinstance(n, int)
-
- if not len(self.history):
- return
-
- # Make sure we have a `YankNthArgState`.
- if self.yank_nth_arg_state is None:
- state = YankNthArgState(n=-1 if _yank_last_arg else 1)
- else:
- state = self.yank_nth_arg_state
-
- if n is not None:
- state.n = n
-
- # Get new history position.
- new_pos = state.history_position - 1
- if -new_pos > len(self.history):
- new_pos = -1
-
- # Take argument from line.
- line = self.history[new_pos]
-
- words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)]
- words = [w for w in words if w]
- try:
- word = words[state.n]
- except IndexError:
- word = ''
-
- # Insert new argument.
- if state.previous_inserted_word:
- self.delete_before_cursor(len(state.previous_inserted_word))
- self.insert_text(word)
-
- # Save state again for next completion. (Note that the 'insert'
- # operation from above clears `self.yank_nth_arg_state`.)
- state.previous_inserted_word = word
- state.history_position = new_pos
- self.yank_nth_arg_state = state
-
- def yank_last_arg(self, n=None):
- """
- Like `yank_nth_arg`, but if no argument has been given, yank the last
- word by default.
- """
- self.yank_nth_arg(n=n, _yank_last_arg=True)
-
+ def yank_nth_arg(self, n=None, _yank_last_arg=False):
+ """
+ Pick nth word from previous history entry (depending on current
+ `yank_nth_arg_state`) and insert it at current position. Rotate through
+ history if called repeatedly. If no `n` has been given, take the first
+ argument. (The second word.)
+
+ :param n: (None or int), The index of the word from the previous line
+ to take.
+ """
+ assert n is None or isinstance(n, int)
+
+ if not len(self.history):
+ return
+
+ # Make sure we have a `YankNthArgState`.
+ if self.yank_nth_arg_state is None:
+ state = YankNthArgState(n=-1 if _yank_last_arg else 1)
+ else:
+ state = self.yank_nth_arg_state
+
+ if n is not None:
+ state.n = n
+
+ # Get new history position.
+ new_pos = state.history_position - 1
+ if -new_pos > len(self.history):
+ new_pos = -1
+
+ # Take argument from line.
+ line = self.history[new_pos]
+
+ words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)]
+ words = [w for w in words if w]
+ try:
+ word = words[state.n]
+ except IndexError:
+ word = ''
+
+ # Insert new argument.
+ if state.previous_inserted_word:
+ self.delete_before_cursor(len(state.previous_inserted_word))
+ self.insert_text(word)
+
+ # Save state again for next completion. (Note that the 'insert'
+ # operation from above clears `self.yank_nth_arg_state`.)
+ state.previous_inserted_word = word
+ state.history_position = new_pos
+ self.yank_nth_arg_state = state
+
+ def yank_last_arg(self, n=None):
+ """
+ Like `yank_nth_arg`, but if no argument has been given, yank the last
+ word by default.
+ """
+ self.yank_nth_arg(n=n, _yank_last_arg=True)
+
def start_selection(self, selection_type=SelectionType.CHARACTERS):
"""
Take the current cursor position as the start of this selection.
@@ -1041,21 +1041,21 @@ class Buffer(object):
:param fire_event: Fire `on_text_insert` event. This is mainly used to
trigger autocompletion while typing.
"""
- # Original text & cursor position.
- otext = self.text
- ocpos = self.cursor_position
-
+ # Original text & cursor position.
+ otext = self.text
+ ocpos = self.cursor_position
+
# In insert/text mode.
if overwrite:
- # Don't overwrite the newline itself. Just before the line ending,
- # it should act like insert mode.
- overwritten_text = otext[ocpos:ocpos + len(data)]
+ # Don't overwrite the newline itself. Just before the line ending,
+ # it should act like insert mode.
+ overwritten_text = otext[ocpos:ocpos + len(data)]
if '\n' in overwritten_text:
overwritten_text = overwritten_text[:overwritten_text.find('\n')]
- self.text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text):]
+ self.text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text):]
else:
- self.text = otext[:ocpos] + data + otext[ocpos:]
+ self.text = otext[:ocpos] + data + otext[ocpos:]
if move_cursor:
self.cursor_position += len(data)
@@ -1192,7 +1192,7 @@ class Buffer(object):
for _ in range(count):
result = search_once(working_index, document)
if result is None:
- return # Nothing found.
+ return # Nothing found.
else:
working_index, document = result
@@ -1201,10 +1201,10 @@ class Buffer(object):
def document_for_search(self, search_state):
"""
Return a :class:`~prompt_toolkit.document.Document` instance that has
- the text/cursor position for this search, if we would apply it. This
- will be used in the
- :class:`~prompt_toolkit.layout.controls.BufferControl` to display
- feedback while searching.
+ the text/cursor position for this search, if we would apply it. This
+ will be used in the
+ :class:`~prompt_toolkit.layout.controls.BufferControl` to display
+ feedback while searching.
"""
search_result = self._search(search_state, include_current_position=True)
@@ -1213,37 +1213,37 @@ class Buffer(object):
else:
working_index, cursor_position = search_result
- # Keep selection, when `working_index` was not changed.
- if working_index == self.working_index:
- selection = self.selection_state
- else:
- selection = None
-
- return Document(self._working_lines[working_index],
- cursor_position, selection=selection)
-
- def get_search_position(self, search_state, include_current_position=True, count=1):
- """
- Get the cursor position for this search.
- (This operation won't change the `working_index`. It's won't go through
- the history. Vi text objects can't span multiple items.)
- """
- search_result = self._search(
- search_state, include_current_position=include_current_position, count=count)
-
- if search_result is None:
- return self.cursor_position
- else:
- working_index, cursor_position = search_result
- return cursor_position
-
+ # Keep selection, when `working_index` was not changed.
+ if working_index == self.working_index:
+ selection = self.selection_state
+ else:
+ selection = None
+
+ return Document(self._working_lines[working_index],
+ cursor_position, selection=selection)
+
+ def get_search_position(self, search_state, include_current_position=True, count=1):
+ """
+ Get the cursor position for this search.
+ (This operation won't change the `working_index`. It's won't go through
+ the history. Vi text objects can't span multiple items.)
+ """
+ search_result = self._search(
+ search_state, include_current_position=include_current_position, count=count)
+
+ if search_result is None:
+ return self.cursor_position
+ else:
+ working_index, cursor_position = search_result
+ return cursor_position
+
def apply_search(self, search_state, include_current_position=True, count=1):
"""
Apply search. If something is found, set `working_index` and
`cursor_position`.
"""
- search_result = self._search(
- search_state, include_current_position=include_current_position, count=count)
+ search_result = self._search(
+ search_state, include_current_position=include_current_position, count=count)
if search_result is not None:
working_index, cursor_position = search_result
@@ -1368,48 +1368,48 @@ def unindent(buffer, from_row, to_row, count=1):
# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=True)
-
-
-def reshape_text(buffer, from_row, to_row):
- """
- Reformat text, taking the width into account.
- `to_row` is included.
- (Vi 'gq' operator.)
- """
- lines = buffer.text.splitlines(True)
- lines_before = lines[:from_row]
- lines_after = lines[to_row + 1:]
- lines_to_reformat = lines[from_row:to_row + 1]
-
- if lines_to_reformat:
- # Take indentation from the first line.
- length = re.search(r'^\s*', lines_to_reformat[0]).end()
- indent = lines_to_reformat[0][:length].replace('\n', '')
-
- # Now, take all the 'words' from the lines to be reshaped.
- words = ''.join(lines_to_reformat).split()
-
- # And reshape.
- width = (buffer.text_width or 80) - len(indent)
- reshaped_text = [indent]
- current_width = 0
- for w in words:
- if current_width:
- if len(w) + current_width + 1 > width:
- reshaped_text.append('\n')
- reshaped_text.append(indent)
- current_width = 0
- else:
- reshaped_text.append(' ')
- current_width += 1
-
- reshaped_text.append(w)
- current_width += len(w)
-
- if reshaped_text[-1] != '\n':
- reshaped_text.append('\n')
-
- # Apply result.
- buffer.document = Document(
- text=''.join(lines_before + reshaped_text + lines_after),
- cursor_position=len(''.join(lines_before + reshaped_text)))
+
+
+def reshape_text(buffer, from_row, to_row):
+ """
+ Reformat text, taking the width into account.
+ `to_row` is included.
+ (Vi 'gq' operator.)
+ """
+ lines = buffer.text.splitlines(True)
+ lines_before = lines[:from_row]
+ lines_after = lines[to_row + 1:]
+ lines_to_reformat = lines[from_row:to_row + 1]
+
+ if lines_to_reformat:
+ # Take indentation from the first line.
+ length = re.search(r'^\s*', lines_to_reformat[0]).end()
+ indent = lines_to_reformat[0][:length].replace('\n', '')
+
+ # Now, take all the 'words' from the lines to be reshaped.
+ words = ''.join(lines_to_reformat).split()
+
+ # And reshape.
+ width = (buffer.text_width or 80) - len(indent)
+ reshaped_text = [indent]
+ current_width = 0
+ for w in words:
+ if current_width:
+ if len(w) + current_width + 1 > width:
+ reshaped_text.append('\n')
+ reshaped_text.append(indent)
+ current_width = 0
+ else:
+ reshaped_text.append(' ')
+ current_width += 1
+
+ reshaped_text.append(w)
+ current_width += len(w)
+
+ if reshaped_text[-1] != '\n':
+ reshaped_text.append('\n')
+
+ # Apply result.
+ buffer.document = Document(
+ text=''.join(lines_before + reshaped_text + lines_after),
+ cursor_position=len(''.join(lines_before + reshaped_text)))
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/cache.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/cache.py
index 5fe397a75b..55c7369c9c 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/cache.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/cache.py
@@ -1,111 +1,111 @@
-from __future__ import unicode_literals
-from collections import deque
-from functools import wraps
-
-__all__ = (
- 'SimpleCache',
- 'FastDictCache',
- 'memoized',
-)
-
-
-class SimpleCache(object):
- """
- Very simple cache that discards the oldest item when the cache size is
- exceeded.
-
- :param maxsize: Maximum size of the cache. (Don't make it too big.)
- """
- def __init__(self, maxsize=8):
- assert isinstance(maxsize, int) and maxsize > 0
-
- self._data = {}
- self._keys = deque()
- self.maxsize = maxsize
-
- def get(self, key, getter_func):
- """
- Get object from the cache.
- If not found, call `getter_func` to resolve it, and put that on the top
- of the cache instead.
- """
- # Look in cache first.
- try:
- return self._data[key]
- except KeyError:
- # Not found? Get it.
- value = getter_func()
- self._data[key] = value
- self._keys.append(key)
-
- # Remove the oldest key when the size is exceeded.
- if len(self._data) > self.maxsize:
- key_to_remove = self._keys.popleft()
- if key_to_remove in self._data:
- del self._data[key_to_remove]
-
- return value
-
- def clear(self):
- " Clear cache. "
- self._data = {}
- self._keys = deque()
-
-
-class FastDictCache(dict):
- """
- Fast, lightweight cache which keeps at most `size` items.
- It will discard the oldest items in the cache first.
-
- The cache is a dictionary, which doesn't keep track of access counts.
- It is perfect to cache little immutable objects which are not expensive to
- create, but where a dictionary lookup is still much faster than an object
- instantiation.
-
- :param get_value: Callable that's called in case of a missing key.
- """
- # NOTE: This cache is used to cache `prompt_toolkit.layout.screen.Char` and
- # `prompt_toolkit.Document`. Make sure to keep this really lightweight.
- # Accessing the cache should stay faster than instantiating new
- # objects.
- # (Dictionary lookups are really fast.)
- # SimpleCache is still required for cases where the cache key is not
- # the same as the arguments given to the function that creates the
- # value.)
- def __init__(self, get_value=None, size=1000000):
- assert callable(get_value)
- assert isinstance(size, int) and size > 0
-
- self._keys = deque()
- self.get_value = get_value
- self.size = size
-
- def __missing__(self, key):
- # Remove the oldest key when the size is exceeded.
- if len(self) > self.size:
- key_to_remove = self._keys.popleft()
- if key_to_remove in self:
- del self[key_to_remove]
-
- result = self.get_value(*key)
- self[key] = result
- self._keys.append(key)
- return result
-
-
-def memoized(maxsize=1024):
- """
- Momoization decorator for immutable classes and pure functions.
- """
- cache = SimpleCache(maxsize=maxsize)
-
- def decorator(obj):
- @wraps(obj)
- def new_callable(*a, **kw):
- def create_new():
- return obj(*a, **kw)
-
- key = (a, tuple(kw.items()))
- return cache.get(key, create_new)
- return new_callable
- return decorator
+from __future__ import unicode_literals
+from collections import deque
+from functools import wraps
+
+__all__ = (
+ 'SimpleCache',
+ 'FastDictCache',
+ 'memoized',
+)
+
+
+class SimpleCache(object):
+ """
+ Very simple cache that discards the oldest item when the cache size is
+ exceeded.
+
+ :param maxsize: Maximum size of the cache. (Don't make it too big.)
+ """
+ def __init__(self, maxsize=8):
+ assert isinstance(maxsize, int) and maxsize > 0
+
+ self._data = {}
+ self._keys = deque()
+ self.maxsize = maxsize
+
+ def get(self, key, getter_func):
+ """
+ Get object from the cache.
+ If not found, call `getter_func` to resolve it, and put that on the top
+ of the cache instead.
+ """
+ # Look in cache first.
+ try:
+ return self._data[key]
+ except KeyError:
+ # Not found? Get it.
+ value = getter_func()
+ self._data[key] = value
+ self._keys.append(key)
+
+ # Remove the oldest key when the size is exceeded.
+ if len(self._data) > self.maxsize:
+ key_to_remove = self._keys.popleft()
+ if key_to_remove in self._data:
+ del self._data[key_to_remove]
+
+ return value
+
+ def clear(self):
+ " Clear cache. "
+ self._data = {}
+ self._keys = deque()
+
+
+class FastDictCache(dict):
+ """
+ Fast, lightweight cache which keeps at most `size` items.
+ It will discard the oldest items in the cache first.
+
+ The cache is a dictionary, which doesn't keep track of access counts.
+ It is perfect to cache little immutable objects which are not expensive to
+ create, but where a dictionary lookup is still much faster than an object
+ instantiation.
+
+ :param get_value: Callable that's called in case of a missing key.
+ """
+ # NOTE: This cache is used to cache `prompt_toolkit.layout.screen.Char` and
+ # `prompt_toolkit.Document`. Make sure to keep this really lightweight.
+ # Accessing the cache should stay faster than instantiating new
+ # objects.
+ # (Dictionary lookups are really fast.)
+ # SimpleCache is still required for cases where the cache key is not
+ # the same as the arguments given to the function that creates the
+ # value.)
+ def __init__(self, get_value=None, size=1000000):
+ assert callable(get_value)
+ assert isinstance(size, int) and size > 0
+
+ self._keys = deque()
+ self.get_value = get_value
+ self.size = size
+
+ def __missing__(self, key):
+ # Remove the oldest key when the size is exceeded.
+ if len(self) > self.size:
+ key_to_remove = self._keys.popleft()
+ if key_to_remove in self:
+ del self[key_to_remove]
+
+ result = self.get_value(*key)
+ self[key] = result
+ self._keys.append(key)
+ return result
+
+
+def memoized(maxsize=1024):
+ """
+ Momoization decorator for immutable classes and pure functions.
+ """
+ cache = SimpleCache(maxsize=maxsize)
+
+ def decorator(obj):
+ @wraps(obj)
+ def new_callable(*a, **kw):
+ def create_new():
+ return obj(*a, **kw)
+
+ key = (a, tuple(kw.items()))
+ return cache.get(key, create_new)
+ return new_callable
+ return decorator
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/clipboard/in_memory.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/clipboard/in_memory.py
index cef6ea1300..081666ab80 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/clipboard/in_memory.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/clipboard/in_memory.py
@@ -15,7 +15,7 @@ class InMemoryClipboard(Clipboard):
This implements a kill-ring, for Emacs mode.
"""
def __init__(self, data=None, max_size=60):
- assert data is None or isinstance(data, ClipboardData)
+ assert data is None or isinstance(data, ClipboardData)
assert max_size >= 1
self.max_size = max_size
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/completion.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/completion.py
index 8807f7b34e..339738ab97 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/completion.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/completion.py
@@ -40,13 +40,13 @@ class Completion(object):
assert self.start_position <= 0
def __repr__(self):
- if self.display == self.text:
- return '%s(text=%r, start_position=%r)' % (
- self.__class__.__name__, self.text, self.start_position)
- else:
- return '%s(text=%r, start_position=%r, display=%r)' % (
- self.__class__.__name__, self.text, self.start_position,
- self.display)
+ if self.display == self.text:
+ return '%s(text=%r, start_position=%r)' % (
+ self.__class__.__name__, self.text, self.start_position)
+ else:
+ return '%s(text=%r, start_position=%r, display=%r)' % (
+ self.__class__.__name__, self.text, self.start_position,
+ self.display)
def __eq__(self, other):
return (
@@ -71,22 +71,22 @@ class Completion(object):
else:
return ''
- def new_completion_from_position(self, position):
- """
- (Only for internal use!)
- Get a new completion by splitting this one. Used by
- `CommandLineInterface` when it needs to have a list of new completions
- after inserting the common prefix.
- """
- assert isinstance(position, int) and position - self.start_position >= 0
-
- return Completion(
- text=self.text[position - self.start_position:],
- display=self.display,
- display_meta=self._display_meta,
- get_display_meta=self._get_display_meta)
-
-
+ def new_completion_from_position(self, position):
+ """
+ (Only for internal use!)
+ Get a new completion by splitting this one. Used by
+ `CommandLineInterface` when it needs to have a list of new completions
+ after inserting the common prefix.
+ """
+ assert isinstance(position, int) and position - self.start_position >= 0
+
+ return Completion(
+ text=self.text[position - self.start_position:],
+ display=self.display,
+ display_meta=self._display_meta,
+ get_display_meta=self._get_display_meta)
+
+
class CompleteEvent(object):
"""
Event that called the completer.
@@ -140,18 +140,18 @@ def get_common_complete_suffix(document, completions):
end = completion.text[:-completion.start_position]
return document.text_before_cursor.endswith(end)
- completions2 = [c for c in completions if doesnt_change_before_cursor(c)]
+ completions2 = [c for c in completions if doesnt_change_before_cursor(c)]
+
+ # When there is at least one completion that changes the text before the
+ # cursor, don't return any common part.
+ if len(completions2) != len(completions):
+ return ''
- # When there is at least one completion that changes the text before the
- # cursor, don't return any common part.
- if len(completions2) != len(completions):
- return ''
-
# Return the common prefix.
def get_suffix(completion):
return completion.text[-completion.start_position:]
- return _commonprefix([get_suffix(c) for c in completions2])
+ return _commonprefix([get_suffix(c) for c in completions2])
def _commonprefix(strings):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/completers/filesystem.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/completers/filesystem.py
index 2b37b4e825..cbd74d8fea 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/completers/filesystem.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/completers/filesystem.py
@@ -80,12 +80,12 @@ class PathCompleter(Completer):
# (We don't add them to the `completion`. Users can type it
# to trigger the autocompletion themself.)
filename += '/'
- elif self.only_directories:
- continue
+ elif self.only_directories:
+ continue
+
+ if not self.file_filter(full_name):
+ continue
- if not self.file_filter(full_name):
- continue
-
yield Completion(completion, 0, display=filename)
except OSError:
pass
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/compiler.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/compiler.py
index 859002ed12..01476bf626 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/compiler.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/compiler.py
@@ -41,7 +41,7 @@ Partial matches are possible::
from __future__ import unicode_literals
import re
-from six.moves import range
+from six.moves import range
from .regex_parser import Any, Sequence, Regex, Variable, Repeat, Lookahead
from .regex_parser import parse_regex, tokenize_regex
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/lexer.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/lexer.py
index f78c9ca446..c166d84fd1 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/lexer.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/lexer.py
@@ -3,13 +3,13 @@
the input using a regular grammar with token annotations.
"""
from __future__ import unicode_literals
-from prompt_toolkit.document import Document
+from prompt_toolkit.document import Document
from prompt_toolkit.layout.lexers import Lexer
-from prompt_toolkit.layout.utils import split_lines
-from prompt_toolkit.token import Token
+from prompt_toolkit.layout.utils import split_lines
+from prompt_toolkit.token import Token
from .compiler import _CompiledGrammar
-from six.moves import range
+from six.moves import range
__all__ = (
'GrammarLexer',
@@ -40,7 +40,7 @@ class GrammarLexer(Lexer):
self.default_token = default_token or Token
self.lexers = lexers or {}
- def _get_tokens(self, cli, text):
+ def _get_tokens(self, cli, text):
m = self.compiled_grammar.match_prefix(text)
if m:
@@ -52,15 +52,15 @@ class GrammarLexer(Lexer):
lexer = self.lexers.get(v.varname)
if lexer:
- document = Document(text[v.start:v.stop])
- lexer_tokens_for_line = lexer.lex_document(cli, document)
- lexer_tokens = []
- for i in range(len(document.lines)):
- lexer_tokens.extend(lexer_tokens_for_line(i))
- lexer_tokens.append((Token, '\n'))
- if lexer_tokens:
- lexer_tokens.pop()
-
+ document = Document(text[v.start:v.stop])
+ lexer_tokens_for_line = lexer.lex_document(cli, document)
+ lexer_tokens = []
+ for i in range(len(document.lines)):
+ lexer_tokens.extend(lexer_tokens_for_line(i))
+ lexer_tokens.append((Token, '\n'))
+ if lexer_tokens:
+ lexer_tokens.pop()
+
i = v.start
for t, s in lexer_tokens:
for c in s:
@@ -77,14 +77,14 @@ class GrammarLexer(Lexer):
return characters
else:
return [(Token, text)]
-
- def lex_document(self, cli, document):
- lines = list(split_lines(self._get_tokens(cli, document.text)))
-
- def get_line(lineno):
- try:
- return lines[lineno]
- except IndexError:
- return []
-
- return get_line
+
+ def lex_document(self, cli, document):
+ lines = list(split_lines(self._get_tokens(cli, document.text)))
+
+ def get_line(lineno):
+ try:
+ return lines[lineno]
+ except IndexError:
+ return []
+
+ return get_line
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/validation.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/validation.py
index 947765f5b1..d5f8cfccc6 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/validation.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/regular_languages/validation.py
@@ -50,7 +50,7 @@ class GrammarValidator(Validator):
validator.validate(inner_document)
except ValidationError as e:
raise ValidationError(
- cursor_position=v.start + e.cursor_position,
+ cursor_position=v.start + e.cursor_position,
message=e.message)
else:
raise ValidationError(cursor_position=len(document.text),
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/telnet/server.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/telnet/server.py
index ad61453d17..d75a9572eb 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/telnet/server.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/telnet/server.py
@@ -121,7 +121,7 @@ class TelnetConnection(object):
def get_size():
return self.size
self.stdout = _ConnectionStdout(conn, encoding=encoding)
- self.vt100_output = Vt100_Output(self.stdout, get_size, write_binary=False)
+ self.vt100_output = Vt100_Output(self.stdout, get_size, write_binary=False)
# Create an eventloop (adaptor) for the CommandLineInterface.
self.eventloop = _TelnetEventLoopInterface(server)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/validators/base.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/validators/base.py
index a81fb91e63..16c1539c52 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/validators/base.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/contrib/validators/base.py
@@ -21,7 +21,7 @@ class SentenceValidator(Validator):
self.move_cursor_to_end = move_cursor_to_end
if ignore_case:
- self.sentences = set([s.lower() for s in self.sentences])
+ self.sentences = set([s.lower() for s in self.sentences])
def validate(self, document):
if document.text not in self.sentences:
@@ -30,5 +30,5 @@ class SentenceValidator(Validator):
else:
index = 0
- raise ValidationError(cursor_position=index,
- message=self.error_message)
+ raise ValidationError(cursor_position=index,
+ message=self.error_message)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py
index 60b4108a53..25d817ddd0 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py
@@ -1,14 +1,14 @@
"""
-The `Document` that implements all the text operations/querying.
+The `Document` that implements all the text operations/querying.
"""
from __future__ import unicode_literals
-import bisect
+import bisect
import re
import six
import string
-import weakref
-from six.moves import range, map
+import weakref
+from six.moves import range, map
from .selection import SelectionType, SelectionState, PasteMode
from .clipboard import ClipboardData
@@ -30,41 +30,41 @@ _FIND_BIG_WORD_RE = re.compile(r'([^\s]+)')
_FIND_CURRENT_BIG_WORD_RE = re.compile(r'^([^\s]+)')
_FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE = re.compile(r'^([^\s]+\s*)')
-# Share the Document._cache between all Document instances.
-# (Document instances are considered immutable. That means that if another
-# `Document` is constructed with the same text, it should have the same
-# `_DocumentCache`.)
-_text_to_document_cache = weakref.WeakValueDictionary() # Maps document.text to DocumentCache instance.
-
-
-class _ImmutableLineList(list):
- """
- Some protection for our 'lines' list, which is assumed to be immutable in the cache.
- (Useful for detecting obvious bugs.)
- """
- def _error(self, *a, **kw):
- raise NotImplementedError('Attempt to modifiy an immutable list.')
-
- __setitem__ = _error
- append = _error
- clear = _error
- extend = _error
- insert = _error
- pop = _error
- remove = _error
- reverse = _error
- sort = _error
-
-
-class _DocumentCache(object):
- def __init__(self):
- #: List of lines for the Document text.
- self.lines = None
-
- #: List of index positions, pointing to the start of all the lines.
- self.line_indexes = None
-
-
+# Share the Document._cache between all Document instances.
+# (Document instances are considered immutable. That means that if another
+# `Document` is constructed with the same text, it should have the same
+# `_DocumentCache`.)
+_text_to_document_cache = weakref.WeakValueDictionary() # Maps document.text to DocumentCache instance.
+
+
+class _ImmutableLineList(list):
+ """
+ Some protection for our 'lines' list, which is assumed to be immutable in the cache.
+ (Useful for detecting obvious bugs.)
+ """
+ def _error(self, *a, **kw):
+ raise NotImplementedError('Attempt to modifiy an immutable list.')
+
+ __setitem__ = _error
+ append = _error
+ clear = _error
+ extend = _error
+ insert = _error
+ pop = _error
+ remove = _error
+ reverse = _error
+ sort = _error
+
+
+class _DocumentCache(object):
+ def __init__(self):
+ #: List of lines for the Document text.
+ self.lines = None
+
+ #: List of index positions, pointing to the start of all the lines.
+ self.line_indexes = None
+
+
class Document(object):
"""
This is a immutable class around the text and cursor position, and contains
@@ -77,7 +77,7 @@ class Document(object):
:param cursor_position: int
:param selection: :class:`.SelectionState`
"""
- __slots__ = ('_text', '_cursor_position', '_selection', '_cache')
+ __slots__ = ('_text', '_cursor_position', '_selection', '_cache')
def __init__(self, text='', cursor_position=None, selection=None):
assert isinstance(text, six.text_type), 'Got %r' % text
@@ -94,46 +94,46 @@ class Document(object):
if cursor_position is None:
cursor_position = len(text)
- # Keep these attributes private. A `Document` really has to be
- # considered to be immutable, because otherwise the caching will break
- # things. Because of that, we wrap these into read-only properties.
- self._text = text
- self._cursor_position = cursor_position
- self._selection = selection
-
- # Cache for lines/indexes. (Shared with other Document instances that
- # contain the same text.
- try:
- self._cache = _text_to_document_cache[self.text]
- except KeyError:
- self._cache = _DocumentCache()
- _text_to_document_cache[self.text] = self._cache
-
- # XX: For some reason, above, we can't use 'WeakValueDictionary.setdefault'.
- # This fails in Pypy3. `self._cache` becomes None, because that's what
- # 'setdefault' returns.
- # self._cache = _text_to_document_cache.setdefault(self.text, _DocumentCache())
- # assert self._cache
-
+ # Keep these attributes private. A `Document` really has to be
+ # considered to be immutable, because otherwise the caching will break
+ # things. Because of that, we wrap these into read-only properties.
+ self._text = text
+ self._cursor_position = cursor_position
+ self._selection = selection
+
+ # Cache for lines/indexes. (Shared with other Document instances that
+ # contain the same text.
+ try:
+ self._cache = _text_to_document_cache[self.text]
+ except KeyError:
+ self._cache = _DocumentCache()
+ _text_to_document_cache[self.text] = self._cache
+
+ # XX: For some reason, above, we can't use 'WeakValueDictionary.setdefault'.
+ # This fails in Pypy3. `self._cache` becomes None, because that's what
+ # 'setdefault' returns.
+ # self._cache = _text_to_document_cache.setdefault(self.text, _DocumentCache())
+ # assert self._cache
+
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.text, self.cursor_position)
@property
- def text(self):
- " The document text. "
- return self._text
-
- @property
- def cursor_position(self):
- " The document cursor position. "
- return self._cursor_position
-
- @property
- def selection(self):
- " :class:`.SelectionState` object. "
- return self._selection
-
- @property
+ def text(self):
+ " The document text. "
+ return self._text
+
+ @property
+ def cursor_position(self):
+ " The document cursor position. "
+ return self._cursor_position
+
+ @property
+ def selection(self):
+ " :class:`.SelectionState` object. "
+ return self._selection
+
+ @property
def current_char(self):
""" Return character under cursor or an empty string. """
return self._get_char_relative_to_cursor(0) or ''
@@ -154,55 +154,55 @@ class Document(object):
@property
def current_line_before_cursor(self):
""" Text from the start of the line until the cursor. """
- _, _, text = self.text_before_cursor.rpartition('\n')
- return text
+ _, _, text = self.text_before_cursor.rpartition('\n')
+ return text
@property
def current_line_after_cursor(self):
""" Text from the cursor until the end of the line. """
- text, _, _ = self.text_after_cursor.partition('\n')
- return text
+ text, _, _ = self.text_after_cursor.partition('\n')
+ return text
@property
def lines(self):
- """
- Array of all the lines.
- """
+ """
+ Array of all the lines.
+ """
# Cache, because this one is reused very often.
- if self._cache.lines is None:
- self._cache.lines = _ImmutableLineList(self.text.split('\n'))
+ if self._cache.lines is None:
+ self._cache.lines = _ImmutableLineList(self.text.split('\n'))
+
+ return self._cache.lines
+
+ @property
+ def _line_start_indexes(self):
+ """
+ Array pointing to the start indexes of all the lines.
+ """
+ # Cache, because this is often reused. (If it is used, it's often used
+ # many times. And this has to be fast for editing big documents!)
+ if self._cache.line_indexes is None:
+ # Create list of line lengths.
+ line_lengths = map(len, self.lines)
+
+ # Calculate cumulative sums.
+ indexes = [0]
+ append = indexes.append
+ pos = 0
- return self._cache.lines
+ for line_length in line_lengths:
+ pos += line_length + 1
+ append(pos)
+
+ # Remove the last item. (This is not a new line.)
+ if len(indexes) > 1:
+ indexes.pop()
+
+ self._cache.line_indexes = indexes
+
+ return self._cache.line_indexes
@property
- def _line_start_indexes(self):
- """
- Array pointing to the start indexes of all the lines.
- """
- # Cache, because this is often reused. (If it is used, it's often used
- # many times. And this has to be fast for editing big documents!)
- if self._cache.line_indexes is None:
- # Create list of line lengths.
- line_lengths = map(len, self.lines)
-
- # Calculate cumulative sums.
- indexes = [0]
- append = indexes.append
- pos = 0
-
- for line_length in line_lengths:
- pos += line_length + 1
- append(pos)
-
- # Remove the last item. (This is not a new line.)
- if len(indexes) > 1:
- indexes.pop()
-
- self._cache.line_indexes = indexes
-
- return self._cache.line_indexes
-
- @property
def lines_from_current(self):
"""
Array of the lines starting from the current line, until the last line.
@@ -256,64 +256,64 @@ class Document(object):
"""
Current row. (0-based.)
"""
- row, _ = self._find_line_start_index(self.cursor_position)
- return row
+ row, _ = self._find_line_start_index(self.cursor_position)
+ return row
@property
def cursor_position_col(self):
"""
Current column. (0-based.)
"""
- # (Don't use self.text_before_cursor to calculate this. Creating
- # substrings and doing rsplit is too expensive for getting the cursor
- # position.)
- _, line_start_index = self._find_line_start_index(self.cursor_position)
- return self.cursor_position - line_start_index
-
- def _find_line_start_index(self, index):
- """
- For the index of a character at a certain line, calculate the index of
- the first character on that line.
-
- Return (row, index) tuple.
- """
- indexes = self._line_start_indexes
-
- pos = bisect.bisect_right(indexes, index) - 1
- return pos, indexes[pos]
-
- def translate_index_to_position(self, index):
- """
+ # (Don't use self.text_before_cursor to calculate this. Creating
+ # substrings and doing rsplit is too expensive for getting the cursor
+ # position.)
+ _, line_start_index = self._find_line_start_index(self.cursor_position)
+ return self.cursor_position - line_start_index
+
+ def _find_line_start_index(self, index):
+ """
+ For the index of a character at a certain line, calculate the index of
+ the first character on that line.
+
+ Return (row, index) tuple.
+ """
+ indexes = self._line_start_indexes
+
+ pos = bisect.bisect_right(indexes, index) - 1
+ return pos, indexes[pos]
+
+ def translate_index_to_position(self, index):
+ """
Given an index for the text, return the corresponding (row, col) tuple.
(0-based. Returns (0, 0) for index=0.)
"""
- # Find start of this line.
- row, row_index = self._find_line_start_index(index)
- col = index - row_index
+ # Find start of this line.
+ row, row_index = self._find_line_start_index(index)
+ col = index - row_index
return row, col
-
+
def translate_row_col_to_index(self, row, col):
"""
Given a (row, col) tuple, return the corresponding index.
(Row and col params are 0-based.)
-
- Negative row/col values are turned into zero.
- """
- try:
- result = self._line_start_indexes[row]
- line = self.lines[row]
- except IndexError:
- if row < 0:
- result = self._line_start_indexes[0]
- line = self.lines[0]
- else:
- result = self._line_start_indexes[-1]
- line = self.lines[-1]
-
- result += max(0, min(col, len(line)))
-
+
+ Negative row/col values are turned into zero.
+ """
+ try:
+ result = self._line_start_indexes[row]
+ line = self.lines[row]
+ except IndexError:
+ if row < 0:
+ result = self._line_start_indexes[0]
+ line = self.lines[0]
+ else:
+ result = self._line_start_indexes[-1]
+ line = self.lines[-1]
+
+ result += max(0, min(col, len(line)))
+
# Keep in range. (len(self.text) is included, because the cursor can be
# right after the end of the text as well.)
result = max(0, min(result, len(self.text)))
@@ -327,16 +327,16 @@ class Document(object):
@property
def is_cursor_at_the_end_of_line(self):
""" True when the cursor is at the end of this line. """
- return self.current_char in ('\n', '')
+ return self.current_char in ('\n', '')
def has_match_at_current_position(self, sub):
"""
`True` when this substring is found at the cursor position.
"""
- return self.text.find(sub, self.cursor_position) == self.cursor_position
+ return self.text.find(sub, self.cursor_position) == self.cursor_position
def find(self, sub, in_current_line=False, include_current_position=False,
- ignore_case=False, count=1):
+ ignore_case=False, count=1):
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
@@ -480,9 +480,9 @@ class Document(object):
Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found.
"""
- if count < 0:
- return self.find_previous_word_beginning(count=-count, WORD=WORD)
-
+ if count < 0:
+ return self.find_previous_word_beginning(count=-count, WORD=WORD)
+
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_after_cursor)
@@ -502,9 +502,9 @@ class Document(object):
Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found.
"""
- if count < 0:
- return self.find_previous_word_ending(count=-count, WORD=WORD)
-
+ if count < 0:
+ return self.find_previous_word_ending(count=-count, WORD=WORD)
+
if include_current_position:
text = self.text_after_cursor
else:
@@ -529,11 +529,11 @@ class Document(object):
def find_previous_word_beginning(self, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the start
- of the previous word. Return `None` if nothing was found.
+ of the previous word. Return `None` if nothing was found.
"""
- if count < 0:
- return self.find_next_word_beginning(count=-count, WORD=WORD)
-
+ if count < 0:
+ return self.find_next_word_beginning(count=-count, WORD=WORD)
+
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_before_cursor[::-1])
@@ -544,30 +544,30 @@ class Document(object):
except StopIteration:
pass
- def find_previous_word_ending(self, count=1, WORD=False):
- """
- Return an index relative to the cursor position pointing to the end
- of the previous word. Return `None` if nothing was found.
- """
- if count < 0:
- return self.find_next_word_ending(count=-count, WORD=WORD)
-
- text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
-
- regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
- iterator = regex.finditer(text_before_cursor)
-
- try:
- for i, match in enumerate(iterator):
- # Take first match, unless it's the word on which we're right now.
- if i == 0 and match.start(1) == 0:
- count += 1
-
- if i + 1 == count:
- return -match.start(1) + 1
- except StopIteration:
- pass
-
+ def find_previous_word_ending(self, count=1, WORD=False):
+ """
+ Return an index relative to the cursor position pointing to the end
+ of the previous word. Return `None` if nothing was found.
+ """
+ if count < 0:
+ return self.find_next_word_ending(count=-count, WORD=WORD)
+
+ text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
+
+ regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
+ iterator = regex.finditer(text_before_cursor)
+
+ try:
+ for i, match in enumerate(iterator):
+ # Take first match, unless it's the word on which we're right now.
+ if i == 0 and match.start(1) == 0:
+ count += 1
+
+ if i + 1 == count:
+ return -match.start(1) + 1
+ except StopIteration:
+ pass
+
def find_next_matching_line(self, match_func, count=1):
"""
Look downwards for empty lines.
@@ -606,119 +606,119 @@ class Document(object):
"""
Relative position for cursor left.
"""
- if count < 0:
- return self.get_cursor_right_position(-count)
-
+ if count < 0:
+ return self.get_cursor_right_position(-count)
+
return - min(self.cursor_position_col, count)
def get_cursor_right_position(self, count=1):
"""
Relative position for cursor_right.
"""
- if count < 0:
- return self.get_cursor_left_position(-count)
-
+ if count < 0:
+ return self.get_cursor_left_position(-count)
+
return min(count, len(self.current_line_after_cursor))
- def get_cursor_up_position(self, count=1, preferred_column=None):
+ def get_cursor_up_position(self, count=1, preferred_column=None):
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-up button.
-
- :param preferred_column: When given, go to this column instead of
- staying at the current column.
+
+ :param preferred_column: When given, go to this column instead of
+ staying at the current column.
+ """
+ assert count >= 1
+ column = self.cursor_position_col if preferred_column is None else preferred_column
+
+ return self.translate_row_col_to_index(
+ max(0, self.cursor_position_row - count), column) - self.cursor_position
+
+ def get_cursor_down_position(self, count=1, preferred_column=None):
+ """
+ Return the relative cursor position (character index) where we would be if the
+ user pressed the arrow-down button.
+
+ :param preferred_column: When given, go to this column instead of
+ staying at the current column.
"""
assert count >= 1
- column = self.cursor_position_col if preferred_column is None else preferred_column
-
- return self.translate_row_col_to_index(
- max(0, self.cursor_position_row - count), column) - self.cursor_position
-
- def get_cursor_down_position(self, count=1, preferred_column=None):
- """
- Return the relative cursor position (character index) where we would be if the
- user pressed the arrow-down button.
-
- :param preferred_column: When given, go to this column instead of
- staying at the current column.
- """
- assert count >= 1
- column = self.cursor_position_col if preferred_column is None else preferred_column
-
- return self.translate_row_col_to_index(
- self.cursor_position_row + count, column) - self.cursor_position
-
- def find_enclosing_bracket_right(self, left_ch, right_ch, end_pos=None):
- """
- Find the right bracket enclosing current position. Return the relative
- position to the cursor position.
-
- When `end_pos` is given, don't look past the position.
- """
- if self.current_char == right_ch:
- return 0
-
- if end_pos is None:
- end_pos = len(self.text)
- else:
- end_pos = min(len(self.text), end_pos)
-
- stack = 1
-
- # Look forward.
- for i in range(self.cursor_position + 1, end_pos):
- c = self.text[i]
-
- if c == left_ch:
- stack += 1
- elif c == right_ch:
- stack -= 1
-
- if stack == 0:
- return i - self.cursor_position
-
- def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None):
- """
- Find the left bracket enclosing current position. Return the relative
- position to the cursor position.
-
- When `start_pos` is given, don't look past the position.
- """
- if self.current_char == left_ch:
- return 0
-
- if start_pos is None:
- start_pos = 0
- else:
- start_pos = max(0, start_pos)
-
- stack = 1
-
- # Look backward.
- for i in range(self.cursor_position - 1, start_pos - 1, -1):
- c = self.text[i]
-
- if c == right_ch:
- stack += 1
- elif c == left_ch:
- stack -= 1
-
- if stack == 0:
- return i - self.cursor_position
-
- def find_matching_bracket_position(self, start_pos=None, end_pos=None):
+ column = self.cursor_position_col if preferred_column is None else preferred_column
+
+ return self.translate_row_col_to_index(
+ self.cursor_position_row + count, column) - self.cursor_position
+
+ def find_enclosing_bracket_right(self, left_ch, right_ch, end_pos=None):
+ """
+ Find the right bracket enclosing current position. Return the relative
+ position to the cursor position.
+
+ When `end_pos` is given, don't look past the position.
+ """
+ if self.current_char == right_ch:
+ return 0
+
+ if end_pos is None:
+ end_pos = len(self.text)
+ else:
+ end_pos = min(len(self.text), end_pos)
+
+ stack = 1
+
+ # Look forward.
+ for i in range(self.cursor_position + 1, end_pos):
+ c = self.text[i]
+
+ if c == left_ch:
+ stack += 1
+ elif c == right_ch:
+ stack -= 1
+
+ if stack == 0:
+ return i - self.cursor_position
+
+ def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None):
+ """
+ Find the left bracket enclosing current position. Return the relative
+ position to the cursor position.
+
+ When `start_pos` is given, don't look past the position.
+ """
+ if self.current_char == left_ch:
+ return 0
+
+ if start_pos is None:
+ start_pos = 0
+ else:
+ start_pos = max(0, start_pos)
+
+ stack = 1
+
+ # Look backward.
+ for i in range(self.cursor_position - 1, start_pos - 1, -1):
+ c = self.text[i]
+
+ if c == right_ch:
+ stack += 1
+ elif c == left_ch:
+ stack -= 1
+
+ if stack == 0:
+ return i - self.cursor_position
+
+ def find_matching_bracket_position(self, start_pos=None, end_pos=None):
"""
Return relative cursor position of matching [, (, { or < bracket.
-
- When `start_pos` or `end_pos` are given. Don't look past the positions.
+
+ When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
- # Look for a match.
+ # Look for a match.
for A, B in '()', '[]', '{}', '<>':
if self.current_char == A:
- return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
+ return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
elif self.current_char == B:
- return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
+ return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
return 0
@@ -746,7 +746,7 @@ class Document(object):
"""
Relative position for the last non blank character of this line.
"""
- return len(self.current_line.rstrip()) - self.cursor_position_col - 1
+ return len(self.current_line.rstrip()) - self.cursor_position_col - 1
def get_column_cursor_position(self, column):
"""
@@ -760,7 +760,7 @@ class Document(object):
return column - current_column
- def selection_range(self): # XXX: shouldn't this return `None` if there is no selection???
+ def selection_range(self): # XXX: shouldn't this return `None` if there is no selection???
"""
Return (from, to) tuple of the selection.
start and end position are included.
@@ -800,46 +800,46 @@ class Document(object):
else:
# In case of a LINES selection, go to the start/end of the lines.
if self.selection.type == SelectionType.LINES:
- from_ = max(0, self.text.rfind('\n', 0, from_) + 1)
+ from_ = max(0, self.text.rfind('\n', 0, from_) + 1)
- if self.text.find('\n', to) >= 0:
- to = self.text.find('\n', to)
+ if self.text.find('\n', to) >= 0:
+ to = self.text.find('\n', to)
else:
- to = len(self.text) - 1
+ to = len(self.text) - 1
yield from_, to
- def selection_range_at_line(self, row):
- """
- If the selection spans a portion of the given line, return a (from, to) tuple.
- Otherwise, return None.
- """
- if self.selection:
- row_start = self.translate_row_col_to_index(row, 0)
- row_end = self.translate_row_col_to_index(row, max(0, len(self.lines[row]) - 1))
-
- from_, to = sorted([self.cursor_position, self.selection.original_cursor_position])
-
- # Take the intersection of the current line and the selection.
- intersection_start = max(row_start, from_)
- intersection_end = min(row_end, to)
-
- if intersection_start <= intersection_end:
- if self.selection.type == SelectionType.LINES:
- intersection_start = row_start
- intersection_end = row_end
- elif self.selection.type == SelectionType.BLOCK:
- _, col1 = self.translate_index_to_position(from_)
- _, col2 = self.translate_index_to_position(to)
- col1, col2 = sorted([col1, col2])
- intersection_start = self.translate_row_col_to_index(row, col1)
- intersection_end = self.translate_row_col_to_index(row, col2)
-
- _, from_column = self.translate_index_to_position(intersection_start)
- _, to_column = self.translate_index_to_position(intersection_end)
-
- return from_column, to_column
-
+ def selection_range_at_line(self, row):
+ """
+ If the selection spans a portion of the given line, return a (from, to) tuple.
+ Otherwise, return None.
+ """
+ if self.selection:
+ row_start = self.translate_row_col_to_index(row, 0)
+ row_end = self.translate_row_col_to_index(row, max(0, len(self.lines[row]) - 1))
+
+ from_, to = sorted([self.cursor_position, self.selection.original_cursor_position])
+
+ # Take the intersection of the current line and the selection.
+ intersection_start = max(row_start, from_)
+ intersection_end = min(row_end, to)
+
+ if intersection_start <= intersection_end:
+ if self.selection.type == SelectionType.LINES:
+ intersection_start = row_start
+ intersection_end = row_end
+ elif self.selection.type == SelectionType.BLOCK:
+ _, col1 = self.translate_index_to_position(from_)
+ _, col2 = self.translate_index_to_position(to)
+ col1, col2 = sorted([col1, col2])
+ intersection_start = self.translate_row_col_to_index(row, col1)
+ intersection_end = self.translate_row_col_to_index(row, col2)
+
+ _, from_column = self.translate_index_to_position(intersection_start)
+ _, to_column = self.translate_index_to_position(intersection_end)
+
+ return from_column, to_column
+
def cut_selection(self):
"""
Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the
@@ -911,7 +911,7 @@ class Document(object):
new_text = '\n'.join(lines)
elif data.type == SelectionType.BLOCK:
- lines = self.lines[:]
+ lines = self.lines[:]
start_line = self.cursor_position_row
start_column = self.cursor_position_col + (0 if before else 1)
@@ -941,36 +941,36 @@ class Document(object):
return count
- def start_of_paragraph(self, count=1, before=False):
- """
- Return the start of the current paragraph. (Relative cursor position.)
- """
- def match_func(text):
- return not text or text.isspace()
-
- line_index = self.find_previous_matching_line(match_func=match_func, count=count)
-
- if line_index:
- add = 0 if before else 1
- return min(0, self.get_cursor_up_position(count=-line_index) + add)
- else:
- return -self.cursor_position
-
- def end_of_paragraph(self, count=1, after=False):
- """
- Return the end of the current paragraph. (Relative cursor position.)
- """
- def match_func(text):
- return not text or text.isspace()
-
- line_index = self.find_next_matching_line(match_func=match_func, count=count)
-
- if line_index:
- add = 0 if after else 1
- return max(0, self.get_cursor_down_position(count=line_index) - add)
- else:
- return len(self.text_after_cursor)
-
+ def start_of_paragraph(self, count=1, before=False):
+ """
+ Return the start of the current paragraph. (Relative cursor position.)
+ """
+ def match_func(text):
+ return not text or text.isspace()
+
+ line_index = self.find_previous_matching_line(match_func=match_func, count=count)
+
+ if line_index:
+ add = 0 if before else 1
+ return min(0, self.get_cursor_up_position(count=-line_index) + add)
+ else:
+ return -self.cursor_position
+
+ def end_of_paragraph(self, count=1, after=False):
+ """
+ Return the end of the current paragraph. (Relative cursor position.)
+ """
+ def match_func(text):
+ return not text or text.isspace()
+
+ line_index = self.find_next_matching_line(match_func=match_func, count=count)
+
+ if line_index:
+ add = 0 if after else 1
+ return max(0, self.get_cursor_down_position(count=line_index) - add)
+ else:
+ return len(self.text_after_cursor)
+
# Modifiers.
def insert_after(self, text):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/enums.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/enums.py
index e7c87536eb..6945f44c96 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/enums.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/enums.py
@@ -6,12 +6,12 @@ class IncrementalSearchDirection(object):
BACKWARD = 'BACKWARD'
-class EditingMode(object):
- # The set of key bindings that is active.
- VI = 'VI'
- EMACS = 'EMACS'
-
-
+class EditingMode(object):
+ # The set of key bindings that is active.
+ VI = 'VI'
+ EMACS = 'EMACS'
+
+
#: Name of the search buffer.
SEARCH_BUFFER = 'SEARCH_BUFFER'
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_posix.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_posix.py
index 737ca0ec00..426ed96f67 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_posix.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_posix.py
@@ -67,10 +67,10 @@ class PosixAsyncioEventLoop(EventLoop):
inputstream.feed(data)
timeout.reset()
- # Quit when the input stream was closed.
- if stdin_reader.closed:
- self.stop()
-
+ # Quit when the input stream was closed.
+ if stdin_reader.closed:
+ self.stop()
+
self.loop.add_reader(stdin.fileno(), stdin_ready)
# Block this coroutine until stop() has been called.
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_win32.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_win32.py
index 6e4e2ca9e7..45f5f52679 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_win32.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/asyncio_win32.py
@@ -66,8 +66,8 @@ class Win32AsyncioEventLoop(EventLoop):
# was not created here.
self.closed = True
- self._console_input_reader.close()
-
+ self._console_input_reader.close()
+
def run_in_executor(self, callback):
self.loop.run_in_executor(None, callback)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/base.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/base.py
index 520ab9e366..db86face66 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/base.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/base.py
@@ -74,12 +74,12 @@ class EventLoop(with_metaclass(ABCMeta, object)):
Call this function in the main event loop. Similar to Twisted's
``callFromThread``.
- :param _max_postpone_until: `None` or `time.time` value. For interal
+ :param _max_postpone_until: `None` or `time.time` value. For interal
use. If the eventloop is saturated, consider this task to be low
priority and postpone maximum until this timestamp. (For instance,
repaint is done using low priority.)
-
- Note: In the past, this used to be a datetime.datetime instance,
- but apparently, executing `time.time` is more efficient: it
- does fewer system calls. (It doesn't read /etc/localtime.)
+
+ Note: In the past, this used to be a datetime.datetime instance,
+ but apparently, executing `time.time` is more efficient: it
+ does fewer system calls. (It doesn't read /etc/localtime.)
"""
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/inputhook.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/inputhook.py
index 44e0a60591..bab1f4c003 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/inputhook.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/inputhook.py
@@ -25,8 +25,8 @@ controls everything.
from __future__ import unicode_literals
import os
import threading
-from prompt_toolkit.utils import is_windows
-from .select import select_fds
+from prompt_toolkit.utils import is_windows
+from .select import select_fds
__all__ = (
'InputHookContext',
@@ -75,19 +75,19 @@ class InputHookContext(object):
# Flush the read end of the pipe.
try:
- # Before calling 'os.read', call select.select. This is required
- # when the gevent monkey patch has been applied. 'os.read' is never
- # monkey patched and won't be cooperative, so that would block all
- # other select() calls otherwise.
- # See: http://www.gevent.org/gevent.os.html
-
- # Note: On Windows, this is apparently not an issue.
- # However, if we would ever want to add a select call, it
- # should use `windll.kernel32.WaitForMultipleObjects`,
- # because `select.select` can't wait for a pipe on Windows.
- if not is_windows():
- select_fds([self._r], timeout=None)
-
+ # Before calling 'os.read', call select.select. This is required
+ # when the gevent monkey patch has been applied. 'os.read' is never
+ # monkey patched and won't be cooperative, so that would block all
+ # other select() calls otherwise.
+ # See: http://www.gevent.org/gevent.os.html
+
+ # Note: On Windows, this is apparently not an issue.
+ # However, if we would ever want to add a select call, it
+ # should use `windll.kernel32.WaitForMultipleObjects`,
+ # because `select.select` can't wait for a pipe on Windows.
+ if not is_windows():
+ select_fds([self._r], timeout=None)
+
os.read(self._r, 1024)
except OSError:
# This happens when the window resizes and a SIGWINCH was received.
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py
index be70d61f19..f631dbd891 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py
@@ -3,7 +3,7 @@ import fcntl
import os
import signal
import threading
-import time
+import time
from prompt_toolkit.terminal.vt100_input import InputStream
from prompt_toolkit.utils import DummyContext, in_main_thread
@@ -13,22 +13,22 @@ from .callbacks import EventLoopCallbacks
from .inputhook import InputHookContext
from .posix_utils import PosixStdinReader
from .utils import TimeIt
-from .select import AutoSelector, Selector, fd_to_int
+from .select import AutoSelector, Selector, fd_to_int
__all__ = (
'PosixEventLoop',
)
-_now = time.time
+_now = time.time
class PosixEventLoop(EventLoop):
"""
Event loop for posix systems (Linux, Mac os X).
"""
- def __init__(self, inputhook=None, selector=AutoSelector):
+ def __init__(self, inputhook=None, selector=AutoSelector):
assert inputhook is None or callable(inputhook)
- assert issubclass(selector, Selector)
+ assert issubclass(selector, Selector)
self.running = False
self.closed = False
@@ -37,7 +37,7 @@ class PosixEventLoop(EventLoop):
self._calls_from_executor = []
self._read_fds = {} # Maps fd to handler.
- self.selector = selector()
+ self.selector = selector()
# Create a pipe for inter thread communication.
self._schedule_pipe = os.pipe()
@@ -84,31 +84,31 @@ class PosixEventLoop(EventLoop):
# Set timeout again.
current_timeout[0] = INPUT_TIMEOUT
- # Quit when the input stream was closed.
- if stdin_reader.closed:
- self.stop()
-
+ # Quit when the input stream was closed.
+ if stdin_reader.closed:
+ self.stop()
+
self.add_reader(stdin, read_from_stdin)
self.add_reader(self._schedule_pipe[0], None)
with ctx:
while self._running:
# Call inputhook.
- if self._inputhook_context:
- with TimeIt() as inputhook_timer:
+ if self._inputhook_context:
+ with TimeIt() as inputhook_timer:
def ready(wait):
" True when there is input ready. The inputhook should return control. "
return self._ready_for_reading(current_timeout[0] if wait else 0) != []
self._inputhook_context.call_inputhook(ready)
- inputhook_duration = inputhook_timer.duration
- else:
- inputhook_duration = 0
+ inputhook_duration = inputhook_timer.duration
+ else:
+ inputhook_duration = 0
# Calculate remaining timeout. (The inputhook consumed some of the time.)
if current_timeout[0] is None:
remaining_timeout = None
else:
- remaining_timeout = max(0, current_timeout[0] - inputhook_duration)
+ remaining_timeout = max(0, current_timeout[0] - inputhook_duration)
# Wait until input is ready.
fds = self._ready_for_reading(remaining_timeout)
@@ -126,23 +126,23 @@ class PosixEventLoop(EventLoop):
# case.
tasks = []
low_priority_tasks = []
- now = None # Lazy load time. (Fewer system calls.)
+ now = None # Lazy load time. (Fewer system calls.)
for fd in fds:
# For the 'call_from_executor' fd, put each pending
# item on either the high or low priority queue.
if fd == self._schedule_pipe[0]:
for c, max_postpone_until in self._calls_from_executor:
- if max_postpone_until is None:
- # Execute now.
+ if max_postpone_until is None:
+ # Execute now.
tasks.append(c)
else:
- # Execute soon, if `max_postpone_until` is in the future.
- now = now or _now()
- if max_postpone_until < now:
- tasks.append(c)
- else:
- low_priority_tasks.append((c, max_postpone_until))
+ # Execute soon, if `max_postpone_until` is in the future.
+ now = now or _now()
+ if max_postpone_until < now:
+ tasks.append(c)
+ else:
+ low_priority_tasks.append((c, max_postpone_until))
self._calls_from_executor = []
# Flush all the pipe content.
@@ -185,8 +185,8 @@ class PosixEventLoop(EventLoop):
"""
Return the file descriptors that are ready for reading.
"""
- fds = self.selector.select(timeout)
- return fds
+ fds = self.selector.select(timeout)
+ return fds
def received_winch(self):
"""
@@ -230,23 +230,23 @@ class PosixEventLoop(EventLoop):
Call this function in the main event loop.
Similar to Twisted's ``callFromThread``.
- :param _max_postpone_until: `None` or `time.time` value. For interal
+ :param _max_postpone_until: `None` or `time.time` value. For interal
use. If the eventloop is saturated, consider this task to be low
priority and postpone maximum until this timestamp. (For instance,
repaint is done using low priority.)
"""
- assert _max_postpone_until is None or isinstance(_max_postpone_until, float)
+ assert _max_postpone_until is None or isinstance(_max_postpone_until, float)
self._calls_from_executor.append((callback, _max_postpone_until))
if self._schedule_pipe:
- try:
- os.write(self._schedule_pipe[1], b'x')
- except (AttributeError, IndexError, OSError):
- # Handle race condition. We're in a different thread.
- # - `_schedule_pipe` could have become None in the meantime.
- # - We catch `OSError` (actually BrokenPipeError), because the
- # main thread could have closed the pipe already.
- pass
+ try:
+ os.write(self._schedule_pipe[1], b'x')
+ except (AttributeError, IndexError, OSError):
+ # Handle race condition. We're in a different thread.
+ # - `_schedule_pipe` could have become None in the meantime.
+ # - We catch `OSError` (actually BrokenPipeError), because the
+ # main thread could have closed the pipe already.
+ pass
def stop(self):
"""
@@ -270,18 +270,18 @@ class PosixEventLoop(EventLoop):
def add_reader(self, fd, callback):
" Add read file descriptor to the event loop. "
- fd = fd_to_int(fd)
+ fd = fd_to_int(fd)
self._read_fds[fd] = callback
- self.selector.register(fd)
+ self.selector.register(fd)
def remove_reader(self, fd):
" Remove read file descriptor from the event loop. "
- fd = fd_to_int(fd)
-
+ fd = fd_to_int(fd)
+
if fd in self._read_fds:
del self._read_fds[fd]
- self.selector.unregister(fd)
+ self.selector.unregister(fd)
class call_on_sigwinch(object):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py
index bb675ba9aa..320df438ca 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py
@@ -2,7 +2,7 @@ from __future__ import unicode_literals
from codecs import getincrementaldecoder
import os
-import six
+import six
__all__ = (
'PosixStdinReader',
@@ -13,42 +13,42 @@ class PosixStdinReader(object):
"""
Wrapper around stdin which reads (nonblocking) the next available 1024
bytes and decodes it.
-
- Note that you can't be sure that the input file is closed if the ``read``
- function returns an empty string. When ``errors=ignore`` is passed,
- ``read`` can return an empty string if all malformed input was replaced by
- an empty string. (We can't block here and wait for more input.) So, because
- of that, check the ``closed`` attribute, to be sure that the file has been
- closed.
-
- :param stdin_fd: File descriptor from which we read.
- :param errors: Can be 'ignore', 'strict' or 'replace'.
- On Python3, this can be 'surrogateescape', which is the default.
-
- 'surrogateescape' is preferred, because this allows us to transfer
- unrecognised bytes to the key bindings. Some terminals, like lxterminal
- and Guake, use the 'Mxx' notation to send mouse events, where each 'x'
- can be any possible byte.
+
+ Note that you can't be sure that the input file is closed if the ``read``
+ function returns an empty string. When ``errors=ignore`` is passed,
+ ``read`` can return an empty string if all malformed input was replaced by
+ an empty string. (We can't block here and wait for more input.) So, because
+ of that, check the ``closed`` attribute, to be sure that the file has been
+ closed.
+
+ :param stdin_fd: File descriptor from which we read.
+ :param errors: Can be 'ignore', 'strict' or 'replace'.
+ On Python3, this can be 'surrogateescape', which is the default.
+
+ 'surrogateescape' is preferred, because this allows us to transfer
+ unrecognised bytes to the key bindings. Some terminals, like lxterminal
+ and Guake, use the 'Mxx' notation to send mouse events, where each 'x'
+ can be any possible byte.
"""
- # By default, we want to 'ignore' errors here. The input stream can be full
- # of junk. One occurrence of this that I had was when using iTerm2 on OS X,
- # with "Option as Meta" checked (You should choose "Option as +Esc".)
-
- def __init__(self, stdin_fd,
- errors=('ignore' if six.PY2 else 'surrogateescape')):
+ # By default, we want to 'ignore' errors here. The input stream can be full
+ # of junk. One occurrence of this that I had was when using iTerm2 on OS X,
+ # with "Option as Meta" checked (You should choose "Option as +Esc".)
+
+ def __init__(self, stdin_fd,
+ errors=('ignore' if six.PY2 else 'surrogateescape')):
assert isinstance(stdin_fd, int)
self.stdin_fd = stdin_fd
- self.errors = errors
+ self.errors = errors
# Create incremental decoder for decoding stdin.
# We can not just do `os.read(stdin.fileno(), 1024).decode('utf-8')`, because
# it could be that we are in the middle of a utf-8 byte sequence.
self._stdin_decoder_cls = getincrementaldecoder('utf-8')
- self._stdin_decoder = self._stdin_decoder_cls(errors=errors)
+ self._stdin_decoder = self._stdin_decoder_cls(errors=errors)
+
+ #: True when there is nothing anymore to read.
+ self.closed = False
- #: True when there is nothing anymore to read.
- self.closed = False
-
def read(self, count=1024):
# By default we choose a rather small chunk size, because reading
# big amounts of input at once, causes the event loop to process
@@ -56,27 +56,27 @@ class PosixStdinReader(object):
# loop. This will make the application feel unresponsive.
"""
Read the input and return it as a string.
-
- Return the text. Note that this can return an empty string, even when
- the input stream was not yet closed. This means that something went
- wrong during the decoding.
+
+ Return the text. Note that this can return an empty string, even when
+ the input stream was not yet closed. This means that something went
+ wrong during the decoding.
"""
- if self.closed:
- return b''
-
+ if self.closed:
+ return b''
+
# Note: the following works better than wrapping `self.stdin` like
# `codecs.getreader('utf-8')(stdin)` and doing `read(1)`.
# Somehow that causes some latency when the escape
# character is pressed. (Especially on combination with the `select`.)
try:
data = os.read(self.stdin_fd, count)
-
- # Nothing more to read, stream is closed.
- if data == b'':
- self.closed = True
- return ''
+
+ # Nothing more to read, stream is closed.
+ if data == b'':
+ self.closed = True
+ return ''
except OSError:
# In case of SIGWINCH
data = b''
- return self._stdin_decoder.decode(data)
+ return self._stdin_decoder.decode(data)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/select.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/select.py
index 66e8e346b8..f678f84c55 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/select.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/select.py
@@ -1,216 +1,216 @@
-"""
-Selectors for the Posix event loop.
-"""
-from __future__ import unicode_literals, absolute_import
-import sys
-import abc
-import errno
-import select
-import six
-
-__all__ = (
- 'AutoSelector',
- 'PollSelector',
- 'SelectSelector',
- 'Selector',
- 'fd_to_int',
-)
-
-def fd_to_int(fd):
- assert isinstance(fd, int) or hasattr(fd, 'fileno')
-
- if isinstance(fd, int):
- return fd
- else:
- return fd.fileno()
-
-
-class Selector(six.with_metaclass(abc.ABCMeta, object)):
- @abc.abstractmethod
- def register(self, fd):
- assert isinstance(fd, int)
-
- @abc.abstractmethod
- def unregister(self, fd):
- assert isinstance(fd, int)
-
- @abc.abstractmethod
- def select(self, timeout):
- pass
-
- @abc.abstractmethod
- def close(self):
- pass
-
-
-class AutoSelector(Selector):
- def __init__(self):
- self._fds = []
-
- self._select_selector = SelectSelector()
- self._selectors = [self._select_selector]
-
- # When 'select.poll' exists, create a PollSelector.
- if hasattr(select, 'poll'):
- self._poll_selector = PollSelector()
- self._selectors.append(self._poll_selector)
- else:
- self._poll_selector = None
-
- # Use of the 'select' module, that was introduced in Python3.4. We don't
- # use it before 3.5 however, because this is the point where this module
- # retries interrupted system calls.
- if sys.version_info >= (3, 5):
- self._py3_selector = Python3Selector()
- self._selectors.append(self._py3_selector)
- else:
- self._py3_selector = None
-
- def register(self, fd):
- assert isinstance(fd, int)
-
- self._fds.append(fd)
-
- for sel in self._selectors:
- sel.register(fd)
-
- def unregister(self, fd):
- assert isinstance(fd, int)
-
- self._fds.remove(fd)
-
- for sel in self._selectors:
- sel.unregister(fd)
-
- def select(self, timeout):
- # Try Python 3 selector first.
- if self._py3_selector:
- try:
- return self._py3_selector.select(timeout)
- except PermissionError:
- # We had a situation (in pypager) where epoll raised a
- # PermissionError when a local file descriptor was registered,
- # however poll and select worked fine. So, in that case, just
- # try using select below.
- pass
-
- try:
- # Prefer 'select.select', if we don't have much file descriptors.
- # This is more universal.
- return self._select_selector.select(timeout)
- except ValueError:
- # When we have more than 1024 open file descriptors, we'll always
- # get a "ValueError: filedescriptor out of range in select()" for
- # 'select'. In this case, try, using 'poll' instead.
- if self._poll_selector is not None:
- return self._poll_selector.select(timeout)
- else:
- raise
-
- def close(self):
- for sel in self._selectors:
- sel.close()
-
-
-class Python3Selector(Selector):
- """
- Use of the Python3 'selectors' module.
-
- NOTE: Only use on Python 3.5 or newer!
- """
- def __init__(self):
- assert sys.version_info >= (3, 5)
-
- import selectors # Inline import: Python3 only!
- self._sel = selectors.DefaultSelector()
-
- def register(self, fd):
- assert isinstance(fd, int)
- import selectors # Inline import: Python3 only!
- self._sel.register(fd, selectors.EVENT_READ, None)
-
- def unregister(self, fd):
- assert isinstance(fd, int)
- self._sel.unregister(fd)
-
- def select(self, timeout):
- events = self._sel.select(timeout=timeout)
- return [key.fileobj for key, mask in events]
-
- def close(self):
- self._sel.close()
-
-
-class PollSelector(Selector):
- def __init__(self):
- self._poll = select.poll()
-
- def register(self, fd):
- assert isinstance(fd, int)
- self._poll.register(fd, select.POLLIN)
-
- def unregister(self, fd):
- assert isinstance(fd, int)
-
- def select(self, timeout):
- tuples = self._poll.poll(timeout) # Returns (fd, event) tuples.
- return [t[0] for t in tuples]
-
- def close(self):
- pass # XXX
-
-
-class SelectSelector(Selector):
- """
- Wrapper around select.select.
-
- When the SIGWINCH signal is handled, other system calls, like select
- are aborted in Python. This wrapper will retry the system call.
- """
- def __init__(self):
- self._fds = []
-
- def register(self, fd):
- self._fds.append(fd)
-
- def unregister(self, fd):
- self._fds.remove(fd)
-
- def select(self, timeout):
- while True:
- try:
- return select.select(self._fds, [], [], timeout)[0]
- except select.error as e:
- # Retry select call when EINTR
- if e.args and e.args[0] == errno.EINTR:
- continue
- else:
- raise
-
- def close(self):
- pass
-
-
-def select_fds(read_fds, timeout, selector=AutoSelector):
- """
- Wait for a list of file descriptors (`read_fds`) to become ready for
- reading. This chooses the most appropriate select-tool for use in
- prompt-toolkit.
- """
- # Map to ensure that we return the objects that were passed in originally.
- # Whether they are a fd integer or an object that has a fileno().
- # (The 'poll' implementation for instance, returns always integers.)
- fd_map = dict((fd_to_int(fd), fd) for fd in read_fds)
-
- # Wait, using selector.
- sel = selector()
- try:
- for fd in read_fds:
- sel.register(fd)
-
- result = sel.select(timeout)
-
- if result is not None:
- return [fd_map[fd_to_int(fd)] for fd in result]
- finally:
- sel.close()
+"""
+Selectors for the Posix event loop.
+"""
+from __future__ import unicode_literals, absolute_import
+import sys
+import abc
+import errno
+import select
+import six
+
+__all__ = (
+ 'AutoSelector',
+ 'PollSelector',
+ 'SelectSelector',
+ 'Selector',
+ 'fd_to_int',
+)
+
+def fd_to_int(fd):
+ assert isinstance(fd, int) or hasattr(fd, 'fileno')
+
+ if isinstance(fd, int):
+ return fd
+ else:
+ return fd.fileno()
+
+
+class Selector(six.with_metaclass(abc.ABCMeta, object)):
+ @abc.abstractmethod
+ def register(self, fd):
+ assert isinstance(fd, int)
+
+ @abc.abstractmethod
+ def unregister(self, fd):
+ assert isinstance(fd, int)
+
+ @abc.abstractmethod
+ def select(self, timeout):
+ pass
+
+ @abc.abstractmethod
+ def close(self):
+ pass
+
+
+class AutoSelector(Selector):
+ def __init__(self):
+ self._fds = []
+
+ self._select_selector = SelectSelector()
+ self._selectors = [self._select_selector]
+
+ # When 'select.poll' exists, create a PollSelector.
+ if hasattr(select, 'poll'):
+ self._poll_selector = PollSelector()
+ self._selectors.append(self._poll_selector)
+ else:
+ self._poll_selector = None
+
+ # Use of the 'select' module, that was introduced in Python3.4. We don't
+ # use it before 3.5 however, because this is the point where this module
+ # retries interrupted system calls.
+ if sys.version_info >= (3, 5):
+ self._py3_selector = Python3Selector()
+ self._selectors.append(self._py3_selector)
+ else:
+ self._py3_selector = None
+
+ def register(self, fd):
+ assert isinstance(fd, int)
+
+ self._fds.append(fd)
+
+ for sel in self._selectors:
+ sel.register(fd)
+
+ def unregister(self, fd):
+ assert isinstance(fd, int)
+
+ self._fds.remove(fd)
+
+ for sel in self._selectors:
+ sel.unregister(fd)
+
+ def select(self, timeout):
+ # Try Python 3 selector first.
+ if self._py3_selector:
+ try:
+ return self._py3_selector.select(timeout)
+ except PermissionError:
+ # We had a situation (in pypager) where epoll raised a
+ # PermissionError when a local file descriptor was registered,
+ # however poll and select worked fine. So, in that case, just
+ # try using select below.
+ pass
+
+ try:
+ # Prefer 'select.select', if we don't have much file descriptors.
+ # This is more universal.
+ return self._select_selector.select(timeout)
+ except ValueError:
+ # When we have more than 1024 open file descriptors, we'll always
+ # get a "ValueError: filedescriptor out of range in select()" for
+ # 'select'. In this case, try, using 'poll' instead.
+ if self._poll_selector is not None:
+ return self._poll_selector.select(timeout)
+ else:
+ raise
+
+ def close(self):
+ for sel in self._selectors:
+ sel.close()
+
+
+class Python3Selector(Selector):
+ """
+ Use of the Python3 'selectors' module.
+
+ NOTE: Only use on Python 3.5 or newer!
+ """
+ def __init__(self):
+ assert sys.version_info >= (3, 5)
+
+ import selectors # Inline import: Python3 only!
+ self._sel = selectors.DefaultSelector()
+
+ def register(self, fd):
+ assert isinstance(fd, int)
+ import selectors # Inline import: Python3 only!
+ self._sel.register(fd, selectors.EVENT_READ, None)
+
+ def unregister(self, fd):
+ assert isinstance(fd, int)
+ self._sel.unregister(fd)
+
+ def select(self, timeout):
+ events = self._sel.select(timeout=timeout)
+ return [key.fileobj for key, mask in events]
+
+ def close(self):
+ self._sel.close()
+
+
+class PollSelector(Selector):
+ def __init__(self):
+ self._poll = select.poll()
+
+ def register(self, fd):
+ assert isinstance(fd, int)
+ self._poll.register(fd, select.POLLIN)
+
+ def unregister(self, fd):
+ assert isinstance(fd, int)
+
+ def select(self, timeout):
+ tuples = self._poll.poll(timeout) # Returns (fd, event) tuples.
+ return [t[0] for t in tuples]
+
+ def close(self):
+ pass # XXX
+
+
+class SelectSelector(Selector):
+ """
+ Wrapper around select.select.
+
+ When the SIGWINCH signal is handled, other system calls, like select
+ are aborted in Python. This wrapper will retry the system call.
+ """
+ def __init__(self):
+ self._fds = []
+
+ def register(self, fd):
+ self._fds.append(fd)
+
+ def unregister(self, fd):
+ self._fds.remove(fd)
+
+ def select(self, timeout):
+ while True:
+ try:
+ return select.select(self._fds, [], [], timeout)[0]
+ except select.error as e:
+ # Retry select call when EINTR
+ if e.args and e.args[0] == errno.EINTR:
+ continue
+ else:
+ raise
+
+ def close(self):
+ pass
+
+
+def select_fds(read_fds, timeout, selector=AutoSelector):
+ """
+ Wait for a list of file descriptors (`read_fds`) to become ready for
+ reading. This chooses the most appropriate select-tool for use in
+ prompt-toolkit.
+ """
+ # Map to ensure that we return the objects that were passed in originally.
+ # Whether they are a fd integer or an object that has a fileno().
+ # (The 'poll' implementation for instance, returns always integers.)
+ fd_map = dict((fd_to_int(fd), fd) for fd in read_fds)
+
+ # Wait, using selector.
+ sel = selector()
+ try:
+ for fd in read_fds:
+ sel.register(fd)
+
+ result = sel.select(timeout)
+
+ if result is not None:
+ return [fd_map[fd_to_int(fd)] for fd in result]
+ finally:
+ sel.close()
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/win32.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/win32.py
index 0a3f63620c..18e356f088 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/win32.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/win32.py
@@ -15,7 +15,7 @@ from .utils import TimeIt
from ctypes import windll, pointer
from ctypes.wintypes import DWORD, BOOL, HANDLE
-import msvcrt
+import msvcrt
import threading
__all__ = (
@@ -29,23 +29,23 @@ INPUT_TIMEOUT_MS = int(1000 * INPUT_TIMEOUT)
class Win32EventLoop(EventLoop):
"""
Event loop for Windows systems.
-
- :param recognize_paste: When True, try to discover paste actions and turn
- the event into a BracketedPaste.
+
+ :param recognize_paste: When True, try to discover paste actions and turn
+ the event into a BracketedPaste.
"""
- def __init__(self, inputhook=None, recognize_paste=True):
+ def __init__(self, inputhook=None, recognize_paste=True):
assert inputhook is None or callable(inputhook)
self._event = HANDLE(_create_event())
- self._console_input_reader = ConsoleInputReader(recognize_paste=recognize_paste)
+ self._console_input_reader = ConsoleInputReader(recognize_paste=recognize_paste)
self._calls_from_executor = []
self.closed = False
self._running = False
- # Additional readers.
- self._read_fds = {} # Maps fd to handler.
-
+ # Additional readers.
+ self._read_fds = {} # Maps fd to handler.
+
# Create inputhook context.
self._inputhook_context = InputHookContext(inputhook) if inputhook else None
@@ -86,9 +86,9 @@ class Win32EventLoop(EventLoop):
windll.kernel32.ResetEvent(self._event)
self._process_queued_calls_from_executor()
- elif handle in self._read_fds:
- callback = self._read_fds[handle]
- callback()
+ elif handle in self._read_fds:
+ callback = self._read_fds[handle]
+ callback()
else:
# Fire input timeout event.
callbacks.input_timeout()
@@ -98,9 +98,9 @@ class Win32EventLoop(EventLoop):
"""
Return the handle that is ready for reading or `None` on timeout.
"""
- handles = [self._event, self._console_input_reader.handle]
- handles.extend(self._read_fds.keys())
- return _wait_for_handles(handles, timeout)
+ handles = [self._event, self._console_input_reader.handle]
+ handles.extend(self._read_fds.keys())
+ return _wait_for_handles(handles, timeout)
def stop(self):
self._running = False
@@ -114,8 +114,8 @@ class Win32EventLoop(EventLoop):
if self._inputhook_context:
self._inputhook_context.close()
- self._console_input_reader.close()
-
+ self._console_input_reader.close()
+
def run_in_executor(self, callback):
"""
Run a long running function in a background thread.
@@ -148,14 +148,14 @@ class Win32EventLoop(EventLoop):
def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
- h = msvcrt.get_osfhandle(fd)
- self._read_fds[h] = callback
+ h = msvcrt.get_osfhandle(fd)
+ self._read_fds[h] = callback
def remove_reader(self, fd):
" Stop watching the file descriptor for read availability. "
- h = msvcrt.get_osfhandle(fd)
- if h in self._read_fds:
- del self._read_fds[h]
+ h = msvcrt.get_osfhandle(fd)
+ if h in self._read_fds:
+ del self._read_fds[h]
def _wait_for_handles(handles, timeout=-1):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/base.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/base.py
index f2b872a2d0..6a1a1d0b10 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/base.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/base.py
@@ -2,9 +2,9 @@ from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from six import with_metaclass
-from prompt_toolkit.utils import test_callable_args
+from prompt_toolkit.utils import test_callable_args
+
-
__all__ = (
'Filter',
'Never',
@@ -29,19 +29,19 @@ class Filter(with_metaclass(ABCMeta, object)):
"""
Chaining of filters using the & operator.
"""
- return _and_cache[self, other]
+ return _and_cache[self, other]
def __or__(self, other):
"""
Chaining of filters using the | operator.
"""
- return _or_cache[self, other]
+ return _or_cache[self, other]
def __invert__(self):
"""
Inverting of filters using the ~ operator.
"""
- return _invert_cache[self]
+ return _invert_cache[self]
def __bool__(self):
"""
@@ -56,11 +56,11 @@ class Filter(with_metaclass(ABCMeta, object)):
__nonzero__ = __bool__ # For Python 2.
- def test_args(self, *args):
+ def test_args(self, *args):
"""
- Test whether this filter can be called with the following argument list.
+ Test whether this filter can be called with the following argument list.
"""
- return test_callable_args(self.__call__, args)
+ return test_callable_args(self.__call__, args)
class _AndCache(dict):
@@ -74,14 +74,14 @@ class _AndCache(dict):
removed. In practise however, there is a finite amount of filters.
"""
def __missing__(self, filters):
- a, b = filters
- assert isinstance(b, Filter), 'Expecting filter, got %r' % b
-
- if isinstance(b, Always) or isinstance(a, Never):
- return a
- elif isinstance(b, Never) or isinstance(a, Always):
- return b
-
+ a, b = filters
+ assert isinstance(b, Filter), 'Expecting filter, got %r' % b
+
+ if isinstance(b, Always) or isinstance(a, Never):
+ return a
+ elif isinstance(b, Never) or isinstance(a, Always):
+ return b
+
result = _AndList(filters)
self[filters] = result
return result
@@ -90,30 +90,30 @@ class _AndCache(dict):
class _OrCache(dict):
""" Cache for Or operation between filters. """
def __missing__(self, filters):
- a, b = filters
- assert isinstance(b, Filter), 'Expecting filter, got %r' % b
-
- if isinstance(b, Always) or isinstance(a, Never):
- return b
- elif isinstance(b, Never) or isinstance(a, Always):
- return a
-
+ a, b = filters
+ assert isinstance(b, Filter), 'Expecting filter, got %r' % b
+
+ if isinstance(b, Always) or isinstance(a, Never):
+ return b
+ elif isinstance(b, Never) or isinstance(a, Always):
+ return a
+
result = _OrList(filters)
self[filters] = result
return result
-class _InvertCache(dict):
- """ Cache for inversion operator. """
- def __missing__(self, filter):
- result = _Invert(filter)
- self[filter] = result
- return result
-
-
+class _InvertCache(dict):
+ """ Cache for inversion operator. """
+ def __missing__(self, filter):
+ result = _Invert(filter)
+ self[filter] = result
+ return result
+
+
_and_cache = _AndCache()
_or_cache = _OrCache()
-_invert_cache = _InvertCache()
+_invert_cache = _InvertCache()
class _AndList(Filter):
@@ -131,8 +131,8 @@ class _AndList(Filter):
self.filters = all_filters
- def test_args(self, *args):
- return all(f.test_args(*args) for f in self.filters)
+ def test_args(self, *args):
+ return all(f.test_args(*args) for f in self.filters)
def __call__(self, *a, **kw):
return all(f(*a, **kw) for f in self.filters)
@@ -156,8 +156,8 @@ class _OrList(Filter):
self.filters = all_filters
- def test_args(self, *args):
- return all(f.test_args(*args) for f in self.filters)
+ def test_args(self, *args):
+ return all(f.test_args(*args) for f in self.filters)
def __call__(self, *a, **kw):
return any(f(*a, **kw) for f in self.filters)
@@ -179,8 +179,8 @@ class _Invert(Filter):
def __repr__(self):
return '~%r' % self.filter
- def test_args(self, *args):
- return self.filter.test_args(*args)
+ def test_args(self, *args):
+ return self.filter.test_args(*args)
class Always(Filter):
@@ -230,5 +230,5 @@ class Condition(Filter):
def __repr__(self):
return 'Condition(%r)' % self.func
- def test_args(self, *a):
- return test_callable_args(self.func, a)
+ def test_args(self, *a):
+ return test_callable_args(self.func, a)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/cli.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/cli.py
index dbcd74dea9..c0b07317be 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/cli.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/cli.py
@@ -3,9 +3,9 @@ Filters that accept a `CommandLineInterface` as argument.
"""
from __future__ import unicode_literals
from .base import Filter
-from prompt_toolkit.enums import EditingMode
-from prompt_toolkit.key_binding.vi_state import InputMode as ViInputMode
-from prompt_toolkit.cache import memoized
+from prompt_toolkit.enums import EditingMode
+from prompt_toolkit.key_binding.vi_state import InputMode as ViInputMode
+from prompt_toolkit.cache import memoized
__all__ = (
'HasArg',
@@ -21,38 +21,38 @@ __all__ = (
'IsReadOnly',
'IsReturning',
'RendererHeightIsKnown',
- 'InEditingMode',
-
- # Vi modes.
- 'ViMode',
- 'ViNavigationMode',
- 'ViInsertMode',
- 'ViInsertMultipleMode',
- 'ViReplaceMode',
- 'ViSelectionMode',
- 'ViWaitingForTextObjectMode',
- 'ViDigraphMode',
-
- # Emacs modes.
- 'EmacsMode',
- 'EmacsInsertMode',
- 'EmacsSelectionMode',
+ 'InEditingMode',
+
+ # Vi modes.
+ 'ViMode',
+ 'ViNavigationMode',
+ 'ViInsertMode',
+ 'ViInsertMultipleMode',
+ 'ViReplaceMode',
+ 'ViSelectionMode',
+ 'ViWaitingForTextObjectMode',
+ 'ViDigraphMode',
+
+ # Emacs modes.
+ 'EmacsMode',
+ 'EmacsInsertMode',
+ 'EmacsSelectionMode',
)
-@memoized()
+@memoized()
class HasFocus(Filter):
"""
Enable when this buffer has the focus.
"""
def __init__(self, buffer_name):
- self._buffer_name = buffer_name
+ self._buffer_name = buffer_name
+
+ @property
+ def buffer_name(self):
+ " The given buffer name. (Read-only) "
+ return self._buffer_name
- @property
- def buffer_name(self):
- " The given buffer name. (Read-only) "
- return self._buffer_name
-
def __call__(self, cli):
return cli.current_buffer_name == self.buffer_name
@@ -60,19 +60,19 @@ class HasFocus(Filter):
return 'HasFocus(%r)' % self.buffer_name
-@memoized()
+@memoized()
class InFocusStack(Filter):
"""
Enable when this buffer appears on the focus stack.
"""
def __init__(self, buffer_name):
- self._buffer_name = buffer_name
+ self._buffer_name = buffer_name
+
+ @property
+ def buffer_name(self):
+ " The given buffer name. (Read-only) "
+ return self._buffer_name
- @property
- def buffer_name(self):
- " The given buffer name. (Read-only) "
- return self._buffer_name
-
def __call__(self, cli):
return self.buffer_name in cli.buffers.focus_stack
@@ -80,7 +80,7 @@ class InFocusStack(Filter):
return 'InFocusStack(%r)' % self.buffer_name
-@memoized()
+@memoized()
class HasSelection(Filter):
"""
Enable when the current buffer has a selection.
@@ -92,7 +92,7 @@ class HasSelection(Filter):
return 'HasSelection()'
-@memoized()
+@memoized()
class HasCompletions(Filter):
"""
Enable when the current buffer has completions.
@@ -104,7 +104,7 @@ class HasCompletions(Filter):
return 'HasCompletions()'
-@memoized()
+@memoized()
class IsMultiline(Filter):
"""
Enable in multiline mode.
@@ -116,7 +116,7 @@ class IsMultiline(Filter):
return 'IsMultiline()'
-@memoized()
+@memoized()
class IsReadOnly(Filter):
"""
True when the current buffer is read only.
@@ -128,7 +128,7 @@ class IsReadOnly(Filter):
return 'IsReadOnly()'
-@memoized()
+@memoized()
class HasValidationError(Filter):
"""
Current buffer has validation error.
@@ -140,7 +140,7 @@ class HasValidationError(Filter):
return 'HasValidationError()'
-@memoized()
+@memoized()
class HasArg(Filter):
"""
Enable when the input processor has an 'arg'.
@@ -152,7 +152,7 @@ class HasArg(Filter):
return 'HasArg()'
-@memoized()
+@memoized()
class HasSearch(Filter):
"""
Incremental search is active.
@@ -164,7 +164,7 @@ class HasSearch(Filter):
return 'HasSearch()'
-@memoized()
+@memoized()
class IsReturning(Filter):
"""
When a return value has been set.
@@ -176,7 +176,7 @@ class IsReturning(Filter):
return 'IsReturning()'
-@memoized()
+@memoized()
class IsAborting(Filter):
"""
True when aborting. (E.g. Control-C pressed.)
@@ -188,7 +188,7 @@ class IsAborting(Filter):
return 'IsAborting()'
-@memoized()
+@memoized()
class IsExiting(Filter):
"""
True when exiting. (E.g. Control-D pressed.)
@@ -200,7 +200,7 @@ class IsExiting(Filter):
return 'IsExiting()'
-@memoized()
+@memoized()
class IsDone(Filter):
"""
True when the CLI is returning, aborting or exiting.
@@ -212,7 +212,7 @@ class IsDone(Filter):
return 'IsDone()'
-@memoized()
+@memoized()
class RendererHeightIsKnown(Filter):
"""
Only True when the renderer knows it's real height.
@@ -228,168 +228,168 @@ class RendererHeightIsKnown(Filter):
def __repr__(self):
return 'RendererHeightIsKnown()'
-
-
-@memoized()
-class InEditingMode(Filter):
- """
- Check whether a given editing mode is active. (Vi or Emacs.)
- """
- def __init__(self, editing_mode):
- self._editing_mode = editing_mode
-
- @property
- def editing_mode(self):
- " The given editing mode. (Read-only) "
- return self._editing_mode
-
- def __call__(self, cli):
- return cli.editing_mode == self.editing_mode
-
- def __repr__(self):
- return 'InEditingMode(%r)' % (self.editing_mode, )
-
-
-@memoized()
-class ViMode(Filter):
- def __call__(self, cli):
- return cli.editing_mode == EditingMode.VI
-
- def __repr__(self):
- return 'ViMode()'
-
-
-@memoized()
-class ViNavigationMode(Filter):
- """
- Active when the set for Vi navigation key bindings are active.
- """
- def __call__(self, cli):
- if (cli.editing_mode != EditingMode.VI
- or cli.vi_state.operator_func
- or cli.vi_state.waiting_for_digraph
- or cli.current_buffer.selection_state):
- return False
-
- return (cli.vi_state.input_mode == ViInputMode.NAVIGATION or
- cli.current_buffer.read_only())
-
- def __repr__(self):
- return 'ViNavigationMode()'
-
-
-@memoized()
-class ViInsertMode(Filter):
- def __call__(self, cli):
- if (cli.editing_mode != EditingMode.VI
- or cli.vi_state.operator_func
- or cli.vi_state.waiting_for_digraph
- or cli.current_buffer.selection_state
- or cli.current_buffer.read_only()):
- return False
-
- return cli.vi_state.input_mode == ViInputMode.INSERT
-
- def __repr__(self):
- return 'ViInputMode()'
-
-
-@memoized()
-class ViInsertMultipleMode(Filter):
- def __call__(self, cli):
- if (cli.editing_mode != EditingMode.VI
- or cli.vi_state.operator_func
- or cli.vi_state.waiting_for_digraph
- or cli.current_buffer.selection_state
- or cli.current_buffer.read_only()):
- return False
-
- return cli.vi_state.input_mode == ViInputMode.INSERT_MULTIPLE
-
- def __repr__(self):
- return 'ViInsertMultipleMode()'
-
-
-@memoized()
-class ViReplaceMode(Filter):
- def __call__(self, cli):
- if (cli.editing_mode != EditingMode.VI
- or cli.vi_state.operator_func
- or cli.vi_state.waiting_for_digraph
- or cli.current_buffer.selection_state
- or cli.current_buffer.read_only()):
- return False
-
- return cli.vi_state.input_mode == ViInputMode.REPLACE
-
- def __repr__(self):
- return 'ViReplaceMode()'
-
-
-@memoized()
-class ViSelectionMode(Filter):
- def __call__(self, cli):
- if cli.editing_mode != EditingMode.VI:
- return False
-
- return bool(cli.current_buffer.selection_state)
-
- def __repr__(self):
- return 'ViSelectionMode()'
-
-
-@memoized()
-class ViWaitingForTextObjectMode(Filter):
- def __call__(self, cli):
- if cli.editing_mode != EditingMode.VI:
- return False
-
- return cli.vi_state.operator_func is not None
-
- def __repr__(self):
- return 'ViWaitingForTextObjectMode()'
-
-
-@memoized()
-class ViDigraphMode(Filter):
- def __call__(self, cli):
- if cli.editing_mode != EditingMode.VI:
- return False
-
- return cli.vi_state.waiting_for_digraph
-
- def __repr__(self):
- return 'ViDigraphMode()'
-
-
-@memoized()
-class EmacsMode(Filter):
- " When the Emacs bindings are active. "
- def __call__(self, cli):
- return cli.editing_mode == EditingMode.EMACS
-
- def __repr__(self):
- return 'EmacsMode()'
-
-
-@memoized()
-class EmacsInsertMode(Filter):
- def __call__(self, cli):
- if (cli.editing_mode != EditingMode.EMACS
- or cli.current_buffer.selection_state
- or cli.current_buffer.read_only()):
- return False
- return True
-
- def __repr__(self):
- return 'EmacsInsertMode()'
-
-
-@memoized()
-class EmacsSelectionMode(Filter):
- def __call__(self, cli):
- return (cli.editing_mode == EditingMode.EMACS
- and cli.current_buffer.selection_state)
-
- def __repr__(self):
- return 'EmacsSelectionMode()'
+
+
+@memoized()
+class InEditingMode(Filter):
+ """
+ Check whether a given editing mode is active. (Vi or Emacs.)
+ """
+ def __init__(self, editing_mode):
+ self._editing_mode = editing_mode
+
+ @property
+ def editing_mode(self):
+ " The given editing mode. (Read-only) "
+ return self._editing_mode
+
+ def __call__(self, cli):
+ return cli.editing_mode == self.editing_mode
+
+ def __repr__(self):
+ return 'InEditingMode(%r)' % (self.editing_mode, )
+
+
+@memoized()
+class ViMode(Filter):
+ def __call__(self, cli):
+ return cli.editing_mode == EditingMode.VI
+
+ def __repr__(self):
+ return 'ViMode()'
+
+
+@memoized()
+class ViNavigationMode(Filter):
+ """
+ Active when the set for Vi navigation key bindings are active.
+ """
+ def __call__(self, cli):
+ if (cli.editing_mode != EditingMode.VI
+ or cli.vi_state.operator_func
+ or cli.vi_state.waiting_for_digraph
+ or cli.current_buffer.selection_state):
+ return False
+
+ return (cli.vi_state.input_mode == ViInputMode.NAVIGATION or
+ cli.current_buffer.read_only())
+
+ def __repr__(self):
+ return 'ViNavigationMode()'
+
+
+@memoized()
+class ViInsertMode(Filter):
+ def __call__(self, cli):
+ if (cli.editing_mode != EditingMode.VI
+ or cli.vi_state.operator_func
+ or cli.vi_state.waiting_for_digraph
+ or cli.current_buffer.selection_state
+ or cli.current_buffer.read_only()):
+ return False
+
+ return cli.vi_state.input_mode == ViInputMode.INSERT
+
+ def __repr__(self):
+ return 'ViInputMode()'
+
+
+@memoized()
+class ViInsertMultipleMode(Filter):
+ def __call__(self, cli):
+ if (cli.editing_mode != EditingMode.VI
+ or cli.vi_state.operator_func
+ or cli.vi_state.waiting_for_digraph
+ or cli.current_buffer.selection_state
+ or cli.current_buffer.read_only()):
+ return False
+
+ return cli.vi_state.input_mode == ViInputMode.INSERT_MULTIPLE
+
+ def __repr__(self):
+ return 'ViInsertMultipleMode()'
+
+
+@memoized()
+class ViReplaceMode(Filter):
+ def __call__(self, cli):
+ if (cli.editing_mode != EditingMode.VI
+ or cli.vi_state.operator_func
+ or cli.vi_state.waiting_for_digraph
+ or cli.current_buffer.selection_state
+ or cli.current_buffer.read_only()):
+ return False
+
+ return cli.vi_state.input_mode == ViInputMode.REPLACE
+
+ def __repr__(self):
+ return 'ViReplaceMode()'
+
+
+@memoized()
+class ViSelectionMode(Filter):
+ def __call__(self, cli):
+ if cli.editing_mode != EditingMode.VI:
+ return False
+
+ return bool(cli.current_buffer.selection_state)
+
+ def __repr__(self):
+ return 'ViSelectionMode()'
+
+
+@memoized()
+class ViWaitingForTextObjectMode(Filter):
+ def __call__(self, cli):
+ if cli.editing_mode != EditingMode.VI:
+ return False
+
+ return cli.vi_state.operator_func is not None
+
+ def __repr__(self):
+ return 'ViWaitingForTextObjectMode()'
+
+
+@memoized()
+class ViDigraphMode(Filter):
+ def __call__(self, cli):
+ if cli.editing_mode != EditingMode.VI:
+ return False
+
+ return cli.vi_state.waiting_for_digraph
+
+ def __repr__(self):
+ return 'ViDigraphMode()'
+
+
+@memoized()
+class EmacsMode(Filter):
+ " When the Emacs bindings are active. "
+ def __call__(self, cli):
+ return cli.editing_mode == EditingMode.EMACS
+
+ def __repr__(self):
+ return 'EmacsMode()'
+
+
+@memoized()
+class EmacsInsertMode(Filter):
+ def __call__(self, cli):
+ if (cli.editing_mode != EditingMode.EMACS
+ or cli.current_buffer.selection_state
+ or cli.current_buffer.read_only()):
+ return False
+ return True
+
+ def __repr__(self):
+ return 'EmacsInsertMode()'
+
+
+@memoized()
+class EmacsSelectionMode(Filter):
+ def __call__(self, cli):
+ return (cli.editing_mode == EditingMode.EMACS
+ and cli.current_buffer.selection_state)
+
+ def __repr__(self):
+ return 'EmacsSelectionMode()'
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/types.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/types.py
index fa518b7b95..3e89c39c01 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/types.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/types.py
@@ -1,37 +1,37 @@
from __future__ import unicode_literals
from six import with_metaclass
-from collections import defaultdict
-import weakref
+from collections import defaultdict
+import weakref
__all__ = (
'CLIFilter',
'SimpleFilter',
)
-# Cache for _FilterTypeMeta. (Don't test the same __instancecheck__ twice as
-# long as the object lives. -- We do this a lot and calling 'test_args' is
-# expensive.)
-_instance_check_cache = defaultdict(weakref.WeakKeyDictionary)
-
-
+# Cache for _FilterTypeMeta. (Don't test the same __instancecheck__ twice as
+# long as the object lives. -- We do this a lot and calling 'test_args' is
+# expensive.)
+_instance_check_cache = defaultdict(weakref.WeakKeyDictionary)
+
+
class _FilterTypeMeta(type):
def __instancecheck__(cls, instance):
- cache = _instance_check_cache[tuple(cls.arguments_list)]
-
- def get():
- " The actual test. "
- if not hasattr(instance, 'test_args'):
- return False
- return instance.test_args(*cls.arguments_list)
-
- try:
- return cache[instance]
- except KeyError:
- result = get()
- cache[instance] = result
- return result
-
-
+ cache = _instance_check_cache[tuple(cls.arguments_list)]
+
+ def get():
+ " The actual test. "
+ if not hasattr(instance, 'test_args'):
+ return False
+ return instance.test_args(*cls.arguments_list)
+
+ try:
+ return cache[instance]
+ except KeyError:
+ result = get()
+ cache[instance] = result
+ return result
+
+
class _FilterType(with_metaclass(_FilterTypeMeta)):
def __new__(cls):
raise NotImplementedError('This class should not be initiated.')
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/utils.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/utils.py
index a4da36f863..836d2956e7 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/utils.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/filters/utils.py
@@ -16,8 +16,8 @@ def to_simple_filter(bool_or_filter):
Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter.
"""
- if not isinstance(bool_or_filter, (bool, SimpleFilter)):
- raise TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
+ if not isinstance(bool_or_filter, (bool, SimpleFilter)):
+ raise TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
@@ -30,8 +30,8 @@ def to_cli_filter(bool_or_filter):
Accept both booleans and CLIFilters as input and
turn it into a CLIFilter.
"""
- if not isinstance(bool_or_filter, (bool, CLIFilter)):
- raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
+ if not isinstance(bool_or_filter, (bool, CLIFilter)):
+ raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/history.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/history.py
index 62ab42bd38..d1eb5f2730 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/history.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/history.py
@@ -103,8 +103,8 @@ class FileHistory(History):
# Save to file.
with open(self.filename, 'ab') as f:
- def write(t):
- f.write(t.encode('utf-8'))
+ def write(t):
+ f.write(t.encode('utf-8'))
write('\n# %s\n' % datetime.datetime.now())
for line in string.split('\n'):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/input.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/input.py
index d3ed08ce86..f123732560 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/input.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/input.py
@@ -7,7 +7,7 @@ from .utils import DummyContext, is_windows
from abc import ABCMeta, abstractmethod
from six import with_metaclass
-import io
+import io
import os
import sys
@@ -63,21 +63,21 @@ class StdinInput(Input):
def __init__(self, stdin=None):
self.stdin = stdin or sys.stdin
- # The input object should be a TTY.
- assert self.stdin.isatty()
-
- # Test whether the given input object has a file descriptor.
- # (Idle reports stdin to be a TTY, but fileno() is not implemented.)
- try:
- # This should not raise, but can return 0.
- self.stdin.fileno()
- except io.UnsupportedOperation:
- if 'idlelib.run' in sys.modules:
- raise io.UnsupportedOperation(
- 'Stdin is not a terminal. Running from Idle is not supported.')
- else:
- raise io.UnsupportedOperation('Stdin is not a terminal.')
-
+ # The input object should be a TTY.
+ assert self.stdin.isatty()
+
+ # Test whether the given input object has a file descriptor.
+ # (Idle reports stdin to be a TTY, but fileno() is not implemented.)
+ try:
+ # This should not raise, but can return 0.
+ self.stdin.fileno()
+ except io.UnsupportedOperation:
+ if 'idlelib.run' in sys.modules:
+ raise io.UnsupportedOperation(
+ 'Stdin is not a terminal. Running from Idle is not supported.')
+ else:
+ raise io.UnsupportedOperation('Stdin is not a terminal.')
+
def __repr__(self):
return 'StdinInput(stdin=%r)' % (self.stdin,)
@@ -114,22 +114,22 @@ class PipeInput(Input):
def read(self):
return os.read(self._r)
- def send_text(self, data):
- " Send text to the input. "
+ def send_text(self, data):
+ " Send text to the input. "
os.write(self._w, data.encode('utf-8'))
- # Deprecated alias for `send_text`.
- send = send_text
-
+ # Deprecated alias for `send_text`.
+ send = send_text
+
def raw_mode(self):
return DummyContext()
def cooked_mode(self):
return DummyContext()
-
- def close(self):
- " Close pipe fds. "
- os.close(self._r)
- os.close(self._w)
- self._r = None
- self._w = None
+
+ def close(self):
+ " Close pipe fds. "
+ os.close(self._r)
+ os.close(self._w)
+ self._r = None
+ self._w = None
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py
index 9b3a1be04d..e1e0e56393 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py
@@ -10,30 +10,30 @@ import six
import sys
import textwrap
import threading
-import time
-import types
+import time
+import types
import weakref
-from subprocess import Popen
-
+from subprocess import Popen
+
from .application import Application, AbortAction
from .buffer import Buffer
from .buffer_mapping import BufferMapping
-from .completion import CompleteEvent, get_common_complete_suffix
+from .completion import CompleteEvent, get_common_complete_suffix
from .enums import SEARCH_BUFFER
from .eventloop.base import EventLoop
from .eventloop.callbacks import EventLoopCallbacks
from .filters import Condition
from .input import StdinInput, Input
from .key_binding.input_processor import InputProcessor
-from .key_binding.input_processor import KeyPress
-from .key_binding.registry import Registry
-from .key_binding.vi_state import ViState
-from .keys import Keys
+from .key_binding.input_processor import KeyPress
+from .key_binding.registry import Registry
+from .key_binding.vi_state import ViState
+from .keys import Keys
from .output import Output
from .renderer import Renderer, print_tokens
from .search_state import SearchState
-from .utils import Event
+from .utils import Event
# Following import is required for backwards compatibility.
from .buffer import AcceptAction
@@ -57,23 +57,23 @@ class CommandLineInterface(object):
:param application: :class:`~prompt_toolkit.application.Application` instance.
:param eventloop: The :class:`~prompt_toolkit.eventloop.base.EventLoop` to
- be used when `run` is called. The easiest way to create
- an eventloop is by calling
- :meth:`~prompt_toolkit.shortcuts.create_eventloop`.
+ be used when `run` is called. The easiest way to create
+ an eventloop is by calling
+ :meth:`~prompt_toolkit.shortcuts.create_eventloop`.
:param input: :class:`~prompt_toolkit.input.Input` instance.
:param output: :class:`~prompt_toolkit.output.Output` instance. (Probably
Vt100_Output or Win32Output.)
"""
def __init__(self, application, eventloop=None, input=None, output=None):
assert isinstance(application, Application)
- assert isinstance(eventloop, EventLoop), 'Passing an eventloop is required.'
+ assert isinstance(eventloop, EventLoop), 'Passing an eventloop is required.'
assert output is None or isinstance(output, Output)
assert input is None or isinstance(input, Input)
- from .shortcuts import create_output
+ from .shortcuts import create_output
self.application = application
- self.eventloop = eventloop
+ self.eventloop = eventloop
self._is_running = False
# Inputs and outputs.
@@ -84,15 +84,15 @@ class CommandLineInterface(object):
assert isinstance(application.buffers, BufferMapping)
self.buffers = application.buffers
- #: EditingMode.VI or EditingMode.EMACS
- self.editing_mode = application.editing_mode
-
+ #: EditingMode.VI or EditingMode.EMACS
+ self.editing_mode = application.editing_mode
+
#: Quoted insert. This flag is set if we go into quoted insert mode.
self.quoted_insert = False
- #: Vi state. (For Vi key bindings.)
- self.vi_state = ViState()
-
+ #: Vi state. (For Vi key bindings.)
+ self.vi_state = ViState()
+
#: The `Renderer` instance.
# Make sure that the same stdout is used, when a custom renderer has been passed.
self.renderer = Renderer(
@@ -125,20 +125,20 @@ class CommandLineInterface(object):
for name, b in self.buffers.items():
self.add_buffer(name, b)
- # Events.
- self.on_buffer_changed = Event(self, application.on_buffer_changed)
- self.on_initialize = Event(self, application.on_initialize)
- self.on_input_timeout = Event(self, application.on_input_timeout)
- self.on_invalidate = Event(self, application.on_invalidate)
- self.on_render = Event(self, application.on_render)
- self.on_reset = Event(self, application.on_reset)
- self.on_start = Event(self, application.on_start)
- self.on_stop = Event(self, application.on_stop)
+ # Events.
+ self.on_buffer_changed = Event(self, application.on_buffer_changed)
+ self.on_initialize = Event(self, application.on_initialize)
+ self.on_input_timeout = Event(self, application.on_input_timeout)
+ self.on_invalidate = Event(self, application.on_invalidate)
+ self.on_render = Event(self, application.on_render)
+ self.on_reset = Event(self, application.on_reset)
+ self.on_start = Event(self, application.on_start)
+ self.on_stop = Event(self, application.on_stop)
# Trigger initialize callback.
- self.reset()
- self.on_initialize += self.application.on_initialize
- self.on_initialize.fire()
+ self.reset()
+ self.on_initialize += self.application.on_initialize
+ self.on_initialize.fire()
@property
def layout(self):
@@ -174,7 +174,7 @@ class CommandLineInterface(object):
ensures that it's only called while typing if the
`complete_while_typing` filter is enabled.
"""
- def on_text_insert(_):
+ def on_text_insert(_):
# Only complete when "complete_while_typing" is enabled.
if buffer.completer and buffer.complete_while_typing():
completer_function()
@@ -187,18 +187,18 @@ class CommandLineInterface(object):
buffer.on_text_insert += create_on_insert_handler()
- def buffer_changed(_):
- """
- When the text in a buffer changes.
- (A paste event is also a change, but not an insert. So we don't
- want to do autocompletions in this case, but we want to propagate
- the on_buffer_changed event.)
- """
- # Trigger on_buffer_changed.
- self.on_buffer_changed.fire()
-
- buffer.on_text_changed += buffer_changed
-
+ def buffer_changed(_):
+ """
+ When the text in a buffer changes.
+ (A paste event is also a change, but not an insert. So we don't
+ want to do autocompletions in this case, but we want to propagate
+ the on_buffer_changed event.)
+ """
+ # Trigger on_buffer_changed.
+ self.on_buffer_changed.fire()
+
+ buffer.on_text_changed += buffer_changed
+
def start_completion(self, buffer_name=None, select_first=False,
select_last=False, insert_common_part=False,
complete_event=None):
@@ -293,14 +293,14 @@ class CommandLineInterface(object):
self.renderer.reset()
self.input_processor.reset()
self.layout.reset()
- self.vi_state.reset()
+ self.vi_state.reset()
# Search new search state. (Does also remember what has to be
# highlighted.)
self.search_state = SearchState(ignore_case=Condition(lambda: self.is_ignoring_case))
# Trigger reset event.
- self.on_reset.fire()
+ self.on_reset.fire()
@property
def in_paste_mode(self):
@@ -333,17 +333,17 @@ class CommandLineInterface(object):
self._redraw()
# Call redraw in the eventloop (thread safe).
- # Usually with the high priority, in order to make the application
- # feel responsive, but this can be tuned by changing the value of
- # `max_render_postpone_time`.
- if self.max_render_postpone_time:
- _max_postpone_until = time.time() + self.max_render_postpone_time
- else:
- _max_postpone_until = None
-
- self.eventloop.call_from_executor(
- redraw, _max_postpone_until=_max_postpone_until)
-
+ # Usually with the high priority, in order to make the application
+ # feel responsive, but this can be tuned by changing the value of
+ # `max_render_postpone_time`.
+ if self.max_render_postpone_time:
+ _max_postpone_until = time.time() + self.max_render_postpone_time
+ else:
+ _max_postpone_until = None
+
+ self.eventloop.call_from_executor(
+ redraw, _max_postpone_until=_max_postpone_until)
+
# Depracated alias for 'invalidate'.
request_redraw = invalidate
@@ -357,9 +357,9 @@ class CommandLineInterface(object):
self.render_counter += 1
self.renderer.render(self, self.layout, is_done=self.is_done)
- # Fire render event.
- self.on_render.fire()
-
+ # Fire render event.
+ self.on_render.fire()
+
def _on_resize(self):
"""
When the window size changes, we erase the current output and request
@@ -368,7 +368,7 @@ class CommandLineInterface(object):
"""
# Erase, request position (when cursor is at the start position)
# and redraw again. -- The order is important.
- self.renderer.erase(leave_alternate_screen=False, erase_title=False)
+ self.renderer.erase(leave_alternate_screen=False, erase_title=False)
self.renderer.request_absolute_cursor_position()
self._redraw()
@@ -387,7 +387,7 @@ class CommandLineInterface(object):
c()
del self.pre_run_callables[:]
- def run(self, reset_current_buffer=False, pre_run=None):
+ def run(self, reset_current_buffer=False, pre_run=None):
"""
Read input from the command line.
This runs the eventloop until a return value has been set.
@@ -401,7 +401,7 @@ class CommandLineInterface(object):
try:
self._is_running = True
- self.on_start.fire()
+ self.on_start.fire()
self.reset()
# Call pre_run.
@@ -416,16 +416,16 @@ class CommandLineInterface(object):
finally:
# Clean up renderer. (This will leave the alternate screen, if we use
# that.)
-
- # If exit/abort haven't been called set, but another exception was
- # thrown instead for some reason, make sure that we redraw in exit
- # mode.
- if not self.is_done:
- self._exit_flag = True
- self._redraw()
-
+
+ # If exit/abort haven't been called set, but another exception was
+ # thrown instead for some reason, make sure that we redraw in exit
+ # mode.
+ if not self.is_done:
+ self._exit_flag = True
+ self._redraw()
+
self.renderer.reset()
- self.on_stop.fire()
+ self.on_stop.fire()
self._is_running = False
# Return result.
@@ -442,41 +442,41 @@ class CommandLineInterface(object):
This is only available on Python >3.3, with asyncio.
"""
- # Inline import, because it slows down startup when asyncio is not
- # needed.
- import asyncio
+ # Inline import, because it slows down startup when asyncio is not
+ # needed.
+ import asyncio
- @asyncio.coroutine
- def run():
- assert pre_run is None or callable(pre_run)
+ @asyncio.coroutine
+ def run():
+ assert pre_run is None or callable(pre_run)
- try:
- self._is_running = True
+ try:
+ self._is_running = True
- self.on_start.fire()
+ self.on_start.fire()
self.reset()
- # Call pre_run.
+ # Call pre_run.
self._pre_run(pre_run)
- with self.input.raw_mode():
- self.renderer.request_absolute_cursor_position()
- self._redraw()
-
- yield from self.eventloop.run_as_coroutine(
- self.input, self.create_eventloop_callbacks())
-
- return self.return_value()
- finally:
- if not self.is_done:
- self._exit_flag = True
- self._redraw()
-
- self.renderer.reset()
- self.on_stop.fire()
- self._is_running = False
-
- return run()
+ with self.input.raw_mode():
+ self.renderer.request_absolute_cursor_position()
+ self._redraw()
+
+ yield from self.eventloop.run_as_coroutine(
+ self.input, self.create_eventloop_callbacks())
+
+ return self.return_value()
+ finally:
+ if not self.is_done:
+ self._exit_flag = True
+ self._redraw()
+
+ self.renderer.reset()
+ self.on_stop.fire()
+ self._is_running = False
+
+ return run()
'''))
except SyntaxError:
# Python2, or early versions of Python 3.
@@ -488,9 +488,9 @@ class CommandLineInterface(object):
"""
raise NotImplementedError
- def run_sub_application(self, application, done_callback=None, erase_when_done=False,
- _from_application_generator=False):
- # `erase_when_done` is deprecated, set Application.erase_when_done instead.
+ def run_sub_application(self, application, done_callback=None, erase_when_done=False,
+ _from_application_generator=False):
+ # `erase_when_done` is deprecated, set Application.erase_when_done instead.
"""
Run a sub :class:`~prompt_toolkit.application.Application`.
@@ -514,8 +514,8 @@ class CommandLineInterface(object):
raise RuntimeError('Another sub application started already.')
# Erase current application.
- if not _from_application_generator:
- self.renderer.erase()
+ if not _from_application_generator:
+ self.renderer.erase()
# Callback when the sub app is done.
def done():
@@ -523,17 +523,17 @@ class CommandLineInterface(object):
# and reset the renderer. (This reset will also quit the alternate
# screen, if the sub application used that.)
sub_cli._redraw()
- if erase_when_done or application.erase_when_done:
- sub_cli.renderer.erase()
+ if erase_when_done or application.erase_when_done:
+ sub_cli.renderer.erase()
sub_cli.renderer.reset()
sub_cli._is_running = False # Don't render anymore.
self._sub_cli = None
# Restore main application.
- if not _from_application_generator:
- self.renderer.request_absolute_cursor_position()
- self._redraw()
+ if not _from_application_generator:
+ self.renderer.request_absolute_cursor_position()
+ self._redraw()
# Deliver result.
if done_callback:
@@ -636,7 +636,7 @@ class CommandLineInterface(object):
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
- self._return_value = None
+ self._return_value = None
# Run system command.
if cooked_mode:
@@ -652,63 +652,63 @@ class CommandLineInterface(object):
return result
- def run_application_generator(self, coroutine, render_cli_done=False):
- """
- EXPERIMENTAL
- Like `run_in_terminal`, but takes a generator that can yield Application instances.
-
- Example:
-
- def f():
- yield Application1(...)
- print('...')
- yield Application2(...)
- cli.run_in_terminal_async(f)
-
- The values which are yielded by the given coroutine are supposed to be
- `Application` instances that run in the current CLI, all other code is
- supposed to be CPU bound, so except for yielding the applications,
- there should not be any user interaction or I/O in the given function.
- """
- # Draw interface in 'done' state, or erase.
- if render_cli_done:
- self._return_value = True
- self._redraw()
- self.renderer.reset() # Make sure to disable mouse mode, etc...
- else:
- self.renderer.erase()
- self._return_value = None
-
- # Loop through the generator.
- g = coroutine()
- assert isinstance(g, types.GeneratorType)
-
- def step_next(send_value=None):
- " Execute next step of the coroutine."
- try:
- # Run until next yield, in cooked mode.
- with self.input.cooked_mode():
- result = g.send(send_value)
- except StopIteration:
- done()
- except:
- done()
- raise
- else:
- # Process yielded value from coroutine.
- assert isinstance(result, Application)
- self.run_sub_application(result, done_callback=step_next,
- _from_application_generator=True)
-
- def done():
- # Redraw interface again.
- self.renderer.reset()
- self.renderer.request_absolute_cursor_position()
- self._redraw()
-
- # Start processing coroutine.
- step_next()
-
+ def run_application_generator(self, coroutine, render_cli_done=False):
+ """
+ EXPERIMENTAL
+ Like `run_in_terminal`, but takes a generator that can yield Application instances.
+
+ Example:
+
+ def f():
+ yield Application1(...)
+ print('...')
+ yield Application2(...)
+ cli.run_in_terminal_async(f)
+
+ The values which are yielded by the given coroutine are supposed to be
+ `Application` instances that run in the current CLI, all other code is
+ supposed to be CPU bound, so except for yielding the applications,
+ there should not be any user interaction or I/O in the given function.
+ """
+ # Draw interface in 'done' state, or erase.
+ if render_cli_done:
+ self._return_value = True
+ self._redraw()
+ self.renderer.reset() # Make sure to disable mouse mode, etc...
+ else:
+ self.renderer.erase()
+ self._return_value = None
+
+ # Loop through the generator.
+ g = coroutine()
+ assert isinstance(g, types.GeneratorType)
+
+ def step_next(send_value=None):
+ " Execute next step of the coroutine."
+ try:
+ # Run until next yield, in cooked mode.
+ with self.input.cooked_mode():
+ result = g.send(send_value)
+ except StopIteration:
+ done()
+ except:
+ done()
+ raise
+ else:
+ # Process yielded value from coroutine.
+ assert isinstance(result, Application)
+ self.run_sub_application(result, done_callback=step_next,
+ _from_application_generator=True)
+
+ def done():
+ # Redraw interface again.
+ self.renderer.reset()
+ self.renderer.request_absolute_cursor_position()
+ self._redraw()
+
+ # Start processing coroutine.
+ step_next()
+
def run_system_command(self, command):
"""
Run system command (While hiding the prompt. When finished, all the
@@ -716,57 +716,57 @@ class CommandLineInterface(object):
:param command: Shell command to be executed.
"""
- def wait_for_enter():
- """
- Create a sub application to wait for the enter key press.
- This has two advantages over using 'input'/'raw_input':
- - This will share the same input/output I/O.
- - This doesn't block the event loop.
- """
- from .shortcuts import create_prompt_application
-
- registry = Registry()
-
- @registry.add_binding(Keys.ControlJ)
- @registry.add_binding(Keys.ControlM)
- def _(event):
- event.cli.set_return_value(None)
-
- application = create_prompt_application(
- message='Press ENTER to continue...',
- key_bindings_registry=registry)
- self.run_sub_application(application)
-
+ def wait_for_enter():
+ """
+ Create a sub application to wait for the enter key press.
+ This has two advantages over using 'input'/'raw_input':
+ - This will share the same input/output I/O.
+ - This doesn't block the event loop.
+ """
+ from .shortcuts import create_prompt_application
+
+ registry = Registry()
+
+ @registry.add_binding(Keys.ControlJ)
+ @registry.add_binding(Keys.ControlM)
+ def _(event):
+ event.cli.set_return_value(None)
+
+ application = create_prompt_application(
+ message='Press ENTER to continue...',
+ key_bindings_registry=registry)
+ self.run_sub_application(application)
+
def run():
- # Try to use the same input/output file descriptors as the one,
- # used to run this application.
+ # Try to use the same input/output file descriptors as the one,
+ # used to run this application.
+ try:
+ input_fd = self.input.fileno()
+ except AttributeError:
+ input_fd = sys.stdin.fileno()
try:
- input_fd = self.input.fileno()
- except AttributeError:
- input_fd = sys.stdin.fileno()
- try:
- output_fd = self.output.fileno()
- except AttributeError:
- output_fd = sys.stdout.fileno()
-
- # Run sub process.
- # XXX: This will still block the event loop.
- p = Popen(command, shell=True,
- stdin=input_fd, stdout=output_fd)
- p.wait()
-
- # Wait for the user to press enter.
- wait_for_enter()
-
+ output_fd = self.output.fileno()
+ except AttributeError:
+ output_fd = sys.stdout.fileno()
+
+ # Run sub process.
+ # XXX: This will still block the event loop.
+ p = Popen(command, shell=True,
+ stdin=input_fd, stdout=output_fd)
+ p.wait()
+
+ # Wait for the user to press enter.
+ wait_for_enter()
+
self.run_in_terminal(run)
- def suspend_to_background(self, suspend_group=True):
+ def suspend_to_background(self, suspend_group=True):
"""
(Not thread safe -- to be called from inside the key bindings.)
Suspend process.
-
- :param suspend_group: When true, suspend the whole process group.
- (This is the default, and probably what you want.)
+
+ :param suspend_group: When true, suspend the whole process group.
+ (This is the default, and probably what you want.)
"""
# Only suspend when the opperating system supports it.
# (Not on Windows.)
@@ -775,13 +775,13 @@ class CommandLineInterface(object):
# Send `SIGSTP` to own process.
# This will cause it to suspend.
- # Usually we want the whole process group to be suspended. This
- # handles the case when input is piped from another process.
- if suspend_group:
- os.kill(0, signal.SIGTSTP)
- else:
- os.kill(os.getpid(), signal.SIGTSTP)
-
+ # Usually we want the whole process group to be suspended. This
+ # handles the case when input is piped from another process.
+ if suspend_group:
+ os.kill(0, signal.SIGTSTP)
+ else:
+ os.kill(os.getpid(), signal.SIGTSTP)
+
self.run_in_terminal(run)
def print_tokens(self, tokens, style=None):
@@ -835,16 +835,16 @@ class CommandLineInterface(object):
"""
complete_thread_running = [False] # By ref.
- def completion_does_nothing(document, completion):
- """
- Return `True` if applying this completion doesn't have any effect.
- (When it doesn't insert any new text.
- """
- text_before_cursor = document.text_before_cursor
- replaced_text = text_before_cursor[
- len(text_before_cursor) + completion.start_position:]
- return replaced_text == completion.text
-
+ def completion_does_nothing(document, completion):
+ """
+ Return `True` if applying this completion doesn't have any effect.
+ (When it doesn't insert any new text.
+ """
+ text_before_cursor = document.text_before_cursor
+ replaced_text = text_before_cursor[
+ len(text_before_cursor) + completion.start_position:]
+ return replaced_text == completion.text
+
def async_completer(select_first=False, select_last=False,
insert_common_part=False, complete_event=None):
document = buffer.document
@@ -871,13 +871,13 @@ class CommandLineInterface(object):
pressed 'Tab' in the meantime. Also don't set it if the text
was changed in the meantime.
"""
- complete_thread_running[0] = False
-
- # When there is only one completion, which has nothing to add, ignore it.
- if (len(completions) == 1 and
- completion_does_nothing(document, completions[0])):
- del completions[:]
-
+ complete_thread_running[0] = False
+
+ # When there is only one completion, which has nothing to add, ignore it.
+ if (len(completions) == 1 and
+ completion_does_nothing(document, completions[0])):
+ del completions[:]
+
# Set completions if the text was not yet changed.
if buffer.text == document.text and \
buffer.cursor_position == document.cursor_position and \
@@ -886,28 +886,28 @@ class CommandLineInterface(object):
set_completions = True
select_first_anyway = False
- # When the common part has to be inserted, and there
+ # When the common part has to be inserted, and there
# is a common part.
if insert_common_part:
common_part = get_common_complete_suffix(document, completions)
if common_part:
- # Insert the common part, update completions.
+ # Insert the common part, update completions.
buffer.insert_text(common_part)
- if len(completions) > 1:
- # (Don't call `async_completer` again, but
- # recalculate completions. See:
- # https://github.com/ipython/ipython/issues/9658)
- completions[:] = [
- c.new_completion_from_position(len(common_part))
- for c in completions]
- else:
- set_completions = False
+ if len(completions) > 1:
+ # (Don't call `async_completer` again, but
+ # recalculate completions. See:
+ # https://github.com/ipython/ipython/issues/9658)
+ completions[:] = [
+ c.new_completion_from_position(len(common_part))
+ for c in completions]
+ else:
+ set_completions = False
else:
# When we were asked to insert the "common"
# prefix, but there was no common suffix but
# still exactly one match, then select the
# first. (It could be that we have a completion
- # which does * expansion, like '*.py', with
+ # which does * expansion, like '*.py', with
# exactly one match.)
if len(completions) == 1:
select_first_anyway = True
@@ -918,7 +918,7 @@ class CommandLineInterface(object):
go_to_first=select_first or select_first_anyway,
go_to_last=select_last)
self.invalidate()
- elif not buffer.complete_state:
+ elif not buffer.complete_state:
# Otherwise, restart thread.
async_completer()
@@ -953,8 +953,8 @@ class CommandLineInterface(object):
suggestion = buffer.auto_suggest.get_suggestion(self, buffer, document)
def callback():
- suggest_thread_running[0] = False
-
+ suggest_thread_running[0] = False
+
# Set suggestion only if the text was not yet changed.
if buffer.text == document.text and \
buffer.cursor_position == document.cursor_position:
@@ -984,18 +984,18 @@ class CommandLineInterface(object):
"""
return _StdoutProxy(self, raw=raw)
- def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):
+ def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):
"""
Return a context manager that will replace ``sys.stdout`` with a proxy
that makes sure that all printed text will appear above the prompt, and
that it doesn't destroy the output from the renderer.
-
- :param patch_stdout: Replace `sys.stdout`.
- :param patch_stderr: Replace `sys.stderr`.
+
+ :param patch_stdout: Replace `sys.stdout`.
+ :param patch_stderr: Replace `sys.stderr`.
"""
- return _PatchStdoutContext(
- self.stdout_proxy(raw=raw),
- patch_stdout=patch_stdout, patch_stderr=patch_stderr)
+ return _PatchStdoutContext(
+ self.stdout_proxy(raw=raw),
+ patch_stdout=patch_stdout, patch_stderr=patch_stderr)
def create_eventloop_callbacks(self):
return _InterfaceEventLoopCallbacks(self)
@@ -1031,46 +1031,46 @@ class _InterfaceEventLoopCallbacks(EventLoopCallbacks):
def input_timeout(self):
cli = self._active_cli
- cli.on_input_timeout.fire()
+ cli.on_input_timeout.fire()
def feed_key(self, key_press):
"""
Feed a key press to the CommandLineInterface.
"""
- assert isinstance(key_press, KeyPress)
- cli = self._active_cli
-
+ assert isinstance(key_press, KeyPress)
+ cli = self._active_cli
+
# Feed the key and redraw.
- # (When the CLI is in 'done' state, it should return to the event loop
- # as soon as possible. Ignore all key presses beyond this point.)
- if not cli.is_done:
- cli.input_processor.feed(key_press)
- cli.input_processor.process_keys()
+ # (When the CLI is in 'done' state, it should return to the event loop
+ # as soon as possible. Ignore all key presses beyond this point.)
+ if not cli.is_done:
+ cli.input_processor.feed(key_press)
+ cli.input_processor.process_keys()
class _PatchStdoutContext(object):
- def __init__(self, new_stdout, patch_stdout=True, patch_stderr=True):
+ def __init__(self, new_stdout, patch_stdout=True, patch_stderr=True):
self.new_stdout = new_stdout
- self.patch_stdout = patch_stdout
- self.patch_stderr = patch_stderr
+ self.patch_stdout = patch_stdout
+ self.patch_stderr = patch_stderr
def __enter__(self):
self.original_stdout = sys.stdout
- self.original_stderr = sys.stderr
+ self.original_stderr = sys.stderr
+
+ if self.patch_stdout:
+ sys.stdout = self.new_stdout
+ if self.patch_stderr:
+ sys.stderr = self.new_stdout
- if self.patch_stdout:
- sys.stdout = self.new_stdout
- if self.patch_stderr:
- sys.stderr = self.new_stdout
-
def __exit__(self, *a, **kw):
- if self.patch_stdout:
- sys.stdout = self.original_stdout
+ if self.patch_stdout:
+ sys.stdout = self.original_stdout
+
+ if self.patch_stderr:
+ sys.stderr = self.original_stderr
- if self.patch_stderr:
- sys.stderr = self.original_stderr
-
class _StdoutProxy(object):
"""
Proxy for stdout, as returned by
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py
index 6debd6b9c9..401135dec0 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py
@@ -5,11 +5,11 @@ from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasSelection, Condition, EmacsInsertMode, ViInsertMode
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.screen import Point
-from prompt_toolkit.mouse_events import MouseEventType, MouseEvent
+from prompt_toolkit.mouse_events import MouseEventType, MouseEvent
from prompt_toolkit.renderer import HeightIsUnknownError
from prompt_toolkit.utils import suspend_to_background_supported, is_windows
-from .named_commands import get_by_name
+from .named_commands import get_by_name
from ..registry import Registry
@@ -28,7 +28,7 @@ def if_no_repeat(event):
def load_basic_bindings():
registry = Registry()
- insert_mode = ViInsertMode() | EmacsInsertMode()
+ insert_mode = ViInsertMode() | EmacsInsertMode()
handle = registry.add_binding
has_selection = HasSelection()
@@ -88,15 +88,15 @@ def load_basic_bindings():
@handle(Keys.Down)
@handle(Keys.Right)
@handle(Keys.Left)
- @handle(Keys.ShiftUp)
- @handle(Keys.ShiftDown)
- @handle(Keys.ShiftRight)
- @handle(Keys.ShiftLeft)
+ @handle(Keys.ShiftUp)
+ @handle(Keys.ShiftDown)
+ @handle(Keys.ShiftRight)
+ @handle(Keys.ShiftLeft)
@handle(Keys.Home)
@handle(Keys.End)
@handle(Keys.Delete)
@handle(Keys.ShiftDelete)
- @handle(Keys.ControlDelete)
+ @handle(Keys.ControlDelete)
@handle(Keys.PageUp)
@handle(Keys.PageDown)
@handle(Keys.BackTab)
@@ -106,7 +106,7 @@ def load_basic_bindings():
@handle(Keys.ControlUp)
@handle(Keys.ControlDown)
@handle(Keys.Insert)
- @handle(Keys.Ignore)
+ @handle(Keys.Ignore)
def _(event):
"""
First, for any of these keys, Don't do anything by default. Also don't
@@ -118,61 +118,61 @@ def load_basic_bindings():
"""
pass
- # Readline-style bindings.
- handle(Keys.Home)(get_by_name('beginning-of-line'))
- handle(Keys.End)(get_by_name('end-of-line'))
- handle(Keys.Left)(get_by_name('backward-char'))
- handle(Keys.Right)(get_by_name('forward-char'))
- handle(Keys.ControlUp)(get_by_name('previous-history'))
- handle(Keys.ControlDown)(get_by_name('next-history'))
- handle(Keys.ControlL)(get_by_name('clear-screen'))
-
- handle(Keys.ControlK, filter=insert_mode)(get_by_name('kill-line'))
- handle(Keys.ControlU, filter=insert_mode)(get_by_name('unix-line-discard'))
- handle(Keys.ControlH, filter=insert_mode, save_before=if_no_repeat)(
- get_by_name('backward-delete-char'))
- handle(Keys.Backspace, filter=insert_mode, save_before=if_no_repeat)(
- get_by_name('backward-delete-char'))
- handle(Keys.Delete, filter=insert_mode, save_before=if_no_repeat)(
- get_by_name('delete-char'))
- handle(Keys.ShiftDelete, filter=insert_mode, save_before=if_no_repeat)(
- get_by_name('delete-char'))
- handle(Keys.Any, filter=insert_mode, save_before=if_no_repeat)(
- get_by_name('self-insert'))
- handle(Keys.ControlT, filter=insert_mode)(get_by_name('transpose-chars'))
- handle(Keys.ControlW, filter=insert_mode)(get_by_name('unix-word-rubout'))
+ # Readline-style bindings.
+ handle(Keys.Home)(get_by_name('beginning-of-line'))
+ handle(Keys.End)(get_by_name('end-of-line'))
+ handle(Keys.Left)(get_by_name('backward-char'))
+ handle(Keys.Right)(get_by_name('forward-char'))
+ handle(Keys.ControlUp)(get_by_name('previous-history'))
+ handle(Keys.ControlDown)(get_by_name('next-history'))
+ handle(Keys.ControlL)(get_by_name('clear-screen'))
+
+ handle(Keys.ControlK, filter=insert_mode)(get_by_name('kill-line'))
+ handle(Keys.ControlU, filter=insert_mode)(get_by_name('unix-line-discard'))
+ handle(Keys.ControlH, filter=insert_mode, save_before=if_no_repeat)(
+ get_by_name('backward-delete-char'))
+ handle(Keys.Backspace, filter=insert_mode, save_before=if_no_repeat)(
+ get_by_name('backward-delete-char'))
+ handle(Keys.Delete, filter=insert_mode, save_before=if_no_repeat)(
+ get_by_name('delete-char'))
+ handle(Keys.ShiftDelete, filter=insert_mode, save_before=if_no_repeat)(
+ get_by_name('delete-char'))
+ handle(Keys.Any, filter=insert_mode, save_before=if_no_repeat)(
+ get_by_name('self-insert'))
+ handle(Keys.ControlT, filter=insert_mode)(get_by_name('transpose-chars'))
+ handle(Keys.ControlW, filter=insert_mode)(get_by_name('unix-word-rubout'))
handle(Keys.ControlI, filter=insert_mode)(get_by_name('menu-complete'))
handle(Keys.BackTab, filter=insert_mode)(get_by_name('menu-complete-backward'))
- handle(Keys.PageUp, filter= ~has_selection)(get_by_name('previous-history'))
- handle(Keys.PageDown, filter= ~has_selection)(get_by_name('next-history'))
-
+ handle(Keys.PageUp, filter= ~has_selection)(get_by_name('previous-history'))
+ handle(Keys.PageDown, filter= ~has_selection)(get_by_name('next-history'))
+
# CTRL keys.
- text_before_cursor = Condition(lambda cli: cli.current_buffer.text)
- handle(Keys.ControlD, filter=text_before_cursor & insert_mode)(get_by_name('delete-char'))
+ text_before_cursor = Condition(lambda cli: cli.current_buffer.text)
+ handle(Keys.ControlD, filter=text_before_cursor & insert_mode)(get_by_name('delete-char'))
- is_multiline = Condition(lambda cli: cli.current_buffer.is_multiline())
- is_returnable = Condition(lambda cli: cli.current_buffer.accept_action.is_returnable)
+ is_multiline = Condition(lambda cli: cli.current_buffer.is_multiline())
+ is_returnable = Condition(lambda cli: cli.current_buffer.accept_action.is_returnable)
- @handle(Keys.ControlJ, filter=is_multiline & insert_mode)
+ @handle(Keys.ControlJ, filter=is_multiline & insert_mode)
def _(event):
- " Newline (in case of multiline input. "
- event.current_buffer.newline(copy_margin=not event.cli.in_paste_mode)
+ " Newline (in case of multiline input. "
+ event.current_buffer.newline(copy_margin=not event.cli.in_paste_mode)
- @handle(Keys.ControlJ, filter=~is_multiline & is_returnable)
+ @handle(Keys.ControlJ, filter=~is_multiline & is_returnable)
def _(event):
- " Enter, accept input. "
- buff = event.current_buffer
- buff.accept_action.validate_and_handle(event.cli, buff)
+ " Enter, accept input. "
+ buff = event.current_buffer
+ buff.accept_action.validate_and_handle(event.cli, buff)
- # Delete the word before the cursor.
+ # Delete the word before the cursor.
- @handle(Keys.Up)
+ @handle(Keys.Up)
def _(event):
event.current_buffer.auto_up(count=event.arg)
- @handle(Keys.Down)
+ @handle(Keys.Down)
def _(event):
event.current_buffer.auto_down(count=event.arg)
@@ -211,16 +211,16 @@ def load_basic_bindings():
@handle(Keys.BracketedPaste)
def _(event):
" Pasting from clipboard. "
- data = event.data
-
- # Be sure to use \n as line ending.
- # Some terminals (Like iTerm2) seem to paste \r\n line endings in a
- # bracketed paste. See: https://github.com/ipython/ipython/issues/9737
- data = data.replace('\r\n', '\n')
- data = data.replace('\r', '\n')
-
- event.current_buffer.insert_text(data)
-
+ data = event.data
+
+ # Be sure to use \n as line ending.
+ # Some terminals (Like iTerm2) seem to paste \r\n line endings in a
+ # bracketed paste. See: https://github.com/ipython/ipython/issues/9737
+ data = data.replace('\r\n', '\n')
+ data = data.replace('\r', '\n')
+
+ event.current_buffer.insert_text(data)
+
@handle(Keys.Any, filter=Condition(lambda cli: cli.quoted_insert), eager=True)
def _(event):
"""
@@ -228,15 +228,15 @@ def load_basic_bindings():
"""
event.current_buffer.insert_text(event.data, overwrite=False)
event.cli.quoted_insert = False
-
+
return registry
def load_mouse_bindings():
- """
- Key bindings, required for mouse support.
- (Mouse events enter through the key binding system.)
- """
+ """
+ Key bindings, required for mouse support.
+ (Mouse events enter through the key binding system.)
+ """
registry = Registry()
@registry.add_binding(Keys.Vt100MouseEvent)
@@ -253,16 +253,16 @@ def load_mouse_bindings():
# Typical.
mouse_event, x, y = map(ord, event.data[3:])
mouse_event = {
- 32: MouseEventType.MOUSE_DOWN,
- 35: MouseEventType.MOUSE_UP,
- 96: MouseEventType.SCROLL_UP,
- 97: MouseEventType.SCROLL_DOWN,
+ 32: MouseEventType.MOUSE_DOWN,
+ 35: MouseEventType.MOUSE_UP,
+ 96: MouseEventType.SCROLL_UP,
+ 97: MouseEventType.SCROLL_DOWN,
}.get(mouse_event)
-
- # Handle situations where `PosixStdinReader` used surrogateescapes.
- if x >= 0xdc00: x-= 0xdc00
- if y >= 0xdc00: y-= 0xdc00
-
+
+ # Handle situations where `PosixStdinReader` used surrogateescapes.
+ if x >= 0xdc00: x-= 0xdc00
+ if y >= 0xdc00: y-= 0xdc00
+
x -= 32
y -= 32
else:
@@ -283,17 +283,17 @@ def load_mouse_bindings():
# Parse event type.
if sgr:
mouse_event = {
- (0, 'M'): MouseEventType.MOUSE_DOWN,
- (0, 'm'): MouseEventType.MOUSE_UP,
- (64, 'M'): MouseEventType.SCROLL_UP,
- (65, 'M'): MouseEventType.SCROLL_DOWN,
+ (0, 'M'): MouseEventType.MOUSE_DOWN,
+ (0, 'm'): MouseEventType.MOUSE_UP,
+ (64, 'M'): MouseEventType.SCROLL_UP,
+ (65, 'M'): MouseEventType.SCROLL_DOWN,
}.get((mouse_event, m))
else:
mouse_event = {
- 32: MouseEventType.MOUSE_DOWN,
- 35: MouseEventType.MOUSE_UP,
- 96: MouseEventType.SCROLL_UP,
- 97: MouseEventType.SCROLL_DOWN,
+ 32: MouseEventType.MOUSE_DOWN,
+ 35: MouseEventType.MOUSE_UP,
+ 96: MouseEventType.SCROLL_UP,
+ 97: MouseEventType.SCROLL_DOWN,
}.get(mouse_event)
x -= 1
@@ -357,7 +357,7 @@ def load_abort_and_exit_bindings():
return (cli.current_buffer_name == DEFAULT_BUFFER and
not cli.current_buffer.text)
- handle(Keys.ControlD, filter=ctrl_d_condition)(get_by_name('end-of-file'))
+ handle(Keys.ControlD, filter=ctrl_d_condition)(get_by_name('end-of-file'))
return registry
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py
index 2b6405a1fa..4903900bc6 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py
@@ -1,161 +1,161 @@
-"""
-Key binding handlers for displaying completions.
-"""
-from __future__ import unicode_literals
-from prompt_toolkit.completion import CompleteEvent, get_common_complete_suffix
-from prompt_toolkit.utils import get_cwidth
-from prompt_toolkit.keys import Keys
-from prompt_toolkit.key_binding.registry import Registry
-
-import math
-
-__all__ = (
- 'generate_completions',
- 'display_completions_like_readline',
-)
-
-def generate_completions(event):
- r"""
- Tab-completion: where the first tab completes the common suffix and the
- second tab lists all the completions.
- """
- b = event.current_buffer
-
- # When already navigating through completions, select the next one.
- if b.complete_state:
- b.complete_next()
- else:
- event.cli.start_completion(insert_common_part=True, select_first=False)
-
-
-def display_completions_like_readline(event):
- """
- Key binding handler for readline-style tab completion.
- This is meant to be as similar as possible to the way how readline displays
- completions.
-
- Generate the completions immediately (blocking) and display them above the
- prompt in columns.
-
- Usage::
-
- # Call this handler when 'Tab' has been pressed.
- registry.add_binding(Keys.ControlI)(display_completions_like_readline)
- """
- # Request completions.
- b = event.current_buffer
- if b.completer is None:
- return
- complete_event = CompleteEvent(completion_requested=True)
- completions = list(b.completer.get_completions(b.document, complete_event))
-
- # Calculate the common suffix.
- common_suffix = get_common_complete_suffix(b.document, completions)
-
- # One completion: insert it.
- if len(completions) == 1:
- b.delete_before_cursor(-completions[0].start_position)
- b.insert_text(completions[0].text)
- # Multiple completions with common part.
- elif common_suffix:
- b.insert_text(common_suffix)
- # Otherwise: display all completions.
- elif completions:
- _display_completions_like_readline(event.cli, completions)
-
-
-def _display_completions_like_readline(cli, completions):
- """
- Display the list of completions in columns above the prompt.
- This will ask for a confirmation if there are too many completions to fit
- on a single page and provide a paginator to walk through them.
- """
- from prompt_toolkit.shortcuts import create_confirm_application
- assert isinstance(completions, list)
-
- # Get terminal dimensions.
- term_size = cli.output.get_size()
- term_width = term_size.columns
- term_height = term_size.rows
-
- # Calculate amount of required columns/rows for displaying the
- # completions. (Keep in mind that completions are displayed
- # alphabetically column-wise.)
- max_compl_width = min(term_width,
- max(get_cwidth(c.text) for c in completions) + 1)
- column_count = max(1, term_width // max_compl_width)
- completions_per_page = column_count * (term_height - 1)
- page_count = int(math.ceil(len(completions) / float(completions_per_page)))
- # Note: math.ceil can return float on Python2.
-
- def display(page):
- # Display completions.
- page_completions = completions[page * completions_per_page:
- (page+1) * completions_per_page]
-
- page_row_count = int(math.ceil(len(page_completions) / float(column_count)))
- page_columns = [page_completions[i * page_row_count:(i+1) * page_row_count]
- for i in range(column_count)]
-
- result = []
- for r in range(page_row_count):
- for c in range(column_count):
- try:
- result.append(page_columns[c][r].text.ljust(max_compl_width))
- except IndexError:
- pass
- result.append('\n')
- cli.output.write(''.join(result))
- cli.output.flush()
-
- # User interaction through an application generator function.
- def run():
- if len(completions) > completions_per_page:
- # Ask confirmation if it doesn't fit on the screen.
- message = 'Display all {} possibilities? (y on n) '.format(len(completions))
- confirm = yield create_confirm_application(message)
-
- if confirm:
- # Display pages.
- for page in range(page_count):
- display(page)
-
- if page != page_count - 1:
- # Display --MORE-- and go to the next page.
- show_more = yield _create_more_application()
- if not show_more:
- return
- else:
- cli.output.write('\n'); cli.output.flush()
- else:
- # Display all completions.
- display(0)
-
- cli.run_application_generator(run, render_cli_done=True)
-
-
-def _create_more_application():
- """
- Create an `Application` instance that displays the "--MORE--".
- """
- from prompt_toolkit.shortcuts import create_prompt_application
- registry = Registry()
-
- @registry.add_binding(' ')
- @registry.add_binding('y')
- @registry.add_binding('Y')
- @registry.add_binding(Keys.ControlJ)
- @registry.add_binding(Keys.ControlI) # Tab.
- def _(event):
- event.cli.set_return_value(True)
-
- @registry.add_binding('n')
- @registry.add_binding('N')
- @registry.add_binding('q')
- @registry.add_binding('Q')
- @registry.add_binding(Keys.ControlC)
- def _(event):
- event.cli.set_return_value(False)
-
- return create_prompt_application(
- '--MORE--', key_bindings_registry=registry, erase_when_done=True)
+"""
+Key binding handlers for displaying completions.
+"""
+from __future__ import unicode_literals
+from prompt_toolkit.completion import CompleteEvent, get_common_complete_suffix
+from prompt_toolkit.utils import get_cwidth
+from prompt_toolkit.keys import Keys
+from prompt_toolkit.key_binding.registry import Registry
+
+import math
+
+__all__ = (
+ 'generate_completions',
+ 'display_completions_like_readline',
+)
+
+def generate_completions(event):
+ r"""
+ Tab-completion: where the first tab completes the common suffix and the
+ second tab lists all the completions.
+ """
+ b = event.current_buffer
+
+ # When already navigating through completions, select the next one.
+ if b.complete_state:
+ b.complete_next()
+ else:
+ event.cli.start_completion(insert_common_part=True, select_first=False)
+
+
+def display_completions_like_readline(event):
+ """
+ Key binding handler for readline-style tab completion.
+ This is meant to be as similar as possible to the way how readline displays
+ completions.
+
+ Generate the completions immediately (blocking) and display them above the
+ prompt in columns.
+
+ Usage::
+
+ # Call this handler when 'Tab' has been pressed.
+ registry.add_binding(Keys.ControlI)(display_completions_like_readline)
+ """
+ # Request completions.
+ b = event.current_buffer
+ if b.completer is None:
+ return
+ complete_event = CompleteEvent(completion_requested=True)
+ completions = list(b.completer.get_completions(b.document, complete_event))
+
+ # Calculate the common suffix.
+ common_suffix = get_common_complete_suffix(b.document, completions)
+
+ # One completion: insert it.
+ if len(completions) == 1:
+ b.delete_before_cursor(-completions[0].start_position)
+ b.insert_text(completions[0].text)
+ # Multiple completions with common part.
+ elif common_suffix:
+ b.insert_text(common_suffix)
+ # Otherwise: display all completions.
+ elif completions:
+ _display_completions_like_readline(event.cli, completions)
+
+
+def _display_completions_like_readline(cli, completions):
+ """
+ Display the list of completions in columns above the prompt.
+ This will ask for a confirmation if there are too many completions to fit
+ on a single page and provide a paginator to walk through them.
+ """
+ from prompt_toolkit.shortcuts import create_confirm_application
+ assert isinstance(completions, list)
+
+ # Get terminal dimensions.
+ term_size = cli.output.get_size()
+ term_width = term_size.columns
+ term_height = term_size.rows
+
+ # Calculate amount of required columns/rows for displaying the
+ # completions. (Keep in mind that completions are displayed
+ # alphabetically column-wise.)
+ max_compl_width = min(term_width,
+ max(get_cwidth(c.text) for c in completions) + 1)
+ column_count = max(1, term_width // max_compl_width)
+ completions_per_page = column_count * (term_height - 1)
+ page_count = int(math.ceil(len(completions) / float(completions_per_page)))
+ # Note: math.ceil can return float on Python2.
+
+ def display(page):
+ # Display completions.
+ page_completions = completions[page * completions_per_page:
+ (page+1) * completions_per_page]
+
+ page_row_count = int(math.ceil(len(page_completions) / float(column_count)))
+ page_columns = [page_completions[i * page_row_count:(i+1) * page_row_count]
+ for i in range(column_count)]
+
+ result = []
+ for r in range(page_row_count):
+ for c in range(column_count):
+ try:
+ result.append(page_columns[c][r].text.ljust(max_compl_width))
+ except IndexError:
+ pass
+ result.append('\n')
+ cli.output.write(''.join(result))
+ cli.output.flush()
+
+ # User interaction through an application generator function.
+ def run():
+ if len(completions) > completions_per_page:
+ # Ask confirmation if it doesn't fit on the screen.
+ message = 'Display all {} possibilities? (y on n) '.format(len(completions))
+ confirm = yield create_confirm_application(message)
+
+ if confirm:
+ # Display pages.
+ for page in range(page_count):
+ display(page)
+
+ if page != page_count - 1:
+ # Display --MORE-- and go to the next page.
+ show_more = yield _create_more_application()
+ if not show_more:
+ return
+ else:
+ cli.output.write('\n'); cli.output.flush()
+ else:
+ # Display all completions.
+ display(0)
+
+ cli.run_application_generator(run, render_cli_done=True)
+
+
+def _create_more_application():
+ """
+ Create an `Application` instance that displays the "--MORE--".
+ """
+ from prompt_toolkit.shortcuts import create_prompt_application
+ registry = Registry()
+
+ @registry.add_binding(' ')
+ @registry.add_binding('y')
+ @registry.add_binding('Y')
+ @registry.add_binding(Keys.ControlJ)
+ @registry.add_binding(Keys.ControlI) # Tab.
+ def _(event):
+ event.cli.set_return_value(True)
+
+ @registry.add_binding('n')
+ @registry.add_binding('N')
+ @registry.add_binding('q')
+ @registry.add_binding('Q')
+ @registry.add_binding(Keys.ControlC)
+ def _(event):
+ event.cli.set_return_value(False)
+
+ return create_prompt_application(
+ '--MORE--', key_bindings_registry=registry, erase_when_done=True)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/emacs.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/emacs.py
index ff27532fec..bccdb04ff3 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/emacs.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/emacs.py
@@ -4,10 +4,10 @@ from prompt_toolkit.buffer import SelectionType, indent, unindent
from prompt_toolkit.keys import Keys
from prompt_toolkit.enums import IncrementalSearchDirection, SEARCH_BUFFER, SYSTEM_BUFFER
from prompt_toolkit.filters import Condition, EmacsMode, HasSelection, EmacsInsertMode, HasFocus, HasArg
-from prompt_toolkit.completion import CompleteEvent
+from prompt_toolkit.completion import CompleteEvent
from .scroll import scroll_page_up, scroll_page_down
-from .named_commands import get_by_name
+from .named_commands import get_by_name
from ..registry import Registry, ConditionalRegistry
__all__ = (
@@ -27,8 +27,8 @@ def load_emacs_bindings():
registry = ConditionalRegistry(Registry(), EmacsMode())
handle = registry.add_binding
- insert_mode = EmacsInsertMode()
- has_selection = HasSelection()
+ insert_mode = EmacsInsertMode()
+ has_selection = HasSelection()
@handle(Keys.Escape)
def _(event):
@@ -42,42 +42,42 @@ def load_emacs_bindings():
"""
pass
- handle(Keys.ControlA)(get_by_name('beginning-of-line'))
- handle(Keys.ControlB)(get_by_name('backward-char'))
- handle(Keys.ControlDelete, filter=insert_mode)(get_by_name('kill-word'))
- handle(Keys.ControlE)(get_by_name('end-of-line'))
- handle(Keys.ControlF)(get_by_name('forward-char'))
- handle(Keys.ControlLeft)(get_by_name('backward-word'))
- handle(Keys.ControlRight)(get_by_name('forward-word'))
- handle(Keys.ControlX, 'r', 'y', filter=insert_mode)(get_by_name('yank'))
- handle(Keys.ControlY, filter=insert_mode)(get_by_name('yank'))
- handle(Keys.Escape, 'b')(get_by_name('backward-word'))
- handle(Keys.Escape, 'c', filter=insert_mode)(get_by_name('capitalize-word'))
- handle(Keys.Escape, 'd', filter=insert_mode)(get_by_name('kill-word'))
- handle(Keys.Escape, 'f')(get_by_name('forward-word'))
- handle(Keys.Escape, 'l', filter=insert_mode)(get_by_name('downcase-word'))
- handle(Keys.Escape, 'u', filter=insert_mode)(get_by_name('uppercase-word'))
+ handle(Keys.ControlA)(get_by_name('beginning-of-line'))
+ handle(Keys.ControlB)(get_by_name('backward-char'))
+ handle(Keys.ControlDelete, filter=insert_mode)(get_by_name('kill-word'))
+ handle(Keys.ControlE)(get_by_name('end-of-line'))
+ handle(Keys.ControlF)(get_by_name('forward-char'))
+ handle(Keys.ControlLeft)(get_by_name('backward-word'))
+ handle(Keys.ControlRight)(get_by_name('forward-word'))
+ handle(Keys.ControlX, 'r', 'y', filter=insert_mode)(get_by_name('yank'))
+ handle(Keys.ControlY, filter=insert_mode)(get_by_name('yank'))
+ handle(Keys.Escape, 'b')(get_by_name('backward-word'))
+ handle(Keys.Escape, 'c', filter=insert_mode)(get_by_name('capitalize-word'))
+ handle(Keys.Escape, 'd', filter=insert_mode)(get_by_name('kill-word'))
+ handle(Keys.Escape, 'f')(get_by_name('forward-word'))
+ handle(Keys.Escape, 'l', filter=insert_mode)(get_by_name('downcase-word'))
+ handle(Keys.Escape, 'u', filter=insert_mode)(get_by_name('uppercase-word'))
handle(Keys.Escape, 'y', filter=insert_mode)(get_by_name('yank-pop'))
handle(Keys.Escape, Keys.ControlH, filter=insert_mode)(get_by_name('backward-kill-word'))
handle(Keys.Escape, Keys.Backspace, filter=insert_mode)(get_by_name('backward-kill-word'))
- handle(Keys.Escape, '\\', filter=insert_mode)(get_by_name('delete-horizontal-space'))
+ handle(Keys.Escape, '\\', filter=insert_mode)(get_by_name('delete-horizontal-space'))
- handle(Keys.ControlUnderscore, save_before=(lambda e: False), filter=insert_mode)(
- get_by_name('undo'))
+ handle(Keys.ControlUnderscore, save_before=(lambda e: False), filter=insert_mode)(
+ get_by_name('undo'))
- handle(Keys.ControlX, Keys.ControlU, save_before=(lambda e: False), filter=insert_mode)(
- get_by_name('undo'))
+ handle(Keys.ControlX, Keys.ControlU, save_before=(lambda e: False), filter=insert_mode)(
+ get_by_name('undo'))
- handle(Keys.Escape, '<', filter= ~has_selection)(get_by_name('beginning-of-history'))
- handle(Keys.Escape, '>', filter= ~has_selection)(get_by_name('end-of-history'))
-
- handle(Keys.Escape, '.', filter=insert_mode)(get_by_name('yank-last-arg'))
- handle(Keys.Escape, '_', filter=insert_mode)(get_by_name('yank-last-arg'))
- handle(Keys.Escape, Keys.ControlY, filter=insert_mode)(get_by_name('yank-nth-arg'))
+ handle(Keys.Escape, '<', filter= ~has_selection)(get_by_name('beginning-of-history'))
+ handle(Keys.Escape, '>', filter= ~has_selection)(get_by_name('end-of-history'))
+
+ handle(Keys.Escape, '.', filter=insert_mode)(get_by_name('yank-last-arg'))
+ handle(Keys.Escape, '_', filter=insert_mode)(get_by_name('yank-last-arg'))
+ handle(Keys.Escape, Keys.ControlY, filter=insert_mode)(get_by_name('yank-nth-arg'))
handle(Keys.Escape, '#', filter=insert_mode)(get_by_name('insert-comment'))
handle(Keys.ControlO)(get_by_name('operate-and-get-next'))
-
+
# ControlQ does a quoted insert. Not that for vt100 terminals, you have to
# disable flow control by running ``stty -ixon``, otherwise Ctrl-Q and
# Ctrl-S are captured by the terminal.
@@ -87,22 +87,22 @@ def load_emacs_bindings():
handle(Keys.ControlX, ')')(get_by_name('end-kbd-macro'))
handle(Keys.ControlX, 'e')(get_by_name('call-last-kbd-macro'))
- @handle(Keys.ControlN)
+ @handle(Keys.ControlN)
def _(event):
- " Next line. "
+ " Next line. "
event.current_buffer.auto_down()
- @handle(Keys.ControlP)
+ @handle(Keys.ControlP)
def _(event):
- " Previous line. "
+ " Previous line. "
event.current_buffer.auto_up(count=event.arg)
def handle_digit(c):
"""
- Handle input of arguments.
- The first number needs to be preceeded by escape.
+ Handle input of arguments.
+ The first number needs to be preceeded by escape.
"""
- @handle(c, filter=HasArg())
+ @handle(c, filter=HasArg())
@handle(Keys.Escape, c)
def _(event):
event.append_to_arg_count(c)
@@ -110,80 +110,80 @@ def load_emacs_bindings():
for c in '0123456789':
handle_digit(c)
- @handle(Keys.Escape, '-', filter=~HasArg())
+ @handle(Keys.Escape, '-', filter=~HasArg())
def _(event):
"""
"""
if event._arg is None:
event.append_to_arg_count('-')
- @handle('-', filter=Condition(lambda cli: cli.input_processor.arg == '-'))
+ @handle('-', filter=Condition(lambda cli: cli.input_processor.arg == '-'))
def _(event):
"""
- When '-' is typed again, after exactly '-' has been given as an
- argument, ignore this.
+ When '-' is typed again, after exactly '-' has been given as an
+ argument, ignore this.
"""
- event.cli.input_processor.arg = '-'
+ event.cli.input_processor.arg = '-'
- is_returnable = Condition(
- lambda cli: cli.current_buffer.accept_action.is_returnable)
+ is_returnable = Condition(
+ lambda cli: cli.current_buffer.accept_action.is_returnable)
- # Meta + Newline: always accept input.
- handle(Keys.Escape, Keys.ControlJ, filter=insert_mode & is_returnable)(
- get_by_name('accept-line'))
+ # Meta + Newline: always accept input.
+ handle(Keys.Escape, Keys.ControlJ, filter=insert_mode & is_returnable)(
+ get_by_name('accept-line'))
- def character_search(buff, char, count):
- if count < 0:
- match = buff.document.find_backwards(char, in_current_line=True, count=-count)
- else:
- match = buff.document.find(char, in_current_line=True, count=count)
+ def character_search(buff, char, count):
+ if count < 0:
+ match = buff.document.find_backwards(char, in_current_line=True, count=-count)
+ else:
+ match = buff.document.find(char, in_current_line=True, count=count)
- if match is not None:
- buff.cursor_position += match
+ if match is not None:
+ buff.cursor_position += match
- @handle(Keys.ControlSquareClose, Keys.Any)
+ @handle(Keys.ControlSquareClose, Keys.Any)
def _(event):
- " When Ctl-] + a character is pressed. go to that character. "
+ " When Ctl-] + a character is pressed. go to that character. "
# Also named 'character-search'
- character_search(event.current_buffer, event.data, event.arg)
+ character_search(event.current_buffer, event.data, event.arg)
- @handle(Keys.Escape, Keys.ControlSquareClose, Keys.Any)
+ @handle(Keys.Escape, Keys.ControlSquareClose, Keys.Any)
def _(event):
- " Like Ctl-], but backwards. "
+ " Like Ctl-], but backwards. "
# Also named 'character-search-backward'
- character_search(event.current_buffer, event.data, -event.arg)
+ character_search(event.current_buffer, event.data, -event.arg)
- @handle(Keys.Escape, 'a')
+ @handle(Keys.Escape, 'a')
def _(event):
- " Previous sentence. "
- # TODO:
+ " Previous sentence. "
+ # TODO:
- @handle(Keys.Escape, 'e')
+ @handle(Keys.Escape, 'e')
def _(event):
- " Move to end of sentence. "
+ " Move to end of sentence. "
# TODO:
- @handle(Keys.Escape, 't', filter=insert_mode)
+ @handle(Keys.Escape, 't', filter=insert_mode)
def _(event):
"""
Swap the last two words before the cursor.
"""
# TODO
- @handle(Keys.Escape, '*', filter=insert_mode)
+ @handle(Keys.Escape, '*', filter=insert_mode)
def _(event):
"""
- `meta-*`: Insert all possible completions of the preceding text.
+ `meta-*`: Insert all possible completions of the preceding text.
"""
- buff = event.current_buffer
+ buff = event.current_buffer
- # List all completions.
- complete_event = CompleteEvent(text_inserted=False, completion_requested=True)
- completions = list(buff.completer.get_completions(buff.document, complete_event))
+ # List all completions.
+ complete_event = CompleteEvent(text_inserted=False, completion_requested=True)
+ completions = list(buff.completer.get_completions(buff.document, complete_event))
- # Insert them.
- text_to_insert = ' '.join(c.text for c in completions)
- buff.insert_text(text_to_insert)
+ # Insert them.
+ text_to_insert = ' '.join(c.text for c in completions)
+ buff.insert_text(text_to_insert)
@handle(Keys.ControlX, Keys.ControlX)
def _(event):
@@ -193,7 +193,7 @@ def load_emacs_bindings():
"""
buffer = event.current_buffer
- if buffer.document.is_cursor_at_the_end_of_line:
+ if buffer.document.is_cursor_at_the_end_of_line:
buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=False)
else:
buffer.cursor_position += buffer.document.get_end_of_line_position()
@@ -201,12 +201,12 @@ def load_emacs_bindings():
@handle(Keys.ControlSpace)
def _(event):
"""
- Start of the selection (if the current buffer is not empty).
+ Start of the selection (if the current buffer is not empty).
"""
# Take the current cursor position as the start of this selection.
- buff = event.current_buffer
- if buff.text:
- buff.start_selection(selection_type=SelectionType.CHARACTERS)
+ buff = event.current_buffer
+ if buff.text:
+ buff.start_selection(selection_type=SelectionType.CHARACTERS)
@handle(Keys.ControlG, filter= ~has_selection)
def _(event):
@@ -257,7 +257,7 @@ def load_emacs_bindings():
buffer.cursor_position += buffer.document.find_next_word_beginning(count=event.arg) or \
buffer.document.get_end_of_document_position()
- @handle(Keys.Escape, '/', filter=insert_mode)
+ @handle(Keys.Escape, '/', filter=insert_mode)
def _(event):
"""
M-/: Complete.
@@ -316,7 +316,7 @@ def load_emacs_system_bindings():
registry = ConditionalRegistry(Registry(), EmacsMode())
handle = registry.add_binding
- has_focus = HasFocus(SYSTEM_BUFFER)
+ has_focus = HasFocus(SYSTEM_BUFFER)
@handle(Keys.Escape, '!', filter= ~has_focus)
def _(event):
@@ -354,8 +354,8 @@ def load_emacs_search_bindings(get_search_state=None):
registry = ConditionalRegistry(Registry(), EmacsMode())
handle = registry.add_binding
- has_focus = HasFocus(SEARCH_BUFFER)
-
+ has_focus = HasFocus(SEARCH_BUFFER)
+
assert get_search_state is None or callable(get_search_state)
if not get_search_state:
@@ -408,30 +408,30 @@ def load_emacs_search_bindings(get_search_state=None):
get_search_state(event.cli).direction = IncrementalSearchDirection.FORWARD
event.cli.push_focus(SEARCH_BUFFER)
- def incremental_search(cli, direction, count=1):
- " Apply search, but keep search buffer focussed. "
+ def incremental_search(cli, direction, count=1):
+ " Apply search, but keep search buffer focussed. "
# Update search_state.
- search_state = get_search_state(cli)
- direction_changed = search_state.direction != direction
+ search_state = get_search_state(cli)
+ direction_changed = search_state.direction != direction
- search_state.text = cli.buffers[SEARCH_BUFFER].text
- search_state.direction = direction
+ search_state.text = cli.buffers[SEARCH_BUFFER].text
+ search_state.direction = direction
# Apply search to current buffer.
if not direction_changed:
- input_buffer = cli.buffers.previous(cli)
+ input_buffer = cli.buffers.previous(cli)
input_buffer.apply_search(search_state,
- include_current_position=False, count=count)
+ include_current_position=False, count=count)
+
+ @handle(Keys.ControlR, filter=has_focus)
+ @handle(Keys.Up, filter=has_focus)
+ def _(event):
+ incremental_search(event.cli, IncrementalSearchDirection.BACKWARD, count=event.arg)
- @handle(Keys.ControlR, filter=has_focus)
- @handle(Keys.Up, filter=has_focus)
- def _(event):
- incremental_search(event.cli, IncrementalSearchDirection.BACKWARD, count=event.arg)
-
@handle(Keys.ControlS, filter=has_focus)
@handle(Keys.Down, filter=has_focus)
def _(event):
- incremental_search(event.cli, IncrementalSearchDirection.FORWARD, count=event.arg)
+ incremental_search(event.cli, IncrementalSearchDirection.FORWARD, count=event.arg)
return registry
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py
index 27c8eddc6b..f80c439fc6 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py
@@ -1,272 +1,272 @@
-"""
-Key bindings which are also known by GNU readline by the given names.
-
-See: http://www.delorie.com/gnu/docs/readline/rlman_13.html
-"""
-from __future__ import unicode_literals
-from prompt_toolkit.enums import IncrementalSearchDirection, SEARCH_BUFFER
+"""
+Key bindings which are also known by GNU readline by the given names.
+
+See: http://www.delorie.com/gnu/docs/readline/rlman_13.html
+"""
+from __future__ import unicode_literals
+from prompt_toolkit.enums import IncrementalSearchDirection, SEARCH_BUFFER
from prompt_toolkit.selection import PasteMode
-from six.moves import range
-import six
-
+from six.moves import range
+import six
+
from .completion import generate_completions, display_completions_like_readline
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.input_processor import KeyPress
from prompt_toolkit.keys import Keys
-
-__all__ = (
- 'get_by_name',
-)
-
-
-# Registry that maps the Readline command names to their handlers.
-_readline_commands = {}
-
-def register(name):
- """
- Store handler in the `_readline_commands` dictionary.
- """
- assert isinstance(name, six.text_type)
- def decorator(handler):
- assert callable(handler)
-
- _readline_commands[name] = handler
- return handler
- return decorator
-
-
-def get_by_name(name):
- """
- Return the handler for the (Readline) command with the given name.
- """
- try:
- return _readline_commands[name]
- except KeyError:
- raise KeyError('Unknown readline command: %r' % name)
-
-#
-# Commands for moving
-# See: http://www.delorie.com/gnu/docs/readline/rlman_14.html
-#
-
-@register('beginning-of-line')
-def beginning_of_line(event):
- " Move to the start of the current line. "
- buff = event.current_buffer
- buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False)
-
-
-@register('end-of-line')
-def end_of_line(event):
- " Move to the end of the line. "
- buff = event.current_buffer
- buff.cursor_position += buff.document.get_end_of_line_position()
-
-
-@register('forward-char')
-def forward_char(event):
- " Move forward a character. "
- buff = event.current_buffer
- buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg)
-
-
-@register('backward-char')
-def backward_char(event):
- " Move back a character. "
- buff = event.current_buffer
- buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg)
-
-
-@register('forward-word')
-def forward_word(event):
- """
- Move forward to the end of the next word. Words are composed of letters and
- digits.
- """
- buff = event.current_buffer
- pos = buff.document.find_next_word_ending(count=event.arg)
-
- if pos:
- buff.cursor_position += pos
-
-
-@register('backward-word')
-def backward_word(event):
- """
- Move back to the start of the current or previous word. Words are composed
- of letters and digits.
- """
- buff = event.current_buffer
- pos = buff.document.find_previous_word_beginning(count=event.arg)
-
- if pos:
- buff.cursor_position += pos
-
-
-@register('clear-screen')
-def clear_screen(event):
- """
- Clear the screen and redraw everything at the top of the screen.
- """
- event.cli.renderer.clear()
-
-
-@register('redraw-current-line')
-def redraw_current_line(event):
- """
- Refresh the current line.
- (Readline defines this command, but prompt-toolkit doesn't have it.)
- """
- pass
-
-#
-# Commands for manipulating the history.
-# See: http://www.delorie.com/gnu/docs/readline/rlman_15.html
-#
-
-@register('accept-line')
-def accept_line(event):
- " Accept the line regardless of where the cursor is. "
- b = event.current_buffer
- b.accept_action.validate_and_handle(event.cli, b)
-
-
-@register('previous-history')
-def previous_history(event):
+
+__all__ = (
+ 'get_by_name',
+)
+
+
+# Registry that maps the Readline command names to their handlers.
+_readline_commands = {}
+
+def register(name):
+ """
+ Store handler in the `_readline_commands` dictionary.
+ """
+ assert isinstance(name, six.text_type)
+ def decorator(handler):
+ assert callable(handler)
+
+ _readline_commands[name] = handler
+ return handler
+ return decorator
+
+
+def get_by_name(name):
+ """
+ Return the handler for the (Readline) command with the given name.
+ """
+ try:
+ return _readline_commands[name]
+ except KeyError:
+ raise KeyError('Unknown readline command: %r' % name)
+
+#
+# Commands for moving
+# See: http://www.delorie.com/gnu/docs/readline/rlman_14.html
+#
+
+@register('beginning-of-line')
+def beginning_of_line(event):
+ " Move to the start of the current line. "
+ buff = event.current_buffer
+ buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False)
+
+
+@register('end-of-line')
+def end_of_line(event):
+ " Move to the end of the line. "
+ buff = event.current_buffer
+ buff.cursor_position += buff.document.get_end_of_line_position()
+
+
+@register('forward-char')
+def forward_char(event):
+ " Move forward a character. "
+ buff = event.current_buffer
+ buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg)
+
+
+@register('backward-char')
+def backward_char(event):
+ " Move back a character. "
+ buff = event.current_buffer
+ buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg)
+
+
+@register('forward-word')
+def forward_word(event):
+ """
+ Move forward to the end of the next word. Words are composed of letters and
+ digits.
+ """
+ buff = event.current_buffer
+ pos = buff.document.find_next_word_ending(count=event.arg)
+
+ if pos:
+ buff.cursor_position += pos
+
+
+@register('backward-word')
+def backward_word(event):
+ """
+ Move back to the start of the current or previous word. Words are composed
+ of letters and digits.
+ """
+ buff = event.current_buffer
+ pos = buff.document.find_previous_word_beginning(count=event.arg)
+
+ if pos:
+ buff.cursor_position += pos
+
+
+@register('clear-screen')
+def clear_screen(event):
+ """
+ Clear the screen and redraw everything at the top of the screen.
+ """
+ event.cli.renderer.clear()
+
+
+@register('redraw-current-line')
+def redraw_current_line(event):
+ """
+ Refresh the current line.
+ (Readline defines this command, but prompt-toolkit doesn't have it.)
+ """
+ pass
+
+#
+# Commands for manipulating the history.
+# See: http://www.delorie.com/gnu/docs/readline/rlman_15.html
+#
+
+@register('accept-line')
+def accept_line(event):
+ " Accept the line regardless of where the cursor is. "
+ b = event.current_buffer
+ b.accept_action.validate_and_handle(event.cli, b)
+
+
+@register('previous-history')
+def previous_history(event):
" Move `back` through the history list, fetching the previous command. "
- event.current_buffer.history_backward(count=event.arg)
-
-
-@register('next-history')
-def next_history(event):
+ event.current_buffer.history_backward(count=event.arg)
+
+
+@register('next-history')
+def next_history(event):
" Move `forward` through the history list, fetching the next command. "
- event.current_buffer.history_forward(count=event.arg)
-
-
-@register('beginning-of-history')
-def beginning_of_history(event):
- " Move to the first line in the history. "
- event.current_buffer.go_to_history(0)
-
-
-@register('end-of-history')
-def end_of_history(event):
- """
- Move to the end of the input history, i.e., the line currently being entered.
- """
- event.current_buffer.history_forward(count=10**100)
- buff = event.current_buffer
- buff.go_to_history(len(buff._working_lines) - 1)
-
-
-@register('reverse-search-history')
-def reverse_search_history(event):
- """
+ event.current_buffer.history_forward(count=event.arg)
+
+
+@register('beginning-of-history')
+def beginning_of_history(event):
+ " Move to the first line in the history. "
+ event.current_buffer.go_to_history(0)
+
+
+@register('end-of-history')
+def end_of_history(event):
+ """
+ Move to the end of the input history, i.e., the line currently being entered.
+ """
+ event.current_buffer.history_forward(count=10**100)
+ buff = event.current_buffer
+ buff.go_to_history(len(buff._working_lines) - 1)
+
+
+@register('reverse-search-history')
+def reverse_search_history(event):
+ """
Search backward starting at the current line and moving `up` through
- the history as necessary. This is an incremental search.
- """
- event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD
- event.cli.push_focus(SEARCH_BUFFER)
-
-
-#
-# Commands for changing text
-#
-
-@register('end-of-file')
-def end_of_file(event):
- """
- Exit.
- """
- event.cli.exit()
-
-
-@register('delete-char')
-def delete_char(event):
- " Delete character before the cursor. "
- deleted = event.current_buffer.delete(count=event.arg)
- if not deleted:
- event.cli.output.bell()
-
-
-@register('backward-delete-char')
-def backward_delete_char(event):
- " Delete the character behind the cursor. "
- if event.arg < 0:
- # When a negative argument has been given, this should delete in front
- # of the cursor.
- deleted = event.current_buffer.delete(count=-event.arg)
- else:
- deleted = event.current_buffer.delete_before_cursor(count=event.arg)
-
- if not deleted:
- event.cli.output.bell()
-
-
-@register('self-insert')
-def self_insert(event):
- " Insert yourself. "
- event.current_buffer.insert_text(event.data * event.arg)
-
-
-@register('transpose-chars')
-def transpose_chars(event):
- """
- Emulate Emacs transpose-char behavior: at the beginning of the buffer,
- do nothing. At the end of a line or buffer, swap the characters before
- the cursor. Otherwise, move the cursor right, and then swap the
- characters before the cursor.
- """
- b = event.current_buffer
- p = b.cursor_position
- if p == 0:
- return
- elif p == len(b.text) or b.text[p] == '\n':
- b.swap_characters_before_cursor()
- else:
- b.cursor_position += b.document.get_cursor_right_position()
- b.swap_characters_before_cursor()
-
-
-@register('uppercase-word')
-def uppercase_word(event):
- """
- Uppercase the current (or following) word.
- """
- buff = event.current_buffer
-
- for i in range(event.arg):
- pos = buff.document.find_next_word_ending()
- words = buff.document.text_after_cursor[:pos]
- buff.insert_text(words.upper(), overwrite=True)
-
-
-@register('downcase-word')
-def downcase_word(event):
- """
- Lowercase the current (or following) word.
- """
- buff = event.current_buffer
-
- for i in range(event.arg): # XXX: not DRY: see meta_c and meta_u!!
- pos = buff.document.find_next_word_ending()
- words = buff.document.text_after_cursor[:pos]
- buff.insert_text(words.lower(), overwrite=True)
-
-
-@register('capitalize-word')
-def capitalize_word(event):
- """
- Capitalize the current (or following) word.
- """
- buff = event.current_buffer
-
- for i in range(event.arg):
- pos = buff.document.find_next_word_ending()
- words = buff.document.text_after_cursor[:pos]
- buff.insert_text(words.title(), overwrite=True)
-
+ the history as necessary. This is an incremental search.
+ """
+ event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD
+ event.cli.push_focus(SEARCH_BUFFER)
+
+
+#
+# Commands for changing text
+#
+
+@register('end-of-file')
+def end_of_file(event):
+ """
+ Exit.
+ """
+ event.cli.exit()
+
+
+@register('delete-char')
+def delete_char(event):
+ " Delete character before the cursor. "
+ deleted = event.current_buffer.delete(count=event.arg)
+ if not deleted:
+ event.cli.output.bell()
+
+
+@register('backward-delete-char')
+def backward_delete_char(event):
+ " Delete the character behind the cursor. "
+ if event.arg < 0:
+ # When a negative argument has been given, this should delete in front
+ # of the cursor.
+ deleted = event.current_buffer.delete(count=-event.arg)
+ else:
+ deleted = event.current_buffer.delete_before_cursor(count=event.arg)
+
+ if not deleted:
+ event.cli.output.bell()
+
+
+@register('self-insert')
+def self_insert(event):
+ " Insert yourself. "
+ event.current_buffer.insert_text(event.data * event.arg)
+
+
+@register('transpose-chars')
+def transpose_chars(event):
+ """
+ Emulate Emacs transpose-char behavior: at the beginning of the buffer,
+ do nothing. At the end of a line or buffer, swap the characters before
+ the cursor. Otherwise, move the cursor right, and then swap the
+ characters before the cursor.
+ """
+ b = event.current_buffer
+ p = b.cursor_position
+ if p == 0:
+ return
+ elif p == len(b.text) or b.text[p] == '\n':
+ b.swap_characters_before_cursor()
+ else:
+ b.cursor_position += b.document.get_cursor_right_position()
+ b.swap_characters_before_cursor()
+
+
+@register('uppercase-word')
+def uppercase_word(event):
+ """
+ Uppercase the current (or following) word.
+ """
+ buff = event.current_buffer
+
+ for i in range(event.arg):
+ pos = buff.document.find_next_word_ending()
+ words = buff.document.text_after_cursor[:pos]
+ buff.insert_text(words.upper(), overwrite=True)
+
+
+@register('downcase-word')
+def downcase_word(event):
+ """
+ Lowercase the current (or following) word.
+ """
+ buff = event.current_buffer
+
+ for i in range(event.arg): # XXX: not DRY: see meta_c and meta_u!!
+ pos = buff.document.find_next_word_ending()
+ words = buff.document.text_after_cursor[:pos]
+ buff.insert_text(words.lower(), overwrite=True)
+
+
+@register('capitalize-word')
+def capitalize_word(event):
+ """
+ Capitalize the current (or following) word.
+ """
+ buff = event.current_buffer
+
+ for i in range(event.arg):
+ pos = buff.document.find_next_word_ending()
+ words = buff.document.text_after_cursor[:pos]
+ buff.insert_text(words.title(), overwrite=True)
+
@register('quoted-insert')
def quoted_insert(event):
@@ -277,73 +277,73 @@ def quoted_insert(event):
event.cli.quoted_insert = True
-#
-# Killing and yanking.
-#
-
-@register('kill-line')
-def kill_line(event):
- """
- Kill the text from the cursor to the end of the line.
-
- If we are at the end of the line, this should remove the newline.
- (That way, it is possible to delete multiple lines by executing this
- command multiple times.)
- """
- buff = event.current_buffer
- if event.arg < 0:
- deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
- else:
- if buff.document.current_char == '\n':
- deleted = buff.delete(1)
- else:
- deleted = buff.delete(count=buff.document.get_end_of_line_position())
- event.cli.clipboard.set_text(deleted)
-
-
-@register('kill-word')
-def kill_word(event):
- """
- Kill from point to the end of the current word, or if between words, to the
- end of the next word. Word boundaries are the same as forward-word.
- """
- buff = event.current_buffer
- pos = buff.document.find_next_word_ending(count=event.arg)
-
- if pos:
- deleted = buff.delete(count=pos)
- event.cli.clipboard.set_text(deleted)
-
-
-@register('unix-word-rubout')
+#
+# Killing and yanking.
+#
+
+@register('kill-line')
+def kill_line(event):
+ """
+ Kill the text from the cursor to the end of the line.
+
+ If we are at the end of the line, this should remove the newline.
+ (That way, it is possible to delete multiple lines by executing this
+ command multiple times.)
+ """
+ buff = event.current_buffer
+ if event.arg < 0:
+ deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
+ else:
+ if buff.document.current_char == '\n':
+ deleted = buff.delete(1)
+ else:
+ deleted = buff.delete(count=buff.document.get_end_of_line_position())
+ event.cli.clipboard.set_text(deleted)
+
+
+@register('kill-word')
+def kill_word(event):
+ """
+ Kill from point to the end of the current word, or if between words, to the
+ end of the next word. Word boundaries are the same as forward-word.
+ """
+ buff = event.current_buffer
+ pos = buff.document.find_next_word_ending(count=event.arg)
+
+ if pos:
+ deleted = buff.delete(count=pos)
+ event.cli.clipboard.set_text(deleted)
+
+
+@register('unix-word-rubout')
def unix_word_rubout(event, WORD=True):
- """
+ """
Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW.
- """
- buff = event.current_buffer
+ """
+ buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
-
- if pos is None:
- # Nothing found? delete until the start of the document. (The
- # input starts with whitespace and no words were found before the
- # cursor.)
- pos = - buff.cursor_position
-
- if pos:
- deleted = buff.delete_before_cursor(count=-pos)
-
- # If the previous key press was also Control-W, concatenate deleted
- # text.
- if event.is_repeat:
- deleted += event.cli.clipboard.get_data().text
-
- event.cli.clipboard.set_text(deleted)
- else:
- # Nothing to delete. Bell.
- event.cli.output.bell()
-
-
+
+ if pos is None:
+ # Nothing found? delete until the start of the document. (The
+ # input starts with whitespace and no words were found before the
+ # cursor.)
+ pos = - buff.cursor_position
+
+ if pos:
+ deleted = buff.delete_before_cursor(count=-pos)
+
+ # If the previous key press was also Control-W, concatenate deleted
+ # text.
+ if event.is_repeat:
+ deleted += event.cli.clipboard.get_data().text
+
+ event.cli.clipboard.set_text(deleted)
+ else:
+ # Nothing to delete. Bell.
+ event.cli.output.bell()
+
+
@register('backward-kill-word')
def backward_kill_word(event):
"""
@@ -353,61 +353,61 @@ def backward_kill_word(event):
unix_word_rubout(event, WORD=False)
-@register('delete-horizontal-space')
-def delete_horizontal_space(event):
- " Delete all spaces and tabs around point. "
- buff = event.current_buffer
- text_before_cursor = buff.document.text_before_cursor
- text_after_cursor = buff.document.text_after_cursor
-
- delete_before = len(text_before_cursor) - len(text_before_cursor.rstrip('\t '))
- delete_after = len(text_after_cursor) - len(text_after_cursor.lstrip('\t '))
-
- buff.delete_before_cursor(count=delete_before)
- buff.delete(count=delete_after)
-
-
-@register('unix-line-discard')
-def unix_line_discard(event):
- """
- Kill backward from the cursor to the beginning of the current line.
- """
- buff = event.current_buffer
-
- if buff.document.cursor_position_col == 0 and buff.document.cursor_position > 0:
- buff.delete_before_cursor(count=1)
- else:
- deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
- event.cli.clipboard.set_text(deleted)
-
-
-@register('yank')
-def yank(event):
- """
- Paste before cursor.
- """
- event.current_buffer.paste_clipboard_data(
+@register('delete-horizontal-space')
+def delete_horizontal_space(event):
+ " Delete all spaces and tabs around point. "
+ buff = event.current_buffer
+ text_before_cursor = buff.document.text_before_cursor
+ text_after_cursor = buff.document.text_after_cursor
+
+ delete_before = len(text_before_cursor) - len(text_before_cursor.rstrip('\t '))
+ delete_after = len(text_after_cursor) - len(text_after_cursor.lstrip('\t '))
+
+ buff.delete_before_cursor(count=delete_before)
+ buff.delete(count=delete_after)
+
+
+@register('unix-line-discard')
+def unix_line_discard(event):
+ """
+ Kill backward from the cursor to the beginning of the current line.
+ """
+ buff = event.current_buffer
+
+ if buff.document.cursor_position_col == 0 and buff.document.cursor_position > 0:
+ buff.delete_before_cursor(count=1)
+ else:
+ deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
+ event.cli.clipboard.set_text(deleted)
+
+
+@register('yank')
+def yank(event):
+ """
+ Paste before cursor.
+ """
+ event.current_buffer.paste_clipboard_data(
event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
-
-@register('yank-nth-arg')
-def yank_nth_arg(event):
- """
- Insert the first argument of the previous command. With an argument, insert
- the nth word from the previous command (start counting at 0).
- """
- n = (event.arg if event.arg_present else None)
- event.current_buffer.yank_nth_arg(n)
-
-
-@register('yank-last-arg')
-def yank_last_arg(event):
- """
- Like `yank_nth_arg`, but if no argument has been given, yank the last word
- of each line.
- """
- n = (event.arg if event.arg_present else None)
- event.current_buffer.yank_last_arg(n)
-
+
+@register('yank-nth-arg')
+def yank_nth_arg(event):
+ """
+ Insert the first argument of the previous command. With an argument, insert
+ the nth word from the previous command (start counting at 0).
+ """
+ n = (event.arg if event.arg_present else None)
+ event.current_buffer.yank_nth_arg(n)
+
+
+@register('yank-last-arg')
+def yank_last_arg(event):
+ """
+ Like `yank_nth_arg`, but if no argument has been given, yank the last word
+ of each line.
+ """
+ n = (event.arg if event.arg_present else None)
+ event.current_buffer.yank_last_arg(n)
+
@register('yank-pop')
def yank_pop(event):
"""
@@ -424,12 +424,12 @@ def yank_pop(event):
buff.paste_clipboard_data(
clipboard.get_data(), paste_mode=PasteMode.EMACS)
-#
-# Completion.
-#
-
-@register('complete')
-def complete(event):
+#
+# Completion.
+#
+
+@register('complete')
+def complete(event):
" Attempt to perform completion. "
display_completions_like_readline(event)
@@ -440,15 +440,15 @@ def menu_complete(event):
Generate completions, or go to the next completion. (This is the default
way of completing input in prompt_toolkit.)
"""
- generate_completions(event)
-
-
+ generate_completions(event)
+
+
@register('menu-complete-backward')
def menu_complete_backward(event):
" Move backward through the list of possible completions. "
event.current_buffer.complete_previous()
-#
+#
# Keyboard macros.
#
@@ -488,13 +488,13 @@ def print_last_kbd_macro(event):
event.cli.run_in_terminal(print_macro)
#
-# Miscellaneous Commands.
-#
-
-@register('undo')
-def undo(event):
- " Incremental undo. "
- event.current_buffer.undo()
+# Miscellaneous Commands.
+#
+
+@register('undo')
+def undo(event):
+ " Incremental undo. "
+ event.current_buffer.undo()
@register('insert-comment')
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/scroll.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/scroll.py
index 91750b3c31..2cc58129ff 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/scroll.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/scroll.py
@@ -8,7 +8,7 @@ Vi, Emacs, etc...
from __future__ import unicode_literals
from prompt_toolkit.layout.utils import find_window_for_buffer_name
-from six.moves import range
+from six.moves import range
__all__ = (
'scroll_forward',
@@ -35,29 +35,29 @@ def scroll_forward(event, half=False):
b = event.cli.current_buffer
if w and w.render_info:
- info = w.render_info
- ui_content = info.ui_content
-
- # Height to scroll.
- scroll_height = info.window_height
+ info = w.render_info
+ ui_content = info.ui_content
+
+ # Height to scroll.
+ scroll_height = info.window_height
if half:
- scroll_height //= 2
-
- # Calculate how many lines is equivalent to that vertical space.
- y = b.document.cursor_position_row + 1
- height = 0
- while y < ui_content.line_count:
- line_height = info.get_height_for_line(y)
-
- if height + line_height < scroll_height:
- height += line_height
- y += 1
- else:
- break
-
- b.cursor_position = b.document.translate_row_col_to_index(y, 0)
-
-
+ scroll_height //= 2
+
+ # Calculate how many lines is equivalent to that vertical space.
+ y = b.document.cursor_position_row + 1
+ height = 0
+ while y < ui_content.line_count:
+ line_height = info.get_height_for_line(y)
+
+ if height + line_height < scroll_height:
+ height += line_height
+ y += 1
+ else:
+ break
+
+ b.cursor_position = b.document.translate_row_col_to_index(y, 0)
+
+
def scroll_backward(event, half=False):
"""
Scroll window up.
@@ -66,28 +66,28 @@ def scroll_backward(event, half=False):
b = event.cli.current_buffer
if w and w.render_info:
- info = w.render_info
-
- # Height to scroll.
- scroll_height = info.window_height
+ info = w.render_info
+
+ # Height to scroll.
+ scroll_height = info.window_height
if half:
- scroll_height //= 2
-
- # Calculate how many lines is equivalent to that vertical space.
- y = max(0, b.document.cursor_position_row - 1)
- height = 0
- while y > 0:
- line_height = info.get_height_for_line(y)
-
- if height + line_height < scroll_height:
- height += line_height
- y -= 1
- else:
- break
-
- b.cursor_position = b.document.translate_row_col_to_index(y, 0)
-
-
+ scroll_height //= 2
+
+ # Calculate how many lines is equivalent to that vertical space.
+ y = max(0, b.document.cursor_position_row - 1)
+ height = 0
+ while y > 0:
+ line_height = info.get_height_for_line(y)
+
+ if height + line_height < scroll_height:
+ height += line_height
+ y -= 1
+ else:
+ break
+
+ b.cursor_position = b.document.translate_row_col_to_index(y, 0)
+
+
def scroll_half_page_down(event):
"""
Same as ControlF, but only scroll half a page.
@@ -134,14 +134,14 @@ def scroll_one_line_up(event):
info = w.render_info
if w.vertical_scroll > 0:
- first_line_height = info.get_height_for_line(info.first_visible_line())
-
- cursor_up = info.cursor_position.y - (info.window_height - 1 - first_line_height -
- info.configured_scroll_offsets.bottom)
-
- # Move cursor up, as many steps as the height of the first line.
- # TODO: not entirely correct yet, in case of line wrapping and many long lines.
- for _ in range(max(0, cursor_up)):
+ first_line_height = info.get_height_for_line(info.first_visible_line())
+
+ cursor_up = info.cursor_position.y - (info.window_height - 1 - first_line_height -
+ info.configured_scroll_offsets.bottom)
+
+ # Move cursor up, as many steps as the height of the first line.
+ # TODO: not entirely correct yet, in case of line wrapping and many long lines.
+ for _ in range(max(0, cursor_up)):
b.cursor_position += b.document.get_cursor_up_position()
# Scroll window
@@ -157,10 +157,10 @@ def scroll_page_down(event):
if w and w.render_info:
# Scroll down one page.
- line_index = max(w.render_info.last_visible_line(), w.vertical_scroll + 1)
- w.vertical_scroll = line_index
+ line_index = max(w.render_info.last_visible_line(), w.vertical_scroll + 1)
+ w.vertical_scroll = line_index
- b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
+ b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
b.cursor_position += b.document.get_start_of_line_position(after_whitespace=True)
@@ -172,14 +172,14 @@ def scroll_page_up(event):
b = event.cli.current_buffer
if w and w.render_info:
- # Put cursor at the first visible line. (But make sure that the cursor
- # moves at least one line up.)
- line_index = max(0, min(w.render_info.first_visible_line(),
- b.document.cursor_position_row - 1))
+ # Put cursor at the first visible line. (But make sure that the cursor
+ # moves at least one line up.)
+ line_index = max(0, min(w.render_info.first_visible_line(),
+ b.document.cursor_position_row - 1))
- b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
- b.cursor_position += b.document.get_start_of_line_position(after_whitespace=True)
+ b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
+ b.cursor_position += b.document.get_start_of_line_position(after_whitespace=True)
- # Set the scroll offset. We can safely set it to zero; the Window will
- # make sure that it scrolls at least until the cursor becomes visible.
- w.vertical_scroll = 0
+ # Set the scroll offset. We can safely set it to zero; the Window will
+ # make sure that it scrolls at least until the cursor becomes visible.
+ w.vertical_scroll = 0
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/utils.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/utils.py
index b3fa299d7c..caf08c5c1b 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/utils.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/utils.py
@@ -7,10 +7,10 @@ __all__ = (
def create_handle_decorator(registry, filter=Always()):
"""
- Create a key handle decorator, which is compatible with `Registry.handle`,
- but will chain the given filter to every key binding.
+ Create a key handle decorator, which is compatible with `Registry.handle`,
+ but will chain the given filter to every key binding.
- :param filter: `CLIFilter`
+ :param filter: `CLIFilter`
"""
assert isinstance(filter, CLIFilter)
@@ -21,5 +21,5 @@ def create_handle_decorator(registry, filter=Always()):
else:
kw['filter'] = filter
- return registry.add_binding(*keys, **kw)
+ return registry.add_binding(*keys, **kw)
return handle
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py
index 4615329eec..72568ee273 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py
@@ -1,11 +1,11 @@
# pylint: disable=function-redefined
from __future__ import unicode_literals
-from prompt_toolkit.buffer import ClipboardData, indent, unindent, reshape_text
+from prompt_toolkit.buffer import ClipboardData, indent, unindent, reshape_text
from prompt_toolkit.document import Document
from prompt_toolkit.enums import IncrementalSearchDirection, SEARCH_BUFFER, SYSTEM_BUFFER
from prompt_toolkit.filters import Filter, Condition, HasArg, Always, IsReadOnly
-from prompt_toolkit.filters.cli import ViNavigationMode, ViInsertMode, ViInsertMultipleMode, ViReplaceMode, ViSelectionMode, ViWaitingForTextObjectMode, ViDigraphMode, ViMode
-from prompt_toolkit.key_binding.digraphs import DIGRAPHS
+from prompt_toolkit.filters.cli import ViNavigationMode, ViInsertMode, ViInsertMultipleMode, ViReplaceMode, ViSelectionMode, ViWaitingForTextObjectMode, ViDigraphMode, ViMode
+from prompt_toolkit.key_binding.digraphs import DIGRAPHS
from prompt_toolkit.key_binding.vi_state import CharacterFind, InputMode
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.utils import find_window_for_buffer_name
@@ -16,21 +16,21 @@ from .named_commands import get_by_name
from ..registry import Registry, ConditionalRegistry, BaseRegistry
import prompt_toolkit.filters as filters
-from six.moves import range
+from six.moves import range
import codecs
-import six
-import string
-
-try:
- from itertools import accumulate
-except ImportError: # < Python 3.2
- def accumulate(iterable):
- " Super simpel 'accumulate' implementation. "
- total = 0
- for item in iterable:
- total += item
- yield total
-
+import six
+import string
+
+try:
+ from itertools import accumulate
+except ImportError: # < Python 3.2
+ def accumulate(iterable):
+ " Super simpel 'accumulate' implementation. "
+ total = 0
+ for item in iterable:
+ total += item
+ yield total
+
__all__ = (
'load_vi_bindings',
'load_vi_search_bindings',
@@ -38,40 +38,40 @@ __all__ = (
'load_extra_vi_page_navigation_bindings',
)
-if six.PY2:
- ascii_lowercase = string.ascii_lowercase.decode('ascii')
-else:
- ascii_lowercase = string.ascii_lowercase
+if six.PY2:
+ ascii_lowercase = string.ascii_lowercase.decode('ascii')
+else:
+ ascii_lowercase = string.ascii_lowercase
-vi_register_names = ascii_lowercase + '0123456789'
+vi_register_names = ascii_lowercase + '0123456789'
-class TextObjectType(object):
- EXCLUSIVE = 'EXCLUSIVE'
- INCLUSIVE = 'INCLUSIVE'
- LINEWISE = 'LINEWISE'
- BLOCK = 'BLOCK'
+class TextObjectType(object):
+ EXCLUSIVE = 'EXCLUSIVE'
+ INCLUSIVE = 'INCLUSIVE'
+ LINEWISE = 'LINEWISE'
+ BLOCK = 'BLOCK'
-class TextObject(object):
+class TextObject(object):
"""
- Return struct for functions wrapped in ``text_object``.
+ Return struct for functions wrapped in ``text_object``.
Both `start` and `end` are relative to the current cursor position.
"""
- def __init__(self, start, end=0, type=TextObjectType.EXCLUSIVE):
+ def __init__(self, start, end=0, type=TextObjectType.EXCLUSIVE):
self.start = start
self.end = end
- self.type = type
-
- @property
- def selection_type(self):
- if self.type == TextObjectType.LINEWISE:
- return SelectionType.LINES
- if self.type == TextObjectType.BLOCK:
- return SelectionType.BLOCK
- else:
- return SelectionType.CHARACTERS
-
+ self.type = type
+
+ @property
+ def selection_type(self):
+ if self.type == TextObjectType.LINEWISE:
+ return SelectionType.LINES
+ if self.type == TextObjectType.BLOCK:
+ return SelectionType.BLOCK
+ else:
+ return SelectionType.CHARACTERS
+
def sorted(self):
"""
Return a (start, end) tuple where start <= end.
@@ -81,62 +81,62 @@ class TextObject(object):
else:
return self.end, self.start
- def operator_range(self, document):
- """
- Return a (start, end) tuple with start <= end that indicates the range
- operators should operate on.
- `buffer` is used to get start and end of line positions.
- """
- start, end = self.sorted()
- doc = document
-
- if (self.type == TextObjectType.EXCLUSIVE and
- doc.translate_index_to_position(end + doc.cursor_position)[1] == 0):
- # If the motion is exclusive and the end of motion is on the first
- # column, the end position becomes end of previous line.
- end -= 1
- if self.type == TextObjectType.INCLUSIVE:
- end += 1
- if self.type == TextObjectType.LINEWISE:
- # Select whole lines
- row, col = doc.translate_index_to_position(start + doc.cursor_position)
- start = doc.translate_row_col_to_index(row, 0) - doc.cursor_position
- row, col = doc.translate_index_to_position(end + doc.cursor_position)
- end = doc.translate_row_col_to_index(row, len(doc.lines[row])) - doc.cursor_position
- return start, end
-
- def get_line_numbers(self, buffer):
- """
- Return a (start_line, end_line) pair.
- """
- # Get absolute cursor positions from the text object.
- from_, to = self.operator_range(buffer.document)
- from_ += buffer.cursor_position
- to += buffer.cursor_position
-
- # Take the start of the lines.
- from_, _ = buffer.document.translate_index_to_position(from_)
- to, _ = buffer.document.translate_index_to_position(to)
-
- return from_, to
-
- def cut(self, buffer):
- """
- Turn text object into `ClipboardData` instance.
- """
- from_, to = self.operator_range(buffer.document)
-
- from_ += buffer.cursor_position
- to += buffer.cursor_position
- to -= 1 # SelectionState does not include the end position, `operator_range` does.
-
- document = Document(buffer.text, to, SelectionState(
- original_cursor_position=from_, type=self.selection_type))
-
- new_document, clipboard_data = document.cut_selection()
- return new_document, clipboard_data
-
-
+ def operator_range(self, document):
+ """
+ Return a (start, end) tuple with start <= end that indicates the range
+ operators should operate on.
+ `buffer` is used to get start and end of line positions.
+ """
+ start, end = self.sorted()
+ doc = document
+
+ if (self.type == TextObjectType.EXCLUSIVE and
+ doc.translate_index_to_position(end + doc.cursor_position)[1] == 0):
+ # If the motion is exclusive and the end of motion is on the first
+ # column, the end position becomes end of previous line.
+ end -= 1
+ if self.type == TextObjectType.INCLUSIVE:
+ end += 1
+ if self.type == TextObjectType.LINEWISE:
+ # Select whole lines
+ row, col = doc.translate_index_to_position(start + doc.cursor_position)
+ start = doc.translate_row_col_to_index(row, 0) - doc.cursor_position
+ row, col = doc.translate_index_to_position(end + doc.cursor_position)
+ end = doc.translate_row_col_to_index(row, len(doc.lines[row])) - doc.cursor_position
+ return start, end
+
+ def get_line_numbers(self, buffer):
+ """
+ Return a (start_line, end_line) pair.
+ """
+ # Get absolute cursor positions from the text object.
+ from_, to = self.operator_range(buffer.document)
+ from_ += buffer.cursor_position
+ to += buffer.cursor_position
+
+ # Take the start of the lines.
+ from_, _ = buffer.document.translate_index_to_position(from_)
+ to, _ = buffer.document.translate_index_to_position(to)
+
+ return from_, to
+
+ def cut(self, buffer):
+ """
+ Turn text object into `ClipboardData` instance.
+ """
+ from_, to = self.operator_range(buffer.document)
+
+ from_ += buffer.cursor_position
+ to += buffer.cursor_position
+ to -= 1 # SelectionState does not include the end position, `operator_range` does.
+
+ document = Document(buffer.text, to, SelectionState(
+ original_cursor_position=from_, type=self.selection_type))
+
+ new_document, clipboard_data = document.cut_selection()
+ return new_document, clipboard_data
+
+
def create_text_object_decorator(registry):
"""
Create a decorator that can be used to register Vi text object implementations.
@@ -304,8 +304,8 @@ def load_vi_bindings(get_search_state=None):
# Overview of Readline Vi commands:
# http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
- :param get_search_state: None or a callable that takes a
- CommandLineInterface and returns a SearchState.
+ :param get_search_state: None or a callable that takes a
+ CommandLineInterface and returns a SearchState.
"""
# Note: Some key bindings have the "~IsReadOnly()" filter added. This
# prevents the handler to be executed when the focus is on a
@@ -323,29 +323,29 @@ def load_vi_bindings(get_search_state=None):
if get_search_state is None:
def get_search_state(cli): return cli.search_state
- # (Note: Always take the navigation bindings in read-only mode, even when
- # ViState says different.)
- navigation_mode = ViNavigationMode()
- insert_mode = ViInsertMode()
- insert_multiple_mode = ViInsertMultipleMode()
- replace_mode = ViReplaceMode()
- selection_mode = ViSelectionMode()
- operator_given = ViWaitingForTextObjectMode()
- digraph_mode = ViDigraphMode()
+ # (Note: Always take the navigation bindings in read-only mode, even when
+ # ViState says different.)
+ navigation_mode = ViNavigationMode()
+ insert_mode = ViInsertMode()
+ insert_multiple_mode = ViInsertMultipleMode()
+ replace_mode = ViReplaceMode()
+ selection_mode = ViSelectionMode()
+ operator_given = ViWaitingForTextObjectMode()
+ digraph_mode = ViDigraphMode()
vi_transform_functions = [
# Rot 13 transformation
- (('g', '?'), Always(), lambda string: codecs.encode(string, 'rot_13')),
+ (('g', '?'), Always(), lambda string: codecs.encode(string, 'rot_13')),
# To lowercase
- (('g', 'u'), Always(), lambda string: string.lower()),
+ (('g', 'u'), Always(), lambda string: string.lower()),
# To uppercase.
- (('g', 'U'), Always(), lambda string: string.upper()),
+ (('g', 'U'), Always(), lambda string: string.upper()),
# Swap case.
- (('g', '~'), Always(), lambda string: string.swapcase()),
- (('~', ), Condition(lambda cli: cli.vi_state.tilde_operator), lambda string: string.swapcase()),
+ (('g', '~'), Always(), lambda string: string.swapcase()),
+ (('~', ), Condition(lambda cli: cli.vi_state.tilde_operator), lambda string: string.swapcase()),
]
# Insert a character literally (quoted insert).
@@ -357,12 +357,12 @@ def load_vi_bindings(get_search_state=None):
Escape goes to vi navigation mode.
"""
buffer = event.current_buffer
- vi_state = event.cli.vi_state
+ vi_state = event.cli.vi_state
if vi_state.input_mode in (InputMode.INSERT, InputMode.REPLACE):
buffer.cursor_position += buffer.document.get_cursor_left_position()
- vi_state.reset(InputMode.NAVIGATION)
+ vi_state.reset(InputMode.NAVIGATION)
if bool(buffer.selection_state):
buffer.exit_selection()
@@ -387,34 +387,34 @@ def load_vi_bindings(get_search_state=None):
"""
Arrow up and ControlP in navigation mode go up.
"""
- event.current_buffer.auto_up(count=event.arg)
-
- @handle('k', filter=navigation_mode)
- def _(event):
- """
- Go up, but if we enter a new history entry, move to the start of the
- line.
- """
- event.current_buffer.auto_up(
- count=event.arg, go_to_start_of_line_if_history_changes=True)
-
+ event.current_buffer.auto_up(count=event.arg)
+
+ @handle('k', filter=navigation_mode)
+ def _(event):
+ """
+ Go up, but if we enter a new history entry, move to the start of the
+ line.
+ """
+ event.current_buffer.auto_up(
+ count=event.arg, go_to_start_of_line_if_history_changes=True)
+
@handle(Keys.Down, filter=navigation_mode)
@handle(Keys.ControlN, filter=navigation_mode)
def _(event):
"""
Arrow down and Control-N in navigation mode.
"""
- event.current_buffer.auto_down(count=event.arg)
-
- @handle('j', filter=navigation_mode)
- def _(event):
- """
- Go down, but if we enter a new history entry, go to the start of the line.
- """
- event.current_buffer.auto_down(
- count=event.arg, go_to_start_of_line_if_history_changes=True)
-
- @handle(Keys.ControlH, filter=navigation_mode)
+ event.current_buffer.auto_down(count=event.arg)
+
+ @handle('j', filter=navigation_mode)
+ def _(event):
+ """
+ Go down, but if we enter a new history entry, go to the start of the line.
+ """
+ event.current_buffer.auto_down(
+ count=event.arg, go_to_start_of_line_if_history_changes=True)
+
+ @handle(Keys.ControlH, filter=navigation_mode)
@handle(Keys.Backspace, filter=navigation_mode)
def _(event):
"""
@@ -458,7 +458,7 @@ def load_vi_bindings(get_search_state=None):
"""
event.current_buffer.cancel_completion()
- @handle(Keys.ControlJ, filter=navigation_mode) # XXX: only if the selected buffer has a return handler.
+ @handle(Keys.ControlJ, filter=navigation_mode) # XXX: only if the selected buffer has a return handler.
def _(event):
"""
In navigation mode, pressing enter will always return the input.
@@ -475,19 +475,19 @@ def load_vi_bindings(get_search_state=None):
@handle(Keys.Insert, filter=navigation_mode)
def _(event):
" Presing the Insert key. "
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('a', filter=navigation_mode & ~IsReadOnly())
# ~IsReadOnly, because we want to stay in navigation mode for
# read-only buffers.
def _(event):
event.current_buffer.cursor_position += event.current_buffer.document.get_cursor_right_position()
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('A', filter=navigation_mode & ~IsReadOnly())
def _(event):
event.current_buffer.cursor_position += event.current_buffer.document.get_end_of_line_position()
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('C', filter=navigation_mode & ~IsReadOnly())
def _(event):
@@ -499,7 +499,7 @@ def load_vi_bindings(get_search_state=None):
deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
event.cli.clipboard.set_text(deleted)
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('c', 'c', filter=navigation_mode & ~IsReadOnly())
@handle('S', filter=navigation_mode & ~IsReadOnly())
@@ -516,7 +516,7 @@ def load_vi_bindings(get_search_state=None):
# But we delete after the whitespace
buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=True)
buffer.delete(count=buffer.document.get_end_of_line_position())
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('D', filter=navigation_mode)
def _(event):
@@ -535,8 +535,8 @@ def load_vi_bindings(get_search_state=None):
lines = buffer.document.lines
before = '\n'.join(lines[:buffer.document.cursor_position_row])
- deleted = '\n'.join(lines[buffer.document.cursor_position_row:
- buffer.document.cursor_position_row + event.arg])
+ deleted = '\n'.join(lines[buffer.document.cursor_position_row:
+ buffer.document.cursor_position_row + event.arg])
after = '\n'.join(lines[buffer.document.cursor_position_row + event.arg:])
# Set new text.
@@ -552,81 +552,81 @@ def load_vi_bindings(get_search_state=None):
# Set clipboard data
event.cli.clipboard.set_data(ClipboardData(deleted, SelectionType.LINES))
- @handle('x', filter=selection_mode)
- def _(event):
- """
- Cut selection.
- ('x' is not an operator.)
- """
- clipboard_data = event.current_buffer.cut_selection()
- event.cli.clipboard.set_data(clipboard_data)
-
+ @handle('x', filter=selection_mode)
+ def _(event):
+ """
+ Cut selection.
+ ('x' is not an operator.)
+ """
+ clipboard_data = event.current_buffer.cut_selection()
+ event.cli.clipboard.set_data(clipboard_data)
+
@handle('i', filter=navigation_mode & ~IsReadOnly())
def _(event):
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('I', filter=navigation_mode & ~IsReadOnly())
def _(event):
- event.cli.vi_state.input_mode = InputMode.INSERT
- event.current_buffer.cursor_position += \
- event.current_buffer.document.get_start_of_line_position(after_whitespace=True)
-
- @Condition
- def in_block_selection(cli):
- buff = cli.current_buffer
- return buff.selection_state and buff.selection_state.type == SelectionType.BLOCK
-
- @handle('I', filter=in_block_selection & ~IsReadOnly())
- def go_to_block_selection(event, after=False):
- " Insert in block selection mode. "
- buff = event.current_buffer
-
- # Store all cursor positions.
- positions = []
-
- if after:
- def get_pos(from_to):
- return from_to[1] + 1
- else:
- def get_pos(from_to):
- return from_to[0]
-
- for i, from_to in enumerate(buff.document.selection_ranges()):
- positions.append(get_pos(from_to))
- if i == 0:
- buff.cursor_position = get_pos(from_to)
-
- buff.multiple_cursor_positions = positions
-
- # Go to 'INSERT_MULTIPLE' mode.
- event.cli.vi_state.input_mode = InputMode.INSERT_MULTIPLE
- buff.exit_selection()
-
- @handle('A', filter=in_block_selection & ~IsReadOnly())
- def _(event):
- go_to_block_selection(event, after=True)
-
- @handle('J', filter=navigation_mode & ~IsReadOnly())
- def _(event):
- " Join lines. "
+ event.cli.vi_state.input_mode = InputMode.INSERT
+ event.current_buffer.cursor_position += \
+ event.current_buffer.document.get_start_of_line_position(after_whitespace=True)
+
+ @Condition
+ def in_block_selection(cli):
+ buff = cli.current_buffer
+ return buff.selection_state and buff.selection_state.type == SelectionType.BLOCK
+
+ @handle('I', filter=in_block_selection & ~IsReadOnly())
+ def go_to_block_selection(event, after=False):
+ " Insert in block selection mode. "
+ buff = event.current_buffer
+
+ # Store all cursor positions.
+ positions = []
+
+ if after:
+ def get_pos(from_to):
+ return from_to[1] + 1
+ else:
+ def get_pos(from_to):
+ return from_to[0]
+
+ for i, from_to in enumerate(buff.document.selection_ranges()):
+ positions.append(get_pos(from_to))
+ if i == 0:
+ buff.cursor_position = get_pos(from_to)
+
+ buff.multiple_cursor_positions = positions
+
+ # Go to 'INSERT_MULTIPLE' mode.
+ event.cli.vi_state.input_mode = InputMode.INSERT_MULTIPLE
+ buff.exit_selection()
+
+ @handle('A', filter=in_block_selection & ~IsReadOnly())
+ def _(event):
+ go_to_block_selection(event, after=True)
+
+ @handle('J', filter=navigation_mode & ~IsReadOnly())
+ def _(event):
+ " Join lines. "
for i in range(event.arg):
event.current_buffer.join_next_line()
- @handle('g', 'J', filter=navigation_mode & ~IsReadOnly())
+ @handle('g', 'J', filter=navigation_mode & ~IsReadOnly())
def _(event):
- " Join lines without space. "
- for i in range(event.arg):
- event.current_buffer.join_next_line(separator='')
-
- @handle('J', filter=selection_mode & ~IsReadOnly())
- def _(event):
- " Join selected lines. "
+ " Join lines without space. "
+ for i in range(event.arg):
+ event.current_buffer.join_next_line(separator='')
+
+ @handle('J', filter=selection_mode & ~IsReadOnly())
+ def _(event):
+ " Join selected lines. "
event.current_buffer.join_selected_lines()
- @handle('g', 'J', filter=selection_mode & ~IsReadOnly())
- def _(event):
- " Join selected lines without space. "
- event.current_buffer.join_selected_lines(separator='')
+ @handle('g', 'J', filter=selection_mode & ~IsReadOnly())
+ def _(event):
+ " Join selected lines without space. "
+ event.current_buffer.join_selected_lines(separator='')
@handle('p', filter=navigation_mode)
def _(event):
@@ -648,26 +648,26 @@ def load_vi_bindings(get_search_state=None):
count=event.arg,
paste_mode=PasteMode.VI_BEFORE)
- @handle('"', Keys.Any, 'p', filter=navigation_mode)
- def _(event):
- " Paste from named register. "
- c = event.key_sequence[1].data
- if c in vi_register_names:
- data = event.cli.vi_state.named_registers.get(c)
- if data:
+ @handle('"', Keys.Any, 'p', filter=navigation_mode)
+ def _(event):
+ " Paste from named register. "
+ c = event.key_sequence[1].data
+ if c in vi_register_names:
+ data = event.cli.vi_state.named_registers.get(c)
+ if data:
event.current_buffer.paste_clipboard_data(
data, count=event.arg, paste_mode=PasteMode.VI_AFTER)
-
- @handle('"', Keys.Any, 'P', filter=navigation_mode)
- def _(event):
- " Paste (before) from named register. "
- c = event.key_sequence[1].data
- if c in vi_register_names:
- data = event.cli.vi_state.named_registers.get(c)
- if data:
- event.current_buffer.paste_clipboard_data(
+
+ @handle('"', Keys.Any, 'P', filter=navigation_mode)
+ def _(event):
+ " Paste (before) from named register. "
+ c = event.key_sequence[1].data
+ if c in vi_register_names:
+ data = event.cli.vi_state.named_registers.get(c)
+ if data:
+ event.current_buffer.paste_clipboard_data(
data, count=event.arg, paste_mode=PasteMode.VI_BEFORE)
-
+
@handle('r', Keys.Any, filter=navigation_mode)
def _(event):
"""
@@ -681,7 +681,7 @@ def load_vi_bindings(get_search_state=None):
"""
Go to 'replace'-mode.
"""
- event.cli.vi_state.input_mode = InputMode.REPLACE
+ event.cli.vi_state.input_mode = InputMode.REPLACE
@handle('s', filter=navigation_mode & ~IsReadOnly())
def _(event):
@@ -691,7 +691,7 @@ def load_vi_bindings(get_search_state=None):
"""
text = event.current_buffer.delete(count=event.arg)
event.cli.clipboard.set_text(text)
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('u', filter=navigation_mode, save_before=(lambda e: False))
def _(event):
@@ -830,7 +830,7 @@ def load_vi_bindings(get_search_state=None):
"""
event.current_buffer.insert_line_above(
copy_margin=not event.cli.in_paste_mode)
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('o', filter=navigation_mode & ~IsReadOnly())
def _(event):
@@ -839,7 +839,7 @@ def load_vi_bindings(get_search_state=None):
"""
event.current_buffer.insert_line_below(
copy_margin=not event.cli.in_paste_mode)
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle('~', filter=navigation_mode)
def _(event):
@@ -850,26 +850,26 @@ def load_vi_bindings(get_search_state=None):
c = buffer.document.current_char
if c is not None and c != '\n':
- buffer.insert_text(c.swapcase(), overwrite=True)
-
- @handle('g', 'u', 'u', filter=navigation_mode & ~IsReadOnly())
- def _(event):
- " Lowercase current line. "
- buff = event.current_buffer
- buff.transform_current_line(lambda s: s.lower())
-
- @handle('g', 'U', 'U', filter=navigation_mode & ~IsReadOnly())
- def _(event):
- " Uppercase current line. "
- buff = event.current_buffer
- buff.transform_current_line(lambda s: s.upper())
-
- @handle('g', '~', '~', filter=navigation_mode & ~IsReadOnly())
- def _(event):
- " Swap case of the current line. "
- buff = event.current_buffer
- buff.transform_current_line(lambda s: s.swapcase())
-
+ buffer.insert_text(c.swapcase(), overwrite=True)
+
+ @handle('g', 'u', 'u', filter=navigation_mode & ~IsReadOnly())
+ def _(event):
+ " Lowercase current line. "
+ buff = event.current_buffer
+ buff.transform_current_line(lambda s: s.lower())
+
+ @handle('g', 'U', 'U', filter=navigation_mode & ~IsReadOnly())
+ def _(event):
+ " Uppercase current line. "
+ buff = event.current_buffer
+ buff.transform_current_line(lambda s: s.upper())
+
+ @handle('g', '~', '~', filter=navigation_mode & ~IsReadOnly())
+ def _(event):
+ " Swap case of the current line. "
+ buff = event.current_buffer
+ buff.transform_current_line(lambda s: s.swapcase())
+
@handle('#', filter=navigation_mode)
def _(event):
"""
@@ -901,338 +901,338 @@ def load_vi_bindings(get_search_state=None):
@handle('(', filter=navigation_mode)
def _(event):
# TODO: go to begin of sentence.
- # XXX: should become text_object.
+ # XXX: should become text_object.
pass
@handle(')', filter=navigation_mode)
def _(event):
# TODO: go to end of sentence.
- # XXX: should become text_object.
+ # XXX: should become text_object.
pass
operator = create_operator_decorator(registry)
text_object = create_text_object_decorator(registry)
- @text_object(Keys.Any, filter=operator_given)
- def _(event):
- """
- Unknown key binding while waiting for a text object.
- """
- event.cli.output.bell()
-
- #
- # *** Operators ***
- #
-
- def create_delete_and_change_operators(delete_only, with_register=False):
- """
- Delete and change operators.
-
- :param delete_only: Create an operator that deletes, but doesn't go to insert mode.
- :param with_register: Copy the deleted text to this named register instead of the clipboard.
- """
- if with_register:
- handler_keys = ('"', Keys.Any, 'cd'[delete_only])
- else:
- handler_keys = 'cd'[delete_only]
-
- @operator(*handler_keys, filter=~IsReadOnly())
- def delete_or_change_operator(event, text_object):
- clipboard_data = None
- buff = event.current_buffer
-
- if text_object:
- new_document, clipboard_data = text_object.cut(buff)
- buff.document = new_document
-
- # Set deleted/changed text to clipboard or named register.
- if clipboard_data and clipboard_data.text:
- if with_register:
- reg_name = event.key_sequence[1].data
- if reg_name in vi_register_names:
- event.cli.vi_state.named_registers[reg_name] = clipboard_data
- else:
- event.cli.clipboard.set_data(clipboard_data)
-
- # Only go back to insert mode in case of 'change'.
- if not delete_only:
- event.cli.vi_state.input_mode = InputMode.INSERT
-
- create_delete_and_change_operators(False, False)
- create_delete_and_change_operators(False, True)
- create_delete_and_change_operators(True, False)
- create_delete_and_change_operators(True, True)
-
- def create_transform_handler(filter, transform_func, *a):
- @operator(*a, filter=filter & ~IsReadOnly())
- def _(event, text_object):
- """
- Apply transformation (uppercase, lowercase, rot13, swap case).
- """
- buff = event.current_buffer
- start, end = text_object.operator_range(buff.document)
-
- if start < end:
- # Transform.
- buff.transform_region(
- buff.cursor_position + start,
- buff.cursor_position + end,
- transform_func)
-
- # Move cursor
- buff.cursor_position += (text_object.end or text_object.start)
-
- for k, f, func in vi_transform_functions:
- create_transform_handler(f, func, *k)
-
- @operator('y')
- def yank_handler(event, text_object):
- """
- Yank operator. (Copy text.)
- """
- _, clipboard_data = text_object.cut(event.current_buffer)
- if clipboard_data.text:
- event.cli.clipboard.set_data(clipboard_data)
-
- @operator('"', Keys.Any, 'y')
- def _(event, text_object):
- " Yank selection to named register. "
- c = event.key_sequence[1].data
- if c in vi_register_names:
- _, clipboard_data = text_object.cut(event.current_buffer)
- event.cli.vi_state.named_registers[c] = clipboard_data
-
- @operator('>')
- def _(event, text_object):
- """
- Indent.
- """
- buff = event.current_buffer
- from_, to = text_object.get_line_numbers(buff)
- indent(buff, from_, to + 1, count=event.arg)
-
- @operator('<')
- def _(event, text_object):
- """
- Unindent.
- """
- buff = event.current_buffer
- from_, to = text_object.get_line_numbers(buff)
- unindent(buff, from_, to + 1, count=event.arg)
-
- @operator('g', 'q')
- def _(event, text_object):
- """
- Reshape text.
- """
- buff = event.current_buffer
- from_, to = text_object.get_line_numbers(buff)
- reshape_text(buff, from_, to)
-
- #
- # *** Text objects ***
- #
-
- @text_object('b')
+ @text_object(Keys.Any, filter=operator_given)
+ def _(event):
+ """
+ Unknown key binding while waiting for a text object.
+ """
+ event.cli.output.bell()
+
+ #
+ # *** Operators ***
+ #
+
+ def create_delete_and_change_operators(delete_only, with_register=False):
+ """
+ Delete and change operators.
+
+ :param delete_only: Create an operator that deletes, but doesn't go to insert mode.
+ :param with_register: Copy the deleted text to this named register instead of the clipboard.
+ """
+ if with_register:
+ handler_keys = ('"', Keys.Any, 'cd'[delete_only])
+ else:
+ handler_keys = 'cd'[delete_only]
+
+ @operator(*handler_keys, filter=~IsReadOnly())
+ def delete_or_change_operator(event, text_object):
+ clipboard_data = None
+ buff = event.current_buffer
+
+ if text_object:
+ new_document, clipboard_data = text_object.cut(buff)
+ buff.document = new_document
+
+ # Set deleted/changed text to clipboard or named register.
+ if clipboard_data and clipboard_data.text:
+ if with_register:
+ reg_name = event.key_sequence[1].data
+ if reg_name in vi_register_names:
+ event.cli.vi_state.named_registers[reg_name] = clipboard_data
+ else:
+ event.cli.clipboard.set_data(clipboard_data)
+
+ # Only go back to insert mode in case of 'change'.
+ if not delete_only:
+ event.cli.vi_state.input_mode = InputMode.INSERT
+
+ create_delete_and_change_operators(False, False)
+ create_delete_and_change_operators(False, True)
+ create_delete_and_change_operators(True, False)
+ create_delete_and_change_operators(True, True)
+
+ def create_transform_handler(filter, transform_func, *a):
+ @operator(*a, filter=filter & ~IsReadOnly())
+ def _(event, text_object):
+ """
+ Apply transformation (uppercase, lowercase, rot13, swap case).
+ """
+ buff = event.current_buffer
+ start, end = text_object.operator_range(buff.document)
+
+ if start < end:
+ # Transform.
+ buff.transform_region(
+ buff.cursor_position + start,
+ buff.cursor_position + end,
+ transform_func)
+
+ # Move cursor
+ buff.cursor_position += (text_object.end or text_object.start)
+
+ for k, f, func in vi_transform_functions:
+ create_transform_handler(f, func, *k)
+
+ @operator('y')
+ def yank_handler(event, text_object):
+ """
+ Yank operator. (Copy text.)
+ """
+ _, clipboard_data = text_object.cut(event.current_buffer)
+ if clipboard_data.text:
+ event.cli.clipboard.set_data(clipboard_data)
+
+ @operator('"', Keys.Any, 'y')
+ def _(event, text_object):
+ " Yank selection to named register. "
+ c = event.key_sequence[1].data
+ if c in vi_register_names:
+ _, clipboard_data = text_object.cut(event.current_buffer)
+ event.cli.vi_state.named_registers[c] = clipboard_data
+
+ @operator('>')
+ def _(event, text_object):
+ """
+ Indent.
+ """
+ buff = event.current_buffer
+ from_, to = text_object.get_line_numbers(buff)
+ indent(buff, from_, to + 1, count=event.arg)
+
+ @operator('<')
+ def _(event, text_object):
+ """
+ Unindent.
+ """
+ buff = event.current_buffer
+ from_, to = text_object.get_line_numbers(buff)
+ unindent(buff, from_, to + 1, count=event.arg)
+
+ @operator('g', 'q')
+ def _(event, text_object):
+ """
+ Reshape text.
+ """
+ buff = event.current_buffer
+ from_, to = text_object.get_line_numbers(buff)
+ reshape_text(buff, from_, to)
+
+ #
+ # *** Text objects ***
+ #
+
+ @text_object('b')
def _(event):
""" Move one word or token left. """
- return TextObject(event.current_buffer.document.find_start_of_previous_word(count=event.arg) or 0)
+ return TextObject(event.current_buffer.document.find_start_of_previous_word(count=event.arg) or 0)
- @text_object('B')
+ @text_object('B')
def _(event):
""" Move one non-blank word left """
- return TextObject(event.current_buffer.document.find_start_of_previous_word(count=event.arg, WORD=True) or 0)
+ return TextObject(event.current_buffer.document.find_start_of_previous_word(count=event.arg, WORD=True) or 0)
- @text_object('$')
+ @text_object('$')
def key_dollar(event):
""" 'c$', 'd$' and '$': Delete/change/move until end of line. """
- return TextObject(event.current_buffer.document.get_end_of_line_position())
+ return TextObject(event.current_buffer.document.get_end_of_line_position())
- @text_object('w')
+ @text_object('w')
def _(event):
""" 'word' forward. 'cw', 'dw', 'w': Delete/change/move one word. """
- return TextObject(event.current_buffer.document.find_next_word_beginning(count=event.arg) or
+ return TextObject(event.current_buffer.document.find_next_word_beginning(count=event.arg) or
event.current_buffer.document.get_end_of_document_position())
- @text_object('W')
+ @text_object('W')
def _(event):
""" 'WORD' forward. 'cW', 'dW', 'W': Delete/change/move one WORD. """
- return TextObject(event.current_buffer.document.find_next_word_beginning(count=event.arg, WORD=True) or
+ return TextObject(event.current_buffer.document.find_next_word_beginning(count=event.arg, WORD=True) or
event.current_buffer.document.get_end_of_document_position())
- @text_object('e')
+ @text_object('e')
def _(event):
""" End of 'word': 'ce', 'de', 'e' """
end = event.current_buffer.document.find_next_word_ending(count=event.arg)
- return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
+ return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
- @text_object('E')
+ @text_object('E')
def _(event):
""" End of 'WORD': 'cE', 'dE', 'E' """
end = event.current_buffer.document.find_next_word_ending(count=event.arg, WORD=True)
- return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
+ return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
- @text_object('i', 'w', no_move_handler=True)
+ @text_object('i', 'w', no_move_handler=True)
def _(event):
""" Inner 'word': ciw and diw """
start, end = event.current_buffer.document.find_boundaries_of_current_word()
- return TextObject(start, end)
+ return TextObject(start, end)
- @text_object('a', 'w', no_move_handler=True)
+ @text_object('a', 'w', no_move_handler=True)
def _(event):
""" A 'word': caw and daw """
start, end = event.current_buffer.document.find_boundaries_of_current_word(include_trailing_whitespace=True)
- return TextObject(start, end)
+ return TextObject(start, end)
- @text_object('i', 'W', no_move_handler=True)
+ @text_object('i', 'W', no_move_handler=True)
def _(event):
""" Inner 'WORD': ciW and diW """
start, end = event.current_buffer.document.find_boundaries_of_current_word(WORD=True)
- return TextObject(start, end)
+ return TextObject(start, end)
- @text_object('a', 'W', no_move_handler=True)
+ @text_object('a', 'W', no_move_handler=True)
def _(event):
""" A 'WORD': caw and daw """
start, end = event.current_buffer.document.find_boundaries_of_current_word(WORD=True, include_trailing_whitespace=True)
- return TextObject(start, end)
-
- @text_object('a', 'p', no_move_handler=True)
- def _(event):
- """
- Auto paragraph.
- """
- start = event.current_buffer.document.start_of_paragraph()
- end = event.current_buffer.document.end_of_paragraph(count=event.arg)
- return TextObject(start, end)
-
- @text_object('^')
+ return TextObject(start, end)
+
+ @text_object('a', 'p', no_move_handler=True)
+ def _(event):
+ """
+ Auto paragraph.
+ """
+ start = event.current_buffer.document.start_of_paragraph()
+ end = event.current_buffer.document.end_of_paragraph(count=event.arg)
+ return TextObject(start, end)
+
+ @text_object('^')
def key_circumflex(event):
""" 'c^', 'd^' and '^': Soft start of line, after whitespace. """
- return TextObject(event.current_buffer.document.get_start_of_line_position(after_whitespace=True))
+ return TextObject(event.current_buffer.document.get_start_of_line_position(after_whitespace=True))
- @text_object('0')
+ @text_object('0')
def key_zero(event):
"""
'c0', 'd0': Hard start of line, before whitespace.
(The move '0' key is implemented elsewhere, because a '0' could also change the `arg`.)
"""
- return TextObject(event.current_buffer.document.get_start_of_line_position(after_whitespace=False))
+ return TextObject(event.current_buffer.document.get_start_of_line_position(after_whitespace=False))
- def create_ci_ca_handles(ci_start, ci_end, inner, key=None):
+ def create_ci_ca_handles(ci_start, ci_end, inner, key=None):
# TODO: 'dat', 'dit', (tags (like xml)
"""
Delete/Change string between this start and stop character. But keep these characters.
This implements all the ci", ci<, ci{, ci(, di", di<, ca", ca<, ... combinations.
"""
- def handler(event):
- if ci_start == ci_end:
- # Quotes
- start = event.current_buffer.document.find_backwards(ci_start, in_current_line=False)
- end = event.current_buffer.document.find(ci_end, in_current_line=False)
- else:
- # Brackets
- start = event.current_buffer.document.find_enclosing_bracket_left(ci_start, ci_end)
- end = event.current_buffer.document.find_enclosing_bracket_right(ci_start, ci_end)
+ def handler(event):
+ if ci_start == ci_end:
+ # Quotes
+ start = event.current_buffer.document.find_backwards(ci_start, in_current_line=False)
+ end = event.current_buffer.document.find(ci_end, in_current_line=False)
+ else:
+ # Brackets
+ start = event.current_buffer.document.find_enclosing_bracket_left(ci_start, ci_end)
+ end = event.current_buffer.document.find_enclosing_bracket_right(ci_start, ci_end)
if start is not None and end is not None:
offset = 0 if inner else 1
- return TextObject(start + 1 - offset, end + offset)
+ return TextObject(start + 1 - offset, end + offset)
else:
# Nothing found.
- return TextObject(0)
-
- if key is None:
- text_object('ai'[inner], ci_start, no_move_handler=True)(handler)
- text_object('ai'[inner], ci_end, no_move_handler=True)(handler)
- else:
- text_object('ai'[inner], key, no_move_handler=True)(handler)
-
+ return TextObject(0)
+
+ if key is None:
+ text_object('ai'[inner], ci_start, no_move_handler=True)(handler)
+ text_object('ai'[inner], ci_end, no_move_handler=True)(handler)
+ else:
+ text_object('ai'[inner], key, no_move_handler=True)(handler)
+
for inner in (False, True):
for ci_start, ci_end in [('"', '"'), ("'", "'"), ("`", "`"),
('[', ']'), ('<', '>'), ('{', '}'), ('(', ')')]:
create_ci_ca_handles(ci_start, ci_end, inner)
- create_ci_ca_handles('(', ')', inner, 'b') # 'dab', 'dib'
- create_ci_ca_handles('{', '}', inner, 'B') # 'daB', 'diB'
-
- @text_object('{')
+ create_ci_ca_handles('(', ')', inner, 'b') # 'dab', 'dib'
+ create_ci_ca_handles('{', '}', inner, 'B') # 'daB', 'diB'
+
+ @text_object('{')
def _(event):
"""
Move to previous blank-line separated section.
Implements '{', 'c{', 'd{', 'y{'
"""
- index = event.current_buffer.document.start_of_paragraph(
- count=event.arg, before=True)
- return TextObject(index)
+ index = event.current_buffer.document.start_of_paragraph(
+ count=event.arg, before=True)
+ return TextObject(index)
- @text_object('}')
+ @text_object('}')
def _(event):
"""
Move to next blank-line separated section.
Implements '}', 'c}', 'd}', 'y}'
"""
- index = event.current_buffer.document.end_of_paragraph(count=event.arg, after=True)
- return TextObject(index)
+ index = event.current_buffer.document.end_of_paragraph(count=event.arg, after=True)
+ return TextObject(index)
- @text_object('f', Keys.Any)
+ @text_object('f', Keys.Any)
def _(event):
"""
Go to next occurance of character. Typing 'fx' will move the
cursor to the next occurance of character. 'x'.
"""
- event.cli.vi_state.last_character_find = CharacterFind(event.data, False)
- match = event.current_buffer.document.find(
- event.data, in_current_line=True, count=event.arg)
- if match:
- return TextObject(match, type=TextObjectType.INCLUSIVE)
- else:
- return TextObject(0)
+ event.cli.vi_state.last_character_find = CharacterFind(event.data, False)
+ match = event.current_buffer.document.find(
+ event.data, in_current_line=True, count=event.arg)
+ if match:
+ return TextObject(match, type=TextObjectType.INCLUSIVE)
+ else:
+ return TextObject(0)
- @text_object('F', Keys.Any)
+ @text_object('F', Keys.Any)
def _(event):
"""
Go to previous occurance of character. Typing 'Fx' will move the
cursor to the previous occurance of character. 'x'.
"""
- event.cli.vi_state.last_character_find = CharacterFind(event.data, True)
- return TextObject(event.current_buffer.document.find_backwards(
- event.data, in_current_line=True, count=event.arg) or 0)
+ event.cli.vi_state.last_character_find = CharacterFind(event.data, True)
+ return TextObject(event.current_buffer.document.find_backwards(
+ event.data, in_current_line=True, count=event.arg) or 0)
- @text_object('t', Keys.Any)
+ @text_object('t', Keys.Any)
def _(event):
"""
Move right to the next occurance of c, then one char backward.
"""
- event.cli.vi_state.last_character_find = CharacterFind(event.data, False)
- match = event.current_buffer.document.find(
- event.data, in_current_line=True, count=event.arg)
- if match:
- return TextObject(match - 1, type=TextObjectType.INCLUSIVE)
- else:
- return TextObject(0)
+ event.cli.vi_state.last_character_find = CharacterFind(event.data, False)
+ match = event.current_buffer.document.find(
+ event.data, in_current_line=True, count=event.arg)
+ if match:
+ return TextObject(match - 1, type=TextObjectType.INCLUSIVE)
+ else:
+ return TextObject(0)
- @text_object('T', Keys.Any)
+ @text_object('T', Keys.Any)
def _(event):
"""
Move left to the previous occurance of c, then one char forward.
"""
- event.cli.vi_state.last_character_find = CharacterFind(event.data, True)
- match = event.current_buffer.document.find_backwards(
- event.data, in_current_line=True, count=event.arg)
- return TextObject(match + 1 if match else 0)
+ event.cli.vi_state.last_character_find = CharacterFind(event.data, True)
+ match = event.current_buffer.document.find_backwards(
+ event.data, in_current_line=True, count=event.arg)
+ return TextObject(match + 1 if match else 0)
def repeat(reverse):
"""
Create ',' and ';' commands.
"""
- @text_object(',' if reverse else ';')
+ @text_object(',' if reverse else ';')
def _(event):
# Repeat the last 'f'/'F'/'t'/'T' command.
pos = 0
- vi_state = event.cli.vi_state
+ vi_state = event.cli.vi_state
+
+ type = TextObjectType.EXCLUSIVE
- type = TextObjectType.EXCLUSIVE
-
if vi_state.last_character_find:
char = vi_state.last_character_find.character
backwards = vi_state.last_character_find.backwards
@@ -1244,43 +1244,43 @@ def load_vi_bindings(get_search_state=None):
pos = event.current_buffer.document.find_backwards(char, in_current_line=True, count=event.arg)
else:
pos = event.current_buffer.document.find(char, in_current_line=True, count=event.arg)
- type = TextObjectType.INCLUSIVE
- if pos:
- return TextObject(pos, type=type)
- else:
- return TextObject(0)
+ type = TextObjectType.INCLUSIVE
+ if pos:
+ return TextObject(pos, type=type)
+ else:
+ return TextObject(0)
repeat(True)
repeat(False)
- @text_object('h')
- @text_object(Keys.Left)
+ @text_object('h')
+ @text_object(Keys.Left)
def _(event):
""" Implements 'ch', 'dh', 'h': Cursor left. """
- return TextObject(event.current_buffer.document.get_cursor_left_position(count=event.arg))
+ return TextObject(event.current_buffer.document.get_cursor_left_position(count=event.arg))
- @text_object('j', no_move_handler=True, no_selection_handler=True)
- # Note: We also need `no_selection_handler`, because we in
- # selection mode, we prefer the other 'j' binding that keeps
- # `buffer.preferred_column`.
+ @text_object('j', no_move_handler=True, no_selection_handler=True)
+ # Note: We also need `no_selection_handler`, because we in
+ # selection mode, we prefer the other 'j' binding that keeps
+ # `buffer.preferred_column`.
def _(event):
""" Implements 'cj', 'dj', 'j', ... Cursor up. """
- return TextObject(event.current_buffer.document.get_cursor_down_position(count=event.arg),
- type=TextObjectType.LINEWISE)
+ return TextObject(event.current_buffer.document.get_cursor_down_position(count=event.arg),
+ type=TextObjectType.LINEWISE)
- @text_object('k', no_move_handler=True, no_selection_handler=True)
+ @text_object('k', no_move_handler=True, no_selection_handler=True)
def _(event):
""" Implements 'ck', 'dk', 'k', ... Cursor up. """
- return TextObject(event.current_buffer.document.get_cursor_up_position(count=event.arg),
- type=TextObjectType.LINEWISE)
+ return TextObject(event.current_buffer.document.get_cursor_up_position(count=event.arg),
+ type=TextObjectType.LINEWISE)
- @text_object('l')
- @text_object(' ')
- @text_object(Keys.Right)
+ @text_object('l')
+ @text_object(' ')
+ @text_object(Keys.Right)
def _(event):
""" Implements 'cl', 'dl', 'l', 'c ', 'd ', ' '. Cursor right. """
- return TextObject(event.current_buffer.document.get_cursor_right_position(count=event.arg))
+ return TextObject(event.current_buffer.document.get_cursor_right_position(count=event.arg))
- @text_object('H')
+ @text_object('H')
def _(event):
"""
Moves to the start of the visible region. (Below the scroll offset.)
@@ -1289,7 +1289,7 @@ def load_vi_bindings(get_search_state=None):
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
b = event.current_buffer
- if w and w.render_info:
+ if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the start of the visible area.
pos = (b.document.translate_row_col_to_index(
@@ -1299,9 +1299,9 @@ def load_vi_bindings(get_search_state=None):
else:
# Otherwise, move to the start of the input.
pos = -len(b.document.text_before_cursor)
- return TextObject(pos, type=TextObjectType.LINEWISE)
+ return TextObject(pos, type=TextObjectType.LINEWISE)
- @text_object('M')
+ @text_object('M')
def _(event):
"""
Moves cursor to the vertical center of the visible region.
@@ -1310,7 +1310,7 @@ def load_vi_bindings(get_search_state=None):
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
b = event.current_buffer
- if w and w.render_info:
+ if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the center of the visible area.
pos = (b.document.translate_row_col_to_index(
@@ -1320,9 +1320,9 @@ def load_vi_bindings(get_search_state=None):
else:
# Otherwise, move to the start of the input.
pos = -len(b.document.text_before_cursor)
- return TextObject(pos, type=TextObjectType.LINEWISE)
+ return TextObject(pos, type=TextObjectType.LINEWISE)
- @text_object('L')
+ @text_object('L')
def _(event):
"""
Moves to the end of the visible region. (Above the scroll offset.)
@@ -1330,7 +1330,7 @@ def load_vi_bindings(get_search_state=None):
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
b = event.current_buffer
- if w and w.render_info:
+ if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the end of the visible area.
pos = (b.document.translate_row_col_to_index(
@@ -1340,40 +1340,40 @@ def load_vi_bindings(get_search_state=None):
else:
# Otherwise, move to the end of the input.
pos = len(b.document.text_after_cursor)
- return TextObject(pos, type=TextObjectType.LINEWISE)
-
- @text_object('n', no_move_handler=True)
- def _(event):
- " Search next. "
- buff = event.current_buffer
- cursor_position = buff.get_search_position(
- get_search_state(event.cli), include_current_position=False,
- count=event.arg)
- return TextObject(cursor_position - buff.cursor_position)
-
- @handle('n', filter=navigation_mode)
- def _(event):
- " Search next in navigation mode. (This goes through the history.) "
- event.current_buffer.apply_search(
- get_search_state(event.cli), include_current_position=False,
- count=event.arg)
-
- @text_object('N', no_move_handler=True)
- def _(event):
- " Search previous. "
- buff = event.current_buffer
- cursor_position = buff.get_search_position(
- ~get_search_state(event.cli), include_current_position=False,
- count=event.arg)
- return TextObject(cursor_position - buff.cursor_position)
-
- @handle('N', filter=navigation_mode)
- def _(event):
- " Search previous in navigation mode. (This goes through the history.) "
- event.current_buffer.apply_search(
- ~get_search_state(event.cli), include_current_position=False,
- count=event.arg)
-
+ return TextObject(pos, type=TextObjectType.LINEWISE)
+
+ @text_object('n', no_move_handler=True)
+ def _(event):
+ " Search next. "
+ buff = event.current_buffer
+ cursor_position = buff.get_search_position(
+ get_search_state(event.cli), include_current_position=False,
+ count=event.arg)
+ return TextObject(cursor_position - buff.cursor_position)
+
+ @handle('n', filter=navigation_mode)
+ def _(event):
+ " Search next in navigation mode. (This goes through the history.) "
+ event.current_buffer.apply_search(
+ get_search_state(event.cli), include_current_position=False,
+ count=event.arg)
+
+ @text_object('N', no_move_handler=True)
+ def _(event):
+ " Search previous. "
+ buff = event.current_buffer
+ cursor_position = buff.get_search_position(
+ ~get_search_state(event.cli), include_current_position=False,
+ count=event.arg)
+ return TextObject(cursor_position - buff.cursor_position)
+
+ @handle('N', filter=navigation_mode)
+ def _(event):
+ " Search previous in navigation mode. (This goes through the history.) "
+ event.current_buffer.apply_search(
+ ~get_search_state(event.cli), include_current_position=False,
+ count=event.arg)
+
@handle('z', '+', filter=navigation_mode|selection_mode)
@handle('z', 't', filter=navigation_mode|selection_mode)
@handle('z', Keys.ControlJ, filter=navigation_mode|selection_mode)
@@ -1383,7 +1383,7 @@ def load_vi_bindings(get_search_state=None):
"""
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
b = event.cli.current_buffer
- w.vertical_scroll = b.document.cursor_position_row
+ w.vertical_scroll = b.document.cursor_position_row
@handle('z', '-', filter=navigation_mode|selection_mode)
@handle('z', 'b', filter=navigation_mode|selection_mode)
@@ -1393,10 +1393,10 @@ def load_vi_bindings(get_search_state=None):
"""
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
- # We can safely set the scroll offset to zero; the Window will meke
- # sure that it scrolls at least enough to make the cursor visible
- # again.
- w.vertical_scroll = 0
+ # We can safely set the scroll offset to zero; the Window will meke
+ # sure that it scrolls at least enough to make the cursor visible
+ # again.
+ w.vertical_scroll = 0
@handle('z', 'z', filter=navigation_mode|selection_mode)
def _(event):
@@ -1407,26 +1407,26 @@ def load_vi_bindings(get_search_state=None):
b = event.cli.current_buffer
if w and w.render_info:
- info = w.render_info
-
+ info = w.render_info
+
# Calculate the offset that we need in order to position the row
# containing the cursor in the center.
- scroll_height = info.window_height // 2
+ scroll_height = info.window_height // 2
+
+ y = max(0, b.document.cursor_position_row - 1)
+ height = 0
+ while y > 0:
+ line_height = info.get_height_for_line(y)
+
+ if height + line_height < scroll_height:
+ height += line_height
+ y -= 1
+ else:
+ break
- y = max(0, b.document.cursor_position_row - 1)
- height = 0
- while y > 0:
- line_height = info.get_height_for_line(y)
+ w.vertical_scroll = y
- if height + line_height < scroll_height:
- height += line_height
- y -= 1
- else:
- break
-
- w.vertical_scroll = y
-
- @text_object('%')
+ @text_object('%')
def _(event):
"""
Implements 'c%', 'd%', '%, 'y%' (Move to corresponding bracket.)
@@ -1439,26 +1439,26 @@ def load_vi_bindings(get_search_state=None):
# row in the file.
if 0 < event.arg <= 100:
absolute_index = buffer.document.translate_row_col_to_index(
- int((event.arg * buffer.document.line_count - 1) / 100), 0)
- return TextObject(absolute_index - buffer.document.cursor_position, type=TextObjectType.LINEWISE)
+ int((event.arg * buffer.document.line_count - 1) / 100), 0)
+ return TextObject(absolute_index - buffer.document.cursor_position, type=TextObjectType.LINEWISE)
else:
- return TextObject(0) # Do nothing.
+ return TextObject(0) # Do nothing.
else:
# Move to the corresponding opening/closing bracket (()'s, []'s and {}'s).
- match = buffer.document.find_matching_bracket_position()
- if match:
- return TextObject(match, type=TextObjectType.INCLUSIVE)
- else:
- return TextObject(0)
+ match = buffer.document.find_matching_bracket_position()
+ if match:
+ return TextObject(match, type=TextObjectType.INCLUSIVE)
+ else:
+ return TextObject(0)
- @text_object('|')
+ @text_object('|')
def _(event):
# Move to the n-th column (you may specify the argument n by typing
# it on number keys, for example, 20|).
- return TextObject(event.current_buffer.document.get_column_cursor_position(event.arg - 1))
+ return TextObject(event.current_buffer.document.get_column_cursor_position(event.arg - 1))
- @text_object('g', 'g')
+ @text_object('g', 'g')
def _(event):
"""
Implements 'gg', 'cgg', 'ygg'
@@ -1467,67 +1467,67 @@ def load_vi_bindings(get_search_state=None):
if event._arg:
# Move to the given line.
- return TextObject(d.translate_row_col_to_index(event.arg - 1, 0) - d.cursor_position, type=TextObjectType.LINEWISE)
+ return TextObject(d.translate_row_col_to_index(event.arg - 1, 0) - d.cursor_position, type=TextObjectType.LINEWISE)
else:
# Move to the top of the input.
- return TextObject(d.get_start_of_document_position(), type=TextObjectType.LINEWISE)
+ return TextObject(d.get_start_of_document_position(), type=TextObjectType.LINEWISE)
- @text_object('g', '_')
+ @text_object('g', '_')
def _(event):
"""
Go to last non-blank of line.
'g_', 'cg_', 'yg_', etc..
"""
- return TextObject(
- event.current_buffer.document.last_non_blank_of_current_line_position(), type=TextObjectType.INCLUSIVE)
+ return TextObject(
+ event.current_buffer.document.last_non_blank_of_current_line_position(), type=TextObjectType.INCLUSIVE)
- @text_object('g', 'e')
+ @text_object('g', 'e')
def _(event):
"""
Go to last character of previous word.
'ge', 'cge', 'yge', etc..
"""
- prev_end = event.current_buffer.document.find_previous_word_ending(count=event.arg)
- return TextObject(prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE)
+ prev_end = event.current_buffer.document.find_previous_word_ending(count=event.arg)
+ return TextObject(prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE)
- @text_object('g', 'E')
+ @text_object('g', 'E')
def _(event):
"""
Go to last character of previous WORD.
'gE', 'cgE', 'ygE', etc..
"""
- prev_end = event.current_buffer.document.find_previous_word_ending(count=event.arg, WORD=True)
- return TextObject(prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE)
-
- @text_object('g', 'm')
- def _(event):
- """
- Like g0, but half a screenwidth to the right. (Or as much as possible.)
- """
- w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
- buff = event.current_buffer
-
- if w and w.render_info:
- width = w.render_info.window_width
- start = buff.document.get_start_of_line_position(after_whitespace=False)
- start += int(min(width / 2, len(buff.document.current_line)))
-
- return TextObject(start, type=TextObjectType.INCLUSIVE)
- return TextObject(0)
-
- @text_object('G')
- def _(event):
- """
+ prev_end = event.current_buffer.document.find_previous_word_ending(count=event.arg, WORD=True)
+ return TextObject(prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE)
+
+ @text_object('g', 'm')
+ def _(event):
+ """
+ Like g0, but half a screenwidth to the right. (Or as much as possible.)
+ """
+ w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)
+ buff = event.current_buffer
+
+ if w and w.render_info:
+ width = w.render_info.window_width
+ start = buff.document.get_start_of_line_position(after_whitespace=False)
+ start += int(min(width / 2, len(buff.document.current_line)))
+
+ return TextObject(start, type=TextObjectType.INCLUSIVE)
+ return TextObject(0)
+
+ @text_object('G')
+ def _(event):
+ """
Go to the end of the document. (If no arg has been given.)
"""
- buf = event.current_buffer
- return TextObject(buf.document.translate_row_col_to_index(buf.document.line_count - 1, 0) -
- buf.cursor_position, type=TextObjectType.LINEWISE)
+ buf = event.current_buffer
+ return TextObject(buf.document.translate_row_col_to_index(buf.document.line_count - 1, 0) -
+ buf.cursor_position, type=TextObjectType.LINEWISE)
+
+ #
+ # *** Other ***
+ #
- #
- # *** Other ***
- #
-
@handle('G', filter=HasArg())
def _(event):
"""
@@ -1536,19 +1536,19 @@ def load_vi_bindings(get_search_state=None):
"""
event.current_buffer.go_to_history(event.arg - 1)
- for n in '123456789':
- @handle(n, filter=navigation_mode|selection_mode|operator_given)
- def _(event):
- """
- Always handle numberics in navigation mode as arg.
- """
+ for n in '123456789':
+ @handle(n, filter=navigation_mode|selection_mode|operator_given)
+ def _(event):
+ """
+ Always handle numberics in navigation mode as arg.
+ """
event.append_to_arg_count(event.data)
- @handle('0', filter=(navigation_mode|selection_mode|operator_given) & HasArg())
- def _(event):
- " Zero when an argument was already give. "
- event.append_to_arg_count(event.data)
-
+ @handle('0', filter=(navigation_mode|selection_mode|operator_given) & HasArg())
+ def _(event):
+ " Zero when an argument was already give. "
+ event.append_to_arg_count(event.data)
+
@handle(Keys.Any, filter=replace_mode)
def _(event):
"""
@@ -1556,104 +1556,104 @@ def load_vi_bindings(get_search_state=None):
"""
event.current_buffer.insert_text(event.data, overwrite=True)
- @handle(Keys.Any, filter=insert_multiple_mode,
- save_before=(lambda e: not e.is_repeat))
- def _(event):
- """
- Insert data at multiple cursor positions at once.
- (Usually a result of pressing 'I' or 'A' in block-selection mode.)
- """
- buff = event.current_buffer
- original_text = buff.text
-
- # Construct new text.
- text = []
- p = 0
-
- for p2 in buff.multiple_cursor_positions:
- text.append(original_text[p:p2])
- text.append(event.data)
- p = p2
-
- text.append(original_text[p:])
-
- # Shift all cursor positions.
- new_cursor_positions = [
- p + i + 1 for i, p in enumerate(buff.multiple_cursor_positions)]
-
- # Set result.
- buff.text = ''.join(text)
- buff.multiple_cursor_positions = new_cursor_positions
- buff.cursor_position += 1
-
- @handle(Keys.Backspace, filter=insert_multiple_mode)
- def _(event):
- " Backspace, using multiple cursors. "
- buff = event.current_buffer
- original_text = buff.text
-
- # Construct new text.
- deleted_something = False
- text = []
- p = 0
-
- for p2 in buff.multiple_cursor_positions:
- if p2 > 0 and original_text[p2 - 1] != '\n': # Don't delete across lines.
- text.append(original_text[p:p2 - 1])
- deleted_something = True
- else:
- text.append(original_text[p:p2])
- p = p2
-
- text.append(original_text[p:])
-
- if deleted_something:
- # Shift all cursor positions.
- lengths = [len(part) for part in text[:-1]]
- new_cursor_positions = list(accumulate(lengths))
-
- # Set result.
- buff.text = ''.join(text)
- buff.multiple_cursor_positions = new_cursor_positions
- buff.cursor_position -= 1
- else:
- event.cli.output.bell()
-
- @handle(Keys.Delete, filter=insert_multiple_mode)
- def _(event):
- " Delete, using multiple cursors. "
- buff = event.current_buffer
- original_text = buff.text
-
- # Construct new text.
- deleted_something = False
- text = []
- new_cursor_positions = []
- p = 0
-
- for p2 in buff.multiple_cursor_positions:
- text.append(original_text[p:p2])
- if p2 >= len(original_text) or original_text[p2] == '\n':
- # Don't delete across lines.
- p = p2
- else:
- p = p2 + 1
- deleted_something = True
-
- text.append(original_text[p:])
-
- if deleted_something:
- # Shift all cursor positions.
- lengths = [len(part) for part in text[:-1]]
- new_cursor_positions = list(accumulate(lengths))
-
- # Set result.
- buff.text = ''.join(text)
- buff.multiple_cursor_positions = new_cursor_positions
- else:
- event.cli.output.bell()
-
-
+ @handle(Keys.Any, filter=insert_multiple_mode,
+ save_before=(lambda e: not e.is_repeat))
+ def _(event):
+ """
+ Insert data at multiple cursor positions at once.
+ (Usually a result of pressing 'I' or 'A' in block-selection mode.)
+ """
+ buff = event.current_buffer
+ original_text = buff.text
+
+ # Construct new text.
+ text = []
+ p = 0
+
+ for p2 in buff.multiple_cursor_positions:
+ text.append(original_text[p:p2])
+ text.append(event.data)
+ p = p2
+
+ text.append(original_text[p:])
+
+ # Shift all cursor positions.
+ new_cursor_positions = [
+ p + i + 1 for i, p in enumerate(buff.multiple_cursor_positions)]
+
+ # Set result.
+ buff.text = ''.join(text)
+ buff.multiple_cursor_positions = new_cursor_positions
+ buff.cursor_position += 1
+
+ @handle(Keys.Backspace, filter=insert_multiple_mode)
+ def _(event):
+ " Backspace, using multiple cursors. "
+ buff = event.current_buffer
+ original_text = buff.text
+
+ # Construct new text.
+ deleted_something = False
+ text = []
+ p = 0
+
+ for p2 in buff.multiple_cursor_positions:
+ if p2 > 0 and original_text[p2 - 1] != '\n': # Don't delete across lines.
+ text.append(original_text[p:p2 - 1])
+ deleted_something = True
+ else:
+ text.append(original_text[p:p2])
+ p = p2
+
+ text.append(original_text[p:])
+
+ if deleted_something:
+ # Shift all cursor positions.
+ lengths = [len(part) for part in text[:-1]]
+ new_cursor_positions = list(accumulate(lengths))
+
+ # Set result.
+ buff.text = ''.join(text)
+ buff.multiple_cursor_positions = new_cursor_positions
+ buff.cursor_position -= 1
+ else:
+ event.cli.output.bell()
+
+ @handle(Keys.Delete, filter=insert_multiple_mode)
+ def _(event):
+ " Delete, using multiple cursors. "
+ buff = event.current_buffer
+ original_text = buff.text
+
+ # Construct new text.
+ deleted_something = False
+ text = []
+ new_cursor_positions = []
+ p = 0
+
+ for p2 in buff.multiple_cursor_positions:
+ text.append(original_text[p:p2])
+ if p2 >= len(original_text) or original_text[p2] == '\n':
+ # Don't delete across lines.
+ p = p2
+ else:
+ p = p2 + 1
+ deleted_something = True
+
+ text.append(original_text[p:])
+
+ if deleted_something:
+ # Shift all cursor positions.
+ lengths = [len(part) for part in text[:-1]]
+ new_cursor_positions = list(accumulate(lengths))
+
+ # Set result.
+ buff.text = ''.join(text)
+ buff.multiple_cursor_positions = new_cursor_positions
+ else:
+ event.cli.output.bell()
+
+
@handle(Keys.ControlX, Keys.ControlL, filter=insert_mode)
def _(event):
"""
@@ -1670,50 +1670,50 @@ def load_vi_bindings(get_search_state=None):
# TODO
pass
- @handle(Keys.ControlK, filter=insert_mode|replace_mode)
- def _(event):
- " Go into digraph mode. "
- event.cli.vi_state.waiting_for_digraph = True
-
- @Condition
- def digraph_symbol_1_given(cli):
- return cli.vi_state.digraph_symbol1 is not None
-
- @handle(Keys.Any, filter=digraph_mode & ~digraph_symbol_1_given)
- def _(event):
- event.cli.vi_state.digraph_symbol1 = event.data
-
- @handle(Keys.Any, filter=digraph_mode & digraph_symbol_1_given)
- def _(event):
- " Insert digraph. "
- try:
- # Lookup.
- code = (event.cli.vi_state.digraph_symbol1, event.data)
- if code not in DIGRAPHS:
- code = code[::-1] # Try reversing.
- symbol = DIGRAPHS[code]
- except KeyError:
- # Unkown digraph.
- event.cli.output.bell()
- else:
- # Insert digraph.
- overwrite = event.cli.vi_state.input_mode == InputMode.REPLACE
- event.current_buffer.insert_text(
- six.unichr(symbol), overwrite=overwrite)
- event.cli.vi_state.waiting_for_digraph = False
- finally:
- event.cli.vi_state.waiting_for_digraph = False
- event.cli.vi_state.digraph_symbol1 = None
-
+ @handle(Keys.ControlK, filter=insert_mode|replace_mode)
+ def _(event):
+ " Go into digraph mode. "
+ event.cli.vi_state.waiting_for_digraph = True
+
+ @Condition
+ def digraph_symbol_1_given(cli):
+ return cli.vi_state.digraph_symbol1 is not None
+
+ @handle(Keys.Any, filter=digraph_mode & ~digraph_symbol_1_given)
+ def _(event):
+ event.cli.vi_state.digraph_symbol1 = event.data
+
+ @handle(Keys.Any, filter=digraph_mode & digraph_symbol_1_given)
+ def _(event):
+ " Insert digraph. "
+ try:
+ # Lookup.
+ code = (event.cli.vi_state.digraph_symbol1, event.data)
+ if code not in DIGRAPHS:
+ code = code[::-1] # Try reversing.
+ symbol = DIGRAPHS[code]
+ except KeyError:
+ # Unkown digraph.
+ event.cli.output.bell()
+ else:
+ # Insert digraph.
+ overwrite = event.cli.vi_state.input_mode == InputMode.REPLACE
+ event.current_buffer.insert_text(
+ six.unichr(symbol), overwrite=overwrite)
+ event.cli.vi_state.waiting_for_digraph = False
+ finally:
+ event.cli.vi_state.waiting_for_digraph = False
+ event.cli.vi_state.digraph_symbol1 = None
+
return registry
-
+
def load_vi_open_in_editor_bindings():
"""
Pressing 'v' in navigation mode will open the buffer in an external editor.
"""
registry = Registry()
- navigation_mode = ViNavigationMode()
+ navigation_mode = ViNavigationMode()
registry.add_binding('v', filter=navigation_mode)(
get_by_name('edit-and-execute-command'))
@@ -1725,7 +1725,7 @@ def load_vi_system_bindings():
handle = registry.add_binding
has_focus = filters.HasFocus(SYSTEM_BUFFER)
- navigation_mode = ViNavigationMode()
+ navigation_mode = ViNavigationMode()
@handle('!', filter=~has_focus & navigation_mode)
def _(event):
@@ -1733,7 +1733,7 @@ def load_vi_system_bindings():
'!' opens the system prompt.
"""
event.cli.push_focus(SYSTEM_BUFFER)
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle(Keys.Escape, filter=has_focus)
@handle(Keys.ControlC, filter=has_focus)
@@ -1741,7 +1741,7 @@ def load_vi_system_bindings():
"""
Cancel system prompt.
"""
- event.cli.vi_state.input_mode = InputMode.NAVIGATION
+ event.cli.vi_state.input_mode = InputMode.NAVIGATION
event.cli.buffers[SYSTEM_BUFFER].reset()
event.cli.pop_focus()
@@ -1750,7 +1750,7 @@ def load_vi_system_bindings():
"""
Run system command.
"""
- event.cli.vi_state.input_mode = InputMode.NAVIGATION
+ event.cli.vi_state.input_mode = InputMode.NAVIGATION
system_buffer = event.cli.buffers[SYSTEM_BUFFER]
event.cli.run_system_command(system_buffer.text)
@@ -1773,8 +1773,8 @@ def load_vi_search_bindings(get_search_state=None,
handle = registry.add_binding
has_focus = filters.HasFocus(search_buffer_name)
- navigation_mode = ViNavigationMode()
- selection_mode = ViSelectionMode()
+ navigation_mode = ViNavigationMode()
+ selection_mode = ViSelectionMode()
reverse_vi_search_direction = Condition(
lambda cli: cli.application.reverse_vi_search_direction(cli))
@@ -1788,7 +1788,7 @@ def load_vi_search_bindings(get_search_state=None,
"""
# Set the ViState.
get_search_state(event.cli).direction = IncrementalSearchDirection.FORWARD
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
# Focus search buffer.
event.cli.push_focus(search_buffer_name)
@@ -1805,7 +1805,7 @@ def load_vi_search_bindings(get_search_state=None,
# Focus search buffer.
event.cli.push_focus(search_buffer_name)
- event.cli.vi_state.input_mode = InputMode.INSERT
+ event.cli.vi_state.input_mode = InputMode.INSERT
@handle(Keys.ControlJ, filter=has_focus)
@handle(Keys.Escape, filter=has_focus)
@@ -1828,44 +1828,44 @@ def load_vi_search_bindings(get_search_state=None,
search_buffer.reset()
# Focus previous document again.
- event.cli.vi_state.input_mode = InputMode.NAVIGATION
+ event.cli.vi_state.input_mode = InputMode.NAVIGATION
event.cli.pop_focus()
- def incremental_search(cli, direction, count=1):
- " Apply search, but keep search buffer focussed. "
- # Update search_state.
- search_state = get_search_state(cli)
- direction_changed = search_state.direction != direction
-
- search_state.text = cli.buffers[search_buffer_name].text
- search_state.direction = direction
-
- # Apply search to current buffer.
- if not direction_changed:
- input_buffer = cli.buffers.previous(cli)
- input_buffer.apply_search(search_state,
- include_current_position=False, count=count)
-
- @handle(Keys.ControlR, filter=has_focus)
- def _(event):
- incremental_search(event.cli, IncrementalSearchDirection.BACKWARD, count=event.arg)
-
- @handle(Keys.ControlS, filter=has_focus)
- def _(event):
- incremental_search(event.cli, IncrementalSearchDirection.FORWARD, count=event.arg)
-
+ def incremental_search(cli, direction, count=1):
+ " Apply search, but keep search buffer focussed. "
+ # Update search_state.
+ search_state = get_search_state(cli)
+ direction_changed = search_state.direction != direction
+
+ search_state.text = cli.buffers[search_buffer_name].text
+ search_state.direction = direction
+
+ # Apply search to current buffer.
+ if not direction_changed:
+ input_buffer = cli.buffers.previous(cli)
+ input_buffer.apply_search(search_state,
+ include_current_position=False, count=count)
+
+ @handle(Keys.ControlR, filter=has_focus)
+ def _(event):
+ incremental_search(event.cli, IncrementalSearchDirection.BACKWARD, count=event.arg)
+
+ @handle(Keys.ControlS, filter=has_focus)
+ def _(event):
+ incremental_search(event.cli, IncrementalSearchDirection.FORWARD, count=event.arg)
+
def search_buffer_is_empty(cli):
""" Returns True when the search buffer is empty. """
return cli.buffers[search_buffer_name].text == ''
@handle(Keys.ControlC, filter=has_focus)
- @handle(Keys.ControlH, filter=has_focus & Condition(search_buffer_is_empty))
+ @handle(Keys.ControlH, filter=has_focus & Condition(search_buffer_is_empty))
@handle(Keys.Backspace, filter=has_focus & Condition(search_buffer_is_empty))
def _(event):
"""
Cancel search.
"""
- event.cli.vi_state.input_mode = InputMode.NAVIGATION
+ event.cli.vi_state.input_mode = InputMode.NAVIGATION
event.cli.pop_focus()
event.cli.buffers[search_buffer_name].reset()
@@ -1889,15 +1889,15 @@ def load_extra_vi_page_navigation_bindings():
handle(Keys.ControlY)(scroll_one_line_up)
handle(Keys.PageDown)(scroll_page_down)
handle(Keys.PageUp)(scroll_page_up)
-
+
return registry
-
-
-class ViStateFilter(Filter):
- " Deprecated! "
- def __init__(self, get_vi_state, mode):
- self.get_vi_state = get_vi_state
- self.mode = mode
-
- def __call__(self, cli):
- return self.get_vi_state(cli).input_mode == self.mode
+
+
+class ViStateFilter(Filter):
+ " Deprecated! "
+ def __init__(self, get_vi_state, mode):
+ self.get_vi_state = get_vi_state
+ self.mode = mode
+
+ def __call__(self, cli):
+ return self.get_vi_state(cli).input_mode == self.mode
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/digraphs.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/digraphs.py
index 3301c507d3..36c6b15103 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/digraphs.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/digraphs.py
@@ -1,1378 +1,1378 @@
-# encoding: utf-8
-from __future__ import unicode_literals
-"""
-Vi Digraphs.
-This is a list of special characters that can be inserted in Vi insert mode by
-pressing Control-K followed by to normal characters.
-
-Taken from Neovim and translated to Python:
-https://raw.githubusercontent.com/neovim/neovim/master/src/nvim/digraph.c
-"""
-__all__ = ('DIGRAPHS', )
-
-# digraphs for Unicode from RFC1345
-# (also work for ISO-8859-1 aka latin1)
-DIGRAPHS = {
- ('N', 'U'): 0x00,
- ('S', 'H'): 0x01,
- ('S', 'X'): 0x02,
- ('E', 'X'): 0x03,
- ('E', 'T'): 0x04,
- ('E', 'Q'): 0x05,
- ('A', 'K'): 0x06,
- ('B', 'L'): 0x07,
- ('B', 'S'): 0x08,
- ('H', 'T'): 0x09,
- ('L', 'F'): 0x0a,
- ('V', 'T'): 0x0b,
- ('F', 'F'): 0x0c,
- ('C', 'R'): 0x0d,
- ('S', 'O'): 0x0e,
- ('S', 'I'): 0x0f,
- ('D', 'L'): 0x10,
- ('D', '1'): 0x11,
- ('D', '2'): 0x12,
- ('D', '3'): 0x13,
- ('D', '4'): 0x14,
- ('N', 'K'): 0x15,
- ('S', 'Y'): 0x16,
- ('E', 'B'): 0x17,
- ('C', 'N'): 0x18,
- ('E', 'M'): 0x19,
- ('S', 'B'): 0x1a,
- ('E', 'C'): 0x1b,
- ('F', 'S'): 0x1c,
- ('G', 'S'): 0x1d,
- ('R', 'S'): 0x1e,
- ('U', 'S'): 0x1f,
- ('S', 'P'): 0x20,
- ('N', 'b'): 0x23,
- ('D', 'O'): 0x24,
- ('A', 't'): 0x40,
- ('<', '('): 0x5b,
- ('/', '/'): 0x5c,
- (')', '>'): 0x5d,
- ('\'', '>'): 0x5e,
- ('\'', '!'): 0x60,
- ('(', '!'): 0x7b,
- ('!', '!'): 0x7c,
- ('!', ')'): 0x7d,
- ('\'', '?'): 0x7e,
- ('D', 'T'): 0x7f,
- ('P', 'A'): 0x80,
- ('H', 'O'): 0x81,
- ('B', 'H'): 0x82,
- ('N', 'H'): 0x83,
- ('I', 'N'): 0x84,
- ('N', 'L'): 0x85,
- ('S', 'A'): 0x86,
- ('E', 'S'): 0x87,
- ('H', 'S'): 0x88,
- ('H', 'J'): 0x89,
- ('V', 'S'): 0x8a,
- ('P', 'D'): 0x8b,
- ('P', 'U'): 0x8c,
- ('R', 'I'): 0x8d,
- ('S', '2'): 0x8e,
- ('S', '3'): 0x8f,
- ('D', 'C'): 0x90,
- ('P', '1'): 0x91,
- ('P', '2'): 0x92,
- ('T', 'S'): 0x93,
- ('C', 'C'): 0x94,
- ('M', 'W'): 0x95,
- ('S', 'G'): 0x96,
- ('E', 'G'): 0x97,
- ('S', 'S'): 0x98,
- ('G', 'C'): 0x99,
- ('S', 'C'): 0x9a,
- ('C', 'I'): 0x9b,
- ('S', 'T'): 0x9c,
- ('O', 'C'): 0x9d,
- ('P', 'M'): 0x9e,
- ('A', 'C'): 0x9f,
- ('N', 'S'): 0xa0,
- ('!', 'I'): 0xa1,
- ('C', 't'): 0xa2,
- ('P', 'd'): 0xa3,
- ('C', 'u'): 0xa4,
- ('Y', 'e'): 0xa5,
- ('B', 'B'): 0xa6,
- ('S', 'E'): 0xa7,
- ('\'', ':'): 0xa8,
- ('C', 'o'): 0xa9,
- ('-', 'a'): 0xaa,
- ('<', '<'): 0xab,
- ('N', 'O'): 0xac,
- ('-', '-'): 0xad,
- ('R', 'g'): 0xae,
- ('\'', 'm'): 0xaf,
- ('D', 'G'): 0xb0,
- ('+', '-'): 0xb1,
- ('2', 'S'): 0xb2,
- ('3', 'S'): 0xb3,
- ('\'', '\''): 0xb4,
- ('M', 'y'): 0xb5,
- ('P', 'I'): 0xb6,
- ('.', 'M'): 0xb7,
- ('\'', ','): 0xb8,
- ('1', 'S'): 0xb9,
- ('-', 'o'): 0xba,
- ('>', '>'): 0xbb,
- ('1', '4'): 0xbc,
- ('1', '2'): 0xbd,
- ('3', '4'): 0xbe,
- ('?', 'I'): 0xbf,
- ('A', '!'): 0xc0,
- ('A', '\''): 0xc1,
- ('A', '>'): 0xc2,
- ('A', '?'): 0xc3,
- ('A', ':'): 0xc4,
- ('A', 'A'): 0xc5,
- ('A', 'E'): 0xc6,
- ('C', ','): 0xc7,
- ('E', '!'): 0xc8,
- ('E', '\''): 0xc9,
- ('E', '>'): 0xca,
- ('E', ':'): 0xcb,
- ('I', '!'): 0xcc,
- ('I', '\''): 0xcd,
- ('I', '>'): 0xce,
- ('I', ':'): 0xcf,
- ('D', '-'): 0xd0,
- ('N', '?'): 0xd1,
- ('O', '!'): 0xd2,
- ('O', '\''): 0xd3,
- ('O', '>'): 0xd4,
- ('O', '?'): 0xd5,
- ('O', ':'): 0xd6,
- ('*', 'X'): 0xd7,
- ('O', '/'): 0xd8,
- ('U', '!'): 0xd9,
- ('U', '\''): 0xda,
- ('U', '>'): 0xdb,
- ('U', ':'): 0xdc,
- ('Y', '\''): 0xdd,
- ('T', 'H'): 0xde,
- ('s', 's'): 0xdf,
- ('a', '!'): 0xe0,
- ('a', '\''): 0xe1,
- ('a', '>'): 0xe2,
- ('a', '?'): 0xe3,
- ('a', ':'): 0xe4,
- ('a', 'a'): 0xe5,
- ('a', 'e'): 0xe6,
- ('c', ','): 0xe7,
- ('e', '!'): 0xe8,
- ('e', '\''): 0xe9,
- ('e', '>'): 0xea,
- ('e', ':'): 0xeb,
- ('i', '!'): 0xec,
- ('i', '\''): 0xed,
- ('i', '>'): 0xee,
- ('i', ':'): 0xef,
- ('d', '-'): 0xf0,
- ('n', '?'): 0xf1,
- ('o', '!'): 0xf2,
- ('o', '\''): 0xf3,
- ('o', '>'): 0xf4,
- ('o', '?'): 0xf5,
- ('o', ':'): 0xf6,
- ('-', ':'): 0xf7,
- ('o', '/'): 0xf8,
- ('u', '!'): 0xf9,
- ('u', '\''): 0xfa,
- ('u', '>'): 0xfb,
- ('u', ':'): 0xfc,
- ('y', '\''): 0xfd,
- ('t', 'h'): 0xfe,
- ('y', ':'): 0xff,
-
- ('A', '-'): 0x0100,
- ('a', '-'): 0x0101,
- ('A', '('): 0x0102,
- ('a', '('): 0x0103,
- ('A', ';'): 0x0104,
- ('a', ';'): 0x0105,
- ('C', '\''): 0x0106,
- ('c', '\''): 0x0107,
- ('C', '>'): 0x0108,
- ('c', '>'): 0x0109,
- ('C', '.'): 0x010a,
- ('c', '.'): 0x010b,
- ('C', '<'): 0x010c,
- ('c', '<'): 0x010d,
- ('D', '<'): 0x010e,
- ('d', '<'): 0x010f,
- ('D', '/'): 0x0110,
- ('d', '/'): 0x0111,
- ('E', '-'): 0x0112,
- ('e', '-'): 0x0113,
- ('E', '('): 0x0114,
- ('e', '('): 0x0115,
- ('E', '.'): 0x0116,
- ('e', '.'): 0x0117,
- ('E', ';'): 0x0118,
- ('e', ';'): 0x0119,
- ('E', '<'): 0x011a,
- ('e', '<'): 0x011b,
- ('G', '>'): 0x011c,
- ('g', '>'): 0x011d,
- ('G', '('): 0x011e,
- ('g', '('): 0x011f,
- ('G', '.'): 0x0120,
- ('g', '.'): 0x0121,
- ('G', ','): 0x0122,
- ('g', ','): 0x0123,
- ('H', '>'): 0x0124,
- ('h', '>'): 0x0125,
- ('H', '/'): 0x0126,
- ('h', '/'): 0x0127,
- ('I', '?'): 0x0128,
- ('i', '?'): 0x0129,
- ('I', '-'): 0x012a,
- ('i', '-'): 0x012b,
- ('I', '('): 0x012c,
- ('i', '('): 0x012d,
- ('I', ';'): 0x012e,
- ('i', ';'): 0x012f,
- ('I', '.'): 0x0130,
- ('i', '.'): 0x0131,
- ('I', 'J'): 0x0132,
- ('i', 'j'): 0x0133,
- ('J', '>'): 0x0134,
- ('j', '>'): 0x0135,
- ('K', ','): 0x0136,
- ('k', ','): 0x0137,
- ('k', 'k'): 0x0138,
- ('L', '\''): 0x0139,
- ('l', '\''): 0x013a,
- ('L', ','): 0x013b,
- ('l', ','): 0x013c,
- ('L', '<'): 0x013d,
- ('l', '<'): 0x013e,
- ('L', '.'): 0x013f,
- ('l', '.'): 0x0140,
- ('L', '/'): 0x0141,
- ('l', '/'): 0x0142,
- ('N', '\''): 0x0143,
- ('n', '\''): 0x0144,
- ('N', ','): 0x0145,
- ('n', ','): 0x0146,
- ('N', '<'): 0x0147,
- ('n', '<'): 0x0148,
- ('\'', 'n'): 0x0149,
- ('N', 'G'): 0x014a,
- ('n', 'g'): 0x014b,
- ('O', '-'): 0x014c,
- ('o', '-'): 0x014d,
- ('O', '('): 0x014e,
- ('o', '('): 0x014f,
- ('O', '"'): 0x0150,
- ('o', '"'): 0x0151,
- ('O', 'E'): 0x0152,
- ('o', 'e'): 0x0153,
- ('R', '\''): 0x0154,
- ('r', '\''): 0x0155,
- ('R', ','): 0x0156,
- ('r', ','): 0x0157,
- ('R', '<'): 0x0158,
- ('r', '<'): 0x0159,
- ('S', '\''): 0x015a,
- ('s', '\''): 0x015b,
- ('S', '>'): 0x015c,
- ('s', '>'): 0x015d,
- ('S', ','): 0x015e,
- ('s', ','): 0x015f,
- ('S', '<'): 0x0160,
- ('s', '<'): 0x0161,
- ('T', ','): 0x0162,
- ('t', ','): 0x0163,
- ('T', '<'): 0x0164,
- ('t', '<'): 0x0165,
- ('T', '/'): 0x0166,
- ('t', '/'): 0x0167,
- ('U', '?'): 0x0168,
- ('u', '?'): 0x0169,
- ('U', '-'): 0x016a,
- ('u', '-'): 0x016b,
- ('U', '('): 0x016c,
- ('u', '('): 0x016d,
- ('U', '0'): 0x016e,
- ('u', '0'): 0x016f,
- ('U', '"'): 0x0170,
- ('u', '"'): 0x0171,
- ('U', ';'): 0x0172,
- ('u', ';'): 0x0173,
- ('W', '>'): 0x0174,
- ('w', '>'): 0x0175,
- ('Y', '>'): 0x0176,
- ('y', '>'): 0x0177,
- ('Y', ':'): 0x0178,
- ('Z', '\''): 0x0179,
- ('z', '\''): 0x017a,
- ('Z', '.'): 0x017b,
- ('z', '.'): 0x017c,
- ('Z', '<'): 0x017d,
- ('z', '<'): 0x017e,
- ('O', '9'): 0x01a0,
- ('o', '9'): 0x01a1,
- ('O', 'I'): 0x01a2,
- ('o', 'i'): 0x01a3,
- ('y', 'r'): 0x01a6,
- ('U', '9'): 0x01af,
- ('u', '9'): 0x01b0,
- ('Z', '/'): 0x01b5,
- ('z', '/'): 0x01b6,
- ('E', 'D'): 0x01b7,
- ('A', '<'): 0x01cd,
- ('a', '<'): 0x01ce,
- ('I', '<'): 0x01cf,
- ('i', '<'): 0x01d0,
- ('O', '<'): 0x01d1,
- ('o', '<'): 0x01d2,
- ('U', '<'): 0x01d3,
- ('u', '<'): 0x01d4,
- ('A', '1'): 0x01de,
- ('a', '1'): 0x01df,
- ('A', '7'): 0x01e0,
- ('a', '7'): 0x01e1,
- ('A', '3'): 0x01e2,
- ('a', '3'): 0x01e3,
- ('G', '/'): 0x01e4,
- ('g', '/'): 0x01e5,
- ('G', '<'): 0x01e6,
- ('g', '<'): 0x01e7,
- ('K', '<'): 0x01e8,
- ('k', '<'): 0x01e9,
- ('O', ';'): 0x01ea,
- ('o', ';'): 0x01eb,
- ('O', '1'): 0x01ec,
- ('o', '1'): 0x01ed,
- ('E', 'Z'): 0x01ee,
- ('e', 'z'): 0x01ef,
- ('j', '<'): 0x01f0,
- ('G', '\''): 0x01f4,
- ('g', '\''): 0x01f5,
- (';', 'S'): 0x02bf,
- ('\'', '<'): 0x02c7,
- ('\'', '('): 0x02d8,
- ('\'', '.'): 0x02d9,
- ('\'', '0'): 0x02da,
- ('\'', ';'): 0x02db,
- ('\'', '"'): 0x02dd,
- ('A', '%'): 0x0386,
- ('E', '%'): 0x0388,
- ('Y', '%'): 0x0389,
- ('I', '%'): 0x038a,
- ('O', '%'): 0x038c,
- ('U', '%'): 0x038e,
- ('W', '%'): 0x038f,
- ('i', '3'): 0x0390,
- ('A', '*'): 0x0391,
- ('B', '*'): 0x0392,
- ('G', '*'): 0x0393,
- ('D', '*'): 0x0394,
- ('E', '*'): 0x0395,
- ('Z', '*'): 0x0396,
- ('Y', '*'): 0x0397,
- ('H', '*'): 0x0398,
- ('I', '*'): 0x0399,
- ('K', '*'): 0x039a,
- ('L', '*'): 0x039b,
- ('M', '*'): 0x039c,
- ('N', '*'): 0x039d,
- ('C', '*'): 0x039e,
- ('O', '*'): 0x039f,
- ('P', '*'): 0x03a0,
- ('R', '*'): 0x03a1,
- ('S', '*'): 0x03a3,
- ('T', '*'): 0x03a4,
- ('U', '*'): 0x03a5,
- ('F', '*'): 0x03a6,
- ('X', '*'): 0x03a7,
- ('Q', '*'): 0x03a8,
- ('W', '*'): 0x03a9,
- ('J', '*'): 0x03aa,
- ('V', '*'): 0x03ab,
- ('a', '%'): 0x03ac,
- ('e', '%'): 0x03ad,
- ('y', '%'): 0x03ae,
- ('i', '%'): 0x03af,
- ('u', '3'): 0x03b0,
- ('a', '*'): 0x03b1,
- ('b', '*'): 0x03b2,
- ('g', '*'): 0x03b3,
- ('d', '*'): 0x03b4,
- ('e', '*'): 0x03b5,
- ('z', '*'): 0x03b6,
- ('y', '*'): 0x03b7,
- ('h', '*'): 0x03b8,
- ('i', '*'): 0x03b9,
- ('k', '*'): 0x03ba,
- ('l', '*'): 0x03bb,
- ('m', '*'): 0x03bc,
- ('n', '*'): 0x03bd,
- ('c', '*'): 0x03be,
- ('o', '*'): 0x03bf,
- ('p', '*'): 0x03c0,
- ('r', '*'): 0x03c1,
- ('*', 's'): 0x03c2,
- ('s', '*'): 0x03c3,
- ('t', '*'): 0x03c4,
- ('u', '*'): 0x03c5,
- ('f', '*'): 0x03c6,
- ('x', '*'): 0x03c7,
- ('q', '*'): 0x03c8,
- ('w', '*'): 0x03c9,
- ('j', '*'): 0x03ca,
- ('v', '*'): 0x03cb,
- ('o', '%'): 0x03cc,
- ('u', '%'): 0x03cd,
- ('w', '%'): 0x03ce,
- ('\'', 'G'): 0x03d8,
- (',', 'G'): 0x03d9,
- ('T', '3'): 0x03da,
- ('t', '3'): 0x03db,
- ('M', '3'): 0x03dc,
- ('m', '3'): 0x03dd,
- ('K', '3'): 0x03de,
- ('k', '3'): 0x03df,
- ('P', '3'): 0x03e0,
- ('p', '3'): 0x03e1,
- ('\'', '%'): 0x03f4,
- ('j', '3'): 0x03f5,
- ('I', 'O'): 0x0401,
- ('D', '%'): 0x0402,
- ('G', '%'): 0x0403,
- ('I', 'E'): 0x0404,
- ('D', 'S'): 0x0405,
- ('I', 'I'): 0x0406,
- ('Y', 'I'): 0x0407,
- ('J', '%'): 0x0408,
- ('L', 'J'): 0x0409,
- ('N', 'J'): 0x040a,
- ('T', 's'): 0x040b,
- ('K', 'J'): 0x040c,
- ('V', '%'): 0x040e,
- ('D', 'Z'): 0x040f,
- ('A', '='): 0x0410,
- ('B', '='): 0x0411,
- ('V', '='): 0x0412,
- ('G', '='): 0x0413,
- ('D', '='): 0x0414,
- ('E', '='): 0x0415,
- ('Z', '%'): 0x0416,
- ('Z', '='): 0x0417,
- ('I', '='): 0x0418,
- ('J', '='): 0x0419,
- ('K', '='): 0x041a,
- ('L', '='): 0x041b,
- ('M', '='): 0x041c,
- ('N', '='): 0x041d,
- ('O', '='): 0x041e,
- ('P', '='): 0x041f,
- ('R', '='): 0x0420,
- ('S', '='): 0x0421,
- ('T', '='): 0x0422,
- ('U', '='): 0x0423,
- ('F', '='): 0x0424,
- ('H', '='): 0x0425,
- ('C', '='): 0x0426,
- ('C', '%'): 0x0427,
- ('S', '%'): 0x0428,
- ('S', 'c'): 0x0429,
- ('=', '"'): 0x042a,
- ('Y', '='): 0x042b,
- ('%', '"'): 0x042c,
- ('J', 'E'): 0x042d,
- ('J', 'U'): 0x042e,
- ('J', 'A'): 0x042f,
- ('a', '='): 0x0430,
- ('b', '='): 0x0431,
- ('v', '='): 0x0432,
- ('g', '='): 0x0433,
- ('d', '='): 0x0434,
- ('e', '='): 0x0435,
- ('z', '%'): 0x0436,
- ('z', '='): 0x0437,
- ('i', '='): 0x0438,
- ('j', '='): 0x0439,
- ('k', '='): 0x043a,
- ('l', '='): 0x043b,
- ('m', '='): 0x043c,
- ('n', '='): 0x043d,
- ('o', '='): 0x043e,
- ('p', '='): 0x043f,
- ('r', '='): 0x0440,
- ('s', '='): 0x0441,
- ('t', '='): 0x0442,
- ('u', '='): 0x0443,
- ('f', '='): 0x0444,
- ('h', '='): 0x0445,
- ('c', '='): 0x0446,
- ('c', '%'): 0x0447,
- ('s', '%'): 0x0448,
- ('s', 'c'): 0x0449,
- ('=', '\''): 0x044a,
- ('y', '='): 0x044b,
- ('%', '\''): 0x044c,
- ('j', 'e'): 0x044d,
- ('j', 'u'): 0x044e,
- ('j', 'a'): 0x044f,
- ('i', 'o'): 0x0451,
- ('d', '%'): 0x0452,
- ('g', '%'): 0x0453,
- ('i', 'e'): 0x0454,
- ('d', 's'): 0x0455,
- ('i', 'i'): 0x0456,
- ('y', 'i'): 0x0457,
- ('j', '%'): 0x0458,
- ('l', 'j'): 0x0459,
- ('n', 'j'): 0x045a,
- ('t', 's'): 0x045b,
- ('k', 'j'): 0x045c,
- ('v', '%'): 0x045e,
- ('d', 'z'): 0x045f,
- ('Y', '3'): 0x0462,
- ('y', '3'): 0x0463,
- ('O', '3'): 0x046a,
- ('o', '3'): 0x046b,
- ('F', '3'): 0x0472,
- ('f', '3'): 0x0473,
- ('V', '3'): 0x0474,
- ('v', '3'): 0x0475,
- ('C', '3'): 0x0480,
- ('c', '3'): 0x0481,
- ('G', '3'): 0x0490,
- ('g', '3'): 0x0491,
- ('A', '+'): 0x05d0,
- ('B', '+'): 0x05d1,
- ('G', '+'): 0x05d2,
- ('D', '+'): 0x05d3,
- ('H', '+'): 0x05d4,
- ('W', '+'): 0x05d5,
- ('Z', '+'): 0x05d6,
- ('X', '+'): 0x05d7,
- ('T', 'j'): 0x05d8,
- ('J', '+'): 0x05d9,
- ('K', '%'): 0x05da,
- ('K', '+'): 0x05db,
- ('L', '+'): 0x05dc,
- ('M', '%'): 0x05dd,
- ('M', '+'): 0x05de,
- ('N', '%'): 0x05df,
- ('N', '+'): 0x05e0,
- ('S', '+'): 0x05e1,
- ('E', '+'): 0x05e2,
- ('P', '%'): 0x05e3,
- ('P', '+'): 0x05e4,
- ('Z', 'j'): 0x05e5,
- ('Z', 'J'): 0x05e6,
- ('Q', '+'): 0x05e7,
- ('R', '+'): 0x05e8,
- ('S', 'h'): 0x05e9,
- ('T', '+'): 0x05ea,
- (',', '+'): 0x060c,
- (';', '+'): 0x061b,
- ('?', '+'): 0x061f,
- ('H', '\''): 0x0621,
- ('a', 'M'): 0x0622,
- ('a', 'H'): 0x0623,
- ('w', 'H'): 0x0624,
- ('a', 'h'): 0x0625,
- ('y', 'H'): 0x0626,
- ('a', '+'): 0x0627,
- ('b', '+'): 0x0628,
- ('t', 'm'): 0x0629,
- ('t', '+'): 0x062a,
- ('t', 'k'): 0x062b,
- ('g', '+'): 0x062c,
- ('h', 'k'): 0x062d,
- ('x', '+'): 0x062e,
- ('d', '+'): 0x062f,
- ('d', 'k'): 0x0630,
- ('r', '+'): 0x0631,
- ('z', '+'): 0x0632,
- ('s', '+'): 0x0633,
- ('s', 'n'): 0x0634,
- ('c', '+'): 0x0635,
- ('d', 'd'): 0x0636,
- ('t', 'j'): 0x0637,
- ('z', 'H'): 0x0638,
- ('e', '+'): 0x0639,
- ('i', '+'): 0x063a,
- ('+', '+'): 0x0640,
- ('f', '+'): 0x0641,
- ('q', '+'): 0x0642,
- ('k', '+'): 0x0643,
- ('l', '+'): 0x0644,
- ('m', '+'): 0x0645,
- ('n', '+'): 0x0646,
- ('h', '+'): 0x0647,
- ('w', '+'): 0x0648,
- ('j', '+'): 0x0649,
- ('y', '+'): 0x064a,
- (':', '+'): 0x064b,
- ('"', '+'): 0x064c,
- ('=', '+'): 0x064d,
- ('/', '+'): 0x064e,
- ('\'', '+'): 0x064f,
- ('1', '+'): 0x0650,
- ('3', '+'): 0x0651,
- ('0', '+'): 0x0652,
- ('a', 'S'): 0x0670,
- ('p', '+'): 0x067e,
- ('v', '+'): 0x06a4,
- ('g', 'f'): 0x06af,
- ('0', 'a'): 0x06f0,
- ('1', 'a'): 0x06f1,
- ('2', 'a'): 0x06f2,
- ('3', 'a'): 0x06f3,
- ('4', 'a'): 0x06f4,
- ('5', 'a'): 0x06f5,
- ('6', 'a'): 0x06f6,
- ('7', 'a'): 0x06f7,
- ('8', 'a'): 0x06f8,
- ('9', 'a'): 0x06f9,
- ('B', '.'): 0x1e02,
- ('b', '.'): 0x1e03,
- ('B', '_'): 0x1e06,
- ('b', '_'): 0x1e07,
- ('D', '.'): 0x1e0a,
- ('d', '.'): 0x1e0b,
- ('D', '_'): 0x1e0e,
- ('d', '_'): 0x1e0f,
- ('D', ','): 0x1e10,
- ('d', ','): 0x1e11,
- ('F', '.'): 0x1e1e,
- ('f', '.'): 0x1e1f,
- ('G', '-'): 0x1e20,
- ('g', '-'): 0x1e21,
- ('H', '.'): 0x1e22,
- ('h', '.'): 0x1e23,
- ('H', ':'): 0x1e26,
- ('h', ':'): 0x1e27,
- ('H', ','): 0x1e28,
- ('h', ','): 0x1e29,
- ('K', '\''): 0x1e30,
- ('k', '\''): 0x1e31,
- ('K', '_'): 0x1e34,
- ('k', '_'): 0x1e35,
- ('L', '_'): 0x1e3a,
- ('l', '_'): 0x1e3b,
- ('M', '\''): 0x1e3e,
- ('m', '\''): 0x1e3f,
- ('M', '.'): 0x1e40,
- ('m', '.'): 0x1e41,
- ('N', '.'): 0x1e44,
- ('n', '.'): 0x1e45,
- ('N', '_'): 0x1e48,
- ('n', '_'): 0x1e49,
- ('P', '\''): 0x1e54,
- ('p', '\''): 0x1e55,
- ('P', '.'): 0x1e56,
- ('p', '.'): 0x1e57,
- ('R', '.'): 0x1e58,
- ('r', '.'): 0x1e59,
- ('R', '_'): 0x1e5e,
- ('r', '_'): 0x1e5f,
- ('S', '.'): 0x1e60,
- ('s', '.'): 0x1e61,
- ('T', '.'): 0x1e6a,
- ('t', '.'): 0x1e6b,
- ('T', '_'): 0x1e6e,
- ('t', '_'): 0x1e6f,
- ('V', '?'): 0x1e7c,
- ('v', '?'): 0x1e7d,
- ('W', '!'): 0x1e80,
- ('w', '!'): 0x1e81,
- ('W', '\''): 0x1e82,
- ('w', '\''): 0x1e83,
- ('W', ':'): 0x1e84,
- ('w', ':'): 0x1e85,
- ('W', '.'): 0x1e86,
- ('w', '.'): 0x1e87,
- ('X', '.'): 0x1e8a,
- ('x', '.'): 0x1e8b,
- ('X', ':'): 0x1e8c,
- ('x', ':'): 0x1e8d,
- ('Y', '.'): 0x1e8e,
- ('y', '.'): 0x1e8f,
- ('Z', '>'): 0x1e90,
- ('z', '>'): 0x1e91,
- ('Z', '_'): 0x1e94,
- ('z', '_'): 0x1e95,
- ('h', '_'): 0x1e96,
- ('t', ':'): 0x1e97,
- ('w', '0'): 0x1e98,
- ('y', '0'): 0x1e99,
- ('A', '2'): 0x1ea2,
- ('a', '2'): 0x1ea3,
- ('E', '2'): 0x1eba,
- ('e', '2'): 0x1ebb,
- ('E', '?'): 0x1ebc,
- ('e', '?'): 0x1ebd,
- ('I', '2'): 0x1ec8,
- ('i', '2'): 0x1ec9,
- ('O', '2'): 0x1ece,
- ('o', '2'): 0x1ecf,
- ('U', '2'): 0x1ee6,
- ('u', '2'): 0x1ee7,
- ('Y', '!'): 0x1ef2,
- ('y', '!'): 0x1ef3,
- ('Y', '2'): 0x1ef6,
- ('y', '2'): 0x1ef7,
- ('Y', '?'): 0x1ef8,
- ('y', '?'): 0x1ef9,
- (';', '\''): 0x1f00,
- (',', '\''): 0x1f01,
- (';', '!'): 0x1f02,
- (',', '!'): 0x1f03,
- ('?', ';'): 0x1f04,
- ('?', ','): 0x1f05,
- ('!', ':'): 0x1f06,
- ('?', ':'): 0x1f07,
- ('1', 'N'): 0x2002,
- ('1', 'M'): 0x2003,
- ('3', 'M'): 0x2004,
- ('4', 'M'): 0x2005,
- ('6', 'M'): 0x2006,
- ('1', 'T'): 0x2009,
- ('1', 'H'): 0x200a,
- ('-', '1'): 0x2010,
- ('-', 'N'): 0x2013,
- ('-', 'M'): 0x2014,
- ('-', '3'): 0x2015,
- ('!', '2'): 0x2016,
- ('=', '2'): 0x2017,
- ('\'', '6'): 0x2018,
- ('\'', '9'): 0x2019,
- ('.', '9'): 0x201a,
- ('9', '\''): 0x201b,
- ('"', '6'): 0x201c,
- ('"', '9'): 0x201d,
- (':', '9'): 0x201e,
- ('9', '"'): 0x201f,
- ('/', '-'): 0x2020,
- ('/', '='): 0x2021,
- ('.', '.'): 0x2025,
- ('%', '0'): 0x2030,
- ('1', '\''): 0x2032,
- ('2', '\''): 0x2033,
- ('3', '\''): 0x2034,
- ('1', '"'): 0x2035,
- ('2', '"'): 0x2036,
- ('3', '"'): 0x2037,
- ('C', 'a'): 0x2038,
- ('<', '1'): 0x2039,
- ('>', '1'): 0x203a,
- (':', 'X'): 0x203b,
- ('\'', '-'): 0x203e,
- ('/', 'f'): 0x2044,
- ('0', 'S'): 0x2070,
- ('4', 'S'): 0x2074,
- ('5', 'S'): 0x2075,
- ('6', 'S'): 0x2076,
- ('7', 'S'): 0x2077,
- ('8', 'S'): 0x2078,
- ('9', 'S'): 0x2079,
- ('+', 'S'): 0x207a,
- ('-', 'S'): 0x207b,
- ('=', 'S'): 0x207c,
- ('(', 'S'): 0x207d,
- (')', 'S'): 0x207e,
- ('n', 'S'): 0x207f,
- ('0', 's'): 0x2080,
- ('1', 's'): 0x2081,
- ('2', 's'): 0x2082,
- ('3', 's'): 0x2083,
- ('4', 's'): 0x2084,
- ('5', 's'): 0x2085,
- ('6', 's'): 0x2086,
- ('7', 's'): 0x2087,
- ('8', 's'): 0x2088,
- ('9', 's'): 0x2089,
- ('+', 's'): 0x208a,
- ('-', 's'): 0x208b,
- ('=', 's'): 0x208c,
- ('(', 's'): 0x208d,
- (')', 's'): 0x208e,
- ('L', 'i'): 0x20a4,
- ('P', 't'): 0x20a7,
- ('W', '='): 0x20a9,
- ('=', 'e'): 0x20ac, # euro
- ('E', 'u'): 0x20ac, # euro
- ('=', 'R'): 0x20bd, # rouble
- ('=', 'P'): 0x20bd, # rouble
- ('o', 'C'): 0x2103,
- ('c', 'o'): 0x2105,
- ('o', 'F'): 0x2109,
- ('N', '0'): 0x2116,
- ('P', 'O'): 0x2117,
- ('R', 'x'): 0x211e,
- ('S', 'M'): 0x2120,
- ('T', 'M'): 0x2122,
- ('O', 'm'): 0x2126,
- ('A', 'O'): 0x212b,
- ('1', '3'): 0x2153,
- ('2', '3'): 0x2154,
- ('1', '5'): 0x2155,
- ('2', '5'): 0x2156,
- ('3', '5'): 0x2157,
- ('4', '5'): 0x2158,
- ('1', '6'): 0x2159,
- ('5', '6'): 0x215a,
- ('1', '8'): 0x215b,
- ('3', '8'): 0x215c,
- ('5', '8'): 0x215d,
- ('7', '8'): 0x215e,
- ('1', 'R'): 0x2160,
- ('2', 'R'): 0x2161,
- ('3', 'R'): 0x2162,
- ('4', 'R'): 0x2163,
- ('5', 'R'): 0x2164,
- ('6', 'R'): 0x2165,
- ('7', 'R'): 0x2166,
- ('8', 'R'): 0x2167,
- ('9', 'R'): 0x2168,
- ('a', 'R'): 0x2169,
- ('b', 'R'): 0x216a,
- ('c', 'R'): 0x216b,
- ('1', 'r'): 0x2170,
- ('2', 'r'): 0x2171,
- ('3', 'r'): 0x2172,
- ('4', 'r'): 0x2173,
- ('5', 'r'): 0x2174,
- ('6', 'r'): 0x2175,
- ('7', 'r'): 0x2176,
- ('8', 'r'): 0x2177,
- ('9', 'r'): 0x2178,
- ('a', 'r'): 0x2179,
- ('b', 'r'): 0x217a,
- ('c', 'r'): 0x217b,
- ('<', '-'): 0x2190,
- ('-', '!'): 0x2191,
- ('-', '>'): 0x2192,
- ('-', 'v'): 0x2193,
- ('<', '>'): 0x2194,
- ('U', 'D'): 0x2195,
- ('<', '='): 0x21d0,
- ('=', '>'): 0x21d2,
- ('=', '='): 0x21d4,
- ('F', 'A'): 0x2200,
- ('d', 'P'): 0x2202,
- ('T', 'E'): 0x2203,
- ('/', '0'): 0x2205,
- ('D', 'E'): 0x2206,
- ('N', 'B'): 0x2207,
- ('(', '-'): 0x2208,
- ('-', ')'): 0x220b,
- ('*', 'P'): 0x220f,
- ('+', 'Z'): 0x2211,
- ('-', '2'): 0x2212,
- ('-', '+'): 0x2213,
- ('*', '-'): 0x2217,
- ('O', 'b'): 0x2218,
- ('S', 'b'): 0x2219,
- ('R', 'T'): 0x221a,
- ('0', '('): 0x221d,
- ('0', '0'): 0x221e,
- ('-', 'L'): 0x221f,
- ('-', 'V'): 0x2220,
- ('P', 'P'): 0x2225,
- ('A', 'N'): 0x2227,
- ('O', 'R'): 0x2228,
- ('(', 'U'): 0x2229,
- (')', 'U'): 0x222a,
- ('I', 'n'): 0x222b,
- ('D', 'I'): 0x222c,
- ('I', 'o'): 0x222e,
- ('.', ':'): 0x2234,
- (':', '.'): 0x2235,
- (':', 'R'): 0x2236,
- (':', ':'): 0x2237,
- ('?', '1'): 0x223c,
- ('C', 'G'): 0x223e,
- ('?', '-'): 0x2243,
- ('?', '='): 0x2245,
- ('?', '2'): 0x2248,
- ('=', '?'): 0x224c,
- ('H', 'I'): 0x2253,
- ('!', '='): 0x2260,
- ('=', '3'): 0x2261,
- ('=', '<'): 0x2264,
- ('>', '='): 0x2265,
- ('<', '*'): 0x226a,
- ('*', '>'): 0x226b,
- ('!', '<'): 0x226e,
- ('!', '>'): 0x226f,
- ('(', 'C'): 0x2282,
- (')', 'C'): 0x2283,
- ('(', '_'): 0x2286,
- (')', '_'): 0x2287,
- ('0', '.'): 0x2299,
- ('0', '2'): 0x229a,
- ('-', 'T'): 0x22a5,
- ('.', 'P'): 0x22c5,
- (':', '3'): 0x22ee,
- ('.', '3'): 0x22ef,
- ('E', 'h'): 0x2302,
- ('<', '7'): 0x2308,
- ('>', '7'): 0x2309,
- ('7', '<'): 0x230a,
- ('7', '>'): 0x230b,
- ('N', 'I'): 0x2310,
- ('(', 'A'): 0x2312,
- ('T', 'R'): 0x2315,
- ('I', 'u'): 0x2320,
- ('I', 'l'): 0x2321,
- ('<', '/'): 0x2329,
- ('/', '>'): 0x232a,
- ('V', 's'): 0x2423,
- ('1', 'h'): 0x2440,
- ('3', 'h'): 0x2441,
- ('2', 'h'): 0x2442,
- ('4', 'h'): 0x2443,
- ('1', 'j'): 0x2446,
- ('2', 'j'): 0x2447,
- ('3', 'j'): 0x2448,
- ('4', 'j'): 0x2449,
- ('1', '.'): 0x2488,
- ('2', '.'): 0x2489,
- ('3', '.'): 0x248a,
- ('4', '.'): 0x248b,
- ('5', '.'): 0x248c,
- ('6', '.'): 0x248d,
- ('7', '.'): 0x248e,
- ('8', '.'): 0x248f,
- ('9', '.'): 0x2490,
- ('h', 'h'): 0x2500,
- ('H', 'H'): 0x2501,
- ('v', 'v'): 0x2502,
- ('V', 'V'): 0x2503,
- ('3', '-'): 0x2504,
- ('3', '_'): 0x2505,
- ('3', '!'): 0x2506,
- ('3', '/'): 0x2507,
- ('4', '-'): 0x2508,
- ('4', '_'): 0x2509,
- ('4', '!'): 0x250a,
- ('4', '/'): 0x250b,
- ('d', 'r'): 0x250c,
- ('d', 'R'): 0x250d,
- ('D', 'r'): 0x250e,
- ('D', 'R'): 0x250f,
- ('d', 'l'): 0x2510,
- ('d', 'L'): 0x2511,
- ('D', 'l'): 0x2512,
- ('L', 'D'): 0x2513,
- ('u', 'r'): 0x2514,
- ('u', 'R'): 0x2515,
- ('U', 'r'): 0x2516,
- ('U', 'R'): 0x2517,
- ('u', 'l'): 0x2518,
- ('u', 'L'): 0x2519,
- ('U', 'l'): 0x251a,
- ('U', 'L'): 0x251b,
- ('v', 'r'): 0x251c,
- ('v', 'R'): 0x251d,
- ('V', 'r'): 0x2520,
- ('V', 'R'): 0x2523,
- ('v', 'l'): 0x2524,
- ('v', 'L'): 0x2525,
- ('V', 'l'): 0x2528,
- ('V', 'L'): 0x252b,
- ('d', 'h'): 0x252c,
- ('d', 'H'): 0x252f,
- ('D', 'h'): 0x2530,
- ('D', 'H'): 0x2533,
- ('u', 'h'): 0x2534,
- ('u', 'H'): 0x2537,
- ('U', 'h'): 0x2538,
- ('U', 'H'): 0x253b,
- ('v', 'h'): 0x253c,
- ('v', 'H'): 0x253f,
- ('V', 'h'): 0x2542,
- ('V', 'H'): 0x254b,
- ('F', 'D'): 0x2571,
- ('B', 'D'): 0x2572,
- ('T', 'B'): 0x2580,
- ('L', 'B'): 0x2584,
- ('F', 'B'): 0x2588,
- ('l', 'B'): 0x258c,
- ('R', 'B'): 0x2590,
- ('.', 'S'): 0x2591,
- (':', 'S'): 0x2592,
- ('?', 'S'): 0x2593,
- ('f', 'S'): 0x25a0,
- ('O', 'S'): 0x25a1,
- ('R', 'O'): 0x25a2,
- ('R', 'r'): 0x25a3,
- ('R', 'F'): 0x25a4,
- ('R', 'Y'): 0x25a5,
- ('R', 'H'): 0x25a6,
- ('R', 'Z'): 0x25a7,
- ('R', 'K'): 0x25a8,
- ('R', 'X'): 0x25a9,
- ('s', 'B'): 0x25aa,
- ('S', 'R'): 0x25ac,
- ('O', 'r'): 0x25ad,
- ('U', 'T'): 0x25b2,
- ('u', 'T'): 0x25b3,
- ('P', 'R'): 0x25b6,
- ('T', 'r'): 0x25b7,
- ('D', 't'): 0x25bc,
- ('d', 'T'): 0x25bd,
- ('P', 'L'): 0x25c0,
- ('T', 'l'): 0x25c1,
- ('D', 'b'): 0x25c6,
- ('D', 'w'): 0x25c7,
- ('L', 'Z'): 0x25ca,
- ('0', 'm'): 0x25cb,
- ('0', 'o'): 0x25ce,
- ('0', 'M'): 0x25cf,
- ('0', 'L'): 0x25d0,
- ('0', 'R'): 0x25d1,
- ('S', 'n'): 0x25d8,
- ('I', 'c'): 0x25d9,
- ('F', 'd'): 0x25e2,
- ('B', 'd'): 0x25e3,
- ('*', '2'): 0x2605,
- ('*', '1'): 0x2606,
- ('<', 'H'): 0x261c,
- ('>', 'H'): 0x261e,
- ('0', 'u'): 0x263a,
- ('0', 'U'): 0x263b,
- ('S', 'U'): 0x263c,
- ('F', 'm'): 0x2640,
- ('M', 'l'): 0x2642,
- ('c', 'S'): 0x2660,
- ('c', 'H'): 0x2661,
- ('c', 'D'): 0x2662,
- ('c', 'C'): 0x2663,
- ('M', 'd'): 0x2669,
- ('M', '8'): 0x266a,
- ('M', '2'): 0x266b,
- ('M', 'b'): 0x266d,
- ('M', 'x'): 0x266e,
- ('M', 'X'): 0x266f,
- ('O', 'K'): 0x2713,
- ('X', 'X'): 0x2717,
- ('-', 'X'): 0x2720,
- ('I', 'S'): 0x3000,
- (',', '_'): 0x3001,
- ('.', '_'): 0x3002,
- ('+', '"'): 0x3003,
- ('+', '_'): 0x3004,
- ('*', '_'): 0x3005,
- (';', '_'): 0x3006,
- ('0', '_'): 0x3007,
- ('<', '+'): 0x300a,
- ('>', '+'): 0x300b,
- ('<', '\''): 0x300c,
- ('>', '\''): 0x300d,
- ('<', '"'): 0x300e,
- ('>', '"'): 0x300f,
- ('(', '"'): 0x3010,
- (')', '"'): 0x3011,
- ('=', 'T'): 0x3012,
- ('=', '_'): 0x3013,
- ('(', '\''): 0x3014,
- (')', '\''): 0x3015,
- ('(', 'I'): 0x3016,
- (')', 'I'): 0x3017,
- ('-', '?'): 0x301c,
- ('A', '5'): 0x3041,
- ('a', '5'): 0x3042,
- ('I', '5'): 0x3043,
- ('i', '5'): 0x3044,
- ('U', '5'): 0x3045,
- ('u', '5'): 0x3046,
- ('E', '5'): 0x3047,
- ('e', '5'): 0x3048,
- ('O', '5'): 0x3049,
- ('o', '5'): 0x304a,
- ('k', 'a'): 0x304b,
- ('g', 'a'): 0x304c,
- ('k', 'i'): 0x304d,
- ('g', 'i'): 0x304e,
- ('k', 'u'): 0x304f,
- ('g', 'u'): 0x3050,
- ('k', 'e'): 0x3051,
- ('g', 'e'): 0x3052,
- ('k', 'o'): 0x3053,
- ('g', 'o'): 0x3054,
- ('s', 'a'): 0x3055,
- ('z', 'a'): 0x3056,
- ('s', 'i'): 0x3057,
- ('z', 'i'): 0x3058,
- ('s', 'u'): 0x3059,
- ('z', 'u'): 0x305a,
- ('s', 'e'): 0x305b,
- ('z', 'e'): 0x305c,
- ('s', 'o'): 0x305d,
- ('z', 'o'): 0x305e,
- ('t', 'a'): 0x305f,
- ('d', 'a'): 0x3060,
- ('t', 'i'): 0x3061,
- ('d', 'i'): 0x3062,
- ('t', 'U'): 0x3063,
- ('t', 'u'): 0x3064,
- ('d', 'u'): 0x3065,
- ('t', 'e'): 0x3066,
- ('d', 'e'): 0x3067,
- ('t', 'o'): 0x3068,
- ('d', 'o'): 0x3069,
- ('n', 'a'): 0x306a,
- ('n', 'i'): 0x306b,
- ('n', 'u'): 0x306c,
- ('n', 'e'): 0x306d,
- ('n', 'o'): 0x306e,
- ('h', 'a'): 0x306f,
- ('b', 'a'): 0x3070,
- ('p', 'a'): 0x3071,
- ('h', 'i'): 0x3072,
- ('b', 'i'): 0x3073,
- ('p', 'i'): 0x3074,
- ('h', 'u'): 0x3075,
- ('b', 'u'): 0x3076,
- ('p', 'u'): 0x3077,
- ('h', 'e'): 0x3078,
- ('b', 'e'): 0x3079,
- ('p', 'e'): 0x307a,
- ('h', 'o'): 0x307b,
- ('b', 'o'): 0x307c,
- ('p', 'o'): 0x307d,
- ('m', 'a'): 0x307e,
- ('m', 'i'): 0x307f,
- ('m', 'u'): 0x3080,
- ('m', 'e'): 0x3081,
- ('m', 'o'): 0x3082,
- ('y', 'A'): 0x3083,
- ('y', 'a'): 0x3084,
- ('y', 'U'): 0x3085,
- ('y', 'u'): 0x3086,
- ('y', 'O'): 0x3087,
- ('y', 'o'): 0x3088,
- ('r', 'a'): 0x3089,
- ('r', 'i'): 0x308a,
- ('r', 'u'): 0x308b,
- ('r', 'e'): 0x308c,
- ('r', 'o'): 0x308d,
- ('w', 'A'): 0x308e,
- ('w', 'a'): 0x308f,
- ('w', 'i'): 0x3090,
- ('w', 'e'): 0x3091,
- ('w', 'o'): 0x3092,
- ('n', '5'): 0x3093,
- ('v', 'u'): 0x3094,
- ('"', '5'): 0x309b,
- ('0', '5'): 0x309c,
- ('*', '5'): 0x309d,
- ('+', '5'): 0x309e,
- ('a', '6'): 0x30a1,
- ('A', '6'): 0x30a2,
- ('i', '6'): 0x30a3,
- ('I', '6'): 0x30a4,
- ('u', '6'): 0x30a5,
- ('U', '6'): 0x30a6,
- ('e', '6'): 0x30a7,
- ('E', '6'): 0x30a8,
- ('o', '6'): 0x30a9,
- ('O', '6'): 0x30aa,
- ('K', 'a'): 0x30ab,
- ('G', 'a'): 0x30ac,
- ('K', 'i'): 0x30ad,
- ('G', 'i'): 0x30ae,
- ('K', 'u'): 0x30af,
- ('G', 'u'): 0x30b0,
- ('K', 'e'): 0x30b1,
- ('G', 'e'): 0x30b2,
- ('K', 'o'): 0x30b3,
- ('G', 'o'): 0x30b4,
- ('S', 'a'): 0x30b5,
- ('Z', 'a'): 0x30b6,
- ('S', 'i'): 0x30b7,
- ('Z', 'i'): 0x30b8,
- ('S', 'u'): 0x30b9,
- ('Z', 'u'): 0x30ba,
- ('S', 'e'): 0x30bb,
- ('Z', 'e'): 0x30bc,
- ('S', 'o'): 0x30bd,
- ('Z', 'o'): 0x30be,
- ('T', 'a'): 0x30bf,
- ('D', 'a'): 0x30c0,
- ('T', 'i'): 0x30c1,
- ('D', 'i'): 0x30c2,
- ('T', 'U'): 0x30c3,
- ('T', 'u'): 0x30c4,
- ('D', 'u'): 0x30c5,
- ('T', 'e'): 0x30c6,
- ('D', 'e'): 0x30c7,
- ('T', 'o'): 0x30c8,
- ('D', 'o'): 0x30c9,
- ('N', 'a'): 0x30ca,
- ('N', 'i'): 0x30cb,
- ('N', 'u'): 0x30cc,
- ('N', 'e'): 0x30cd,
- ('N', 'o'): 0x30ce,
- ('H', 'a'): 0x30cf,
- ('B', 'a'): 0x30d0,
- ('P', 'a'): 0x30d1,
- ('H', 'i'): 0x30d2,
- ('B', 'i'): 0x30d3,
- ('P', 'i'): 0x30d4,
- ('H', 'u'): 0x30d5,
- ('B', 'u'): 0x30d6,
- ('P', 'u'): 0x30d7,
- ('H', 'e'): 0x30d8,
- ('B', 'e'): 0x30d9,
- ('P', 'e'): 0x30da,
- ('H', 'o'): 0x30db,
- ('B', 'o'): 0x30dc,
- ('P', 'o'): 0x30dd,
- ('M', 'a'): 0x30de,
- ('M', 'i'): 0x30df,
- ('M', 'u'): 0x30e0,
- ('M', 'e'): 0x30e1,
- ('M', 'o'): 0x30e2,
- ('Y', 'A'): 0x30e3,
- ('Y', 'a'): 0x30e4,
- ('Y', 'U'): 0x30e5,
- ('Y', 'u'): 0x30e6,
- ('Y', 'O'): 0x30e7,
- ('Y', 'o'): 0x30e8,
- ('R', 'a'): 0x30e9,
- ('R', 'i'): 0x30ea,
- ('R', 'u'): 0x30eb,
- ('R', 'e'): 0x30ec,
- ('R', 'o'): 0x30ed,
- ('W', 'A'): 0x30ee,
- ('W', 'a'): 0x30ef,
- ('W', 'i'): 0x30f0,
- ('W', 'e'): 0x30f1,
- ('W', 'o'): 0x30f2,
- ('N', '6'): 0x30f3,
- ('V', 'u'): 0x30f4,
- ('K', 'A'): 0x30f5,
- ('K', 'E'): 0x30f6,
- ('V', 'a'): 0x30f7,
- ('V', 'i'): 0x30f8,
- ('V', 'e'): 0x30f9,
- ('V', 'o'): 0x30fa,
- ('.', '6'): 0x30fb,
- ('-', '6'): 0x30fc,
- ('*', '6'): 0x30fd,
- ('+', '6'): 0x30fe,
- ('b', '4'): 0x3105,
- ('p', '4'): 0x3106,
- ('m', '4'): 0x3107,
- ('f', '4'): 0x3108,
- ('d', '4'): 0x3109,
- ('t', '4'): 0x310a,
- ('n', '4'): 0x310b,
- ('l', '4'): 0x310c,
- ('g', '4'): 0x310d,
- ('k', '4'): 0x310e,
- ('h', '4'): 0x310f,
- ('j', '4'): 0x3110,
- ('q', '4'): 0x3111,
- ('x', '4'): 0x3112,
- ('z', 'h'): 0x3113,
- ('c', 'h'): 0x3114,
- ('s', 'h'): 0x3115,
- ('r', '4'): 0x3116,
- ('z', '4'): 0x3117,
- ('c', '4'): 0x3118,
- ('s', '4'): 0x3119,
- ('a', '4'): 0x311a,
- ('o', '4'): 0x311b,
- ('e', '4'): 0x311c,
- ('a', 'i'): 0x311e,
- ('e', 'i'): 0x311f,
- ('a', 'u'): 0x3120,
- ('o', 'u'): 0x3121,
- ('a', 'n'): 0x3122,
- ('e', 'n'): 0x3123,
- ('a', 'N'): 0x3124,
- ('e', 'N'): 0x3125,
- ('e', 'r'): 0x3126,
- ('i', '4'): 0x3127,
- ('u', '4'): 0x3128,
- ('i', 'u'): 0x3129,
- ('v', '4'): 0x312a,
- ('n', 'G'): 0x312b,
- ('g', 'n'): 0x312c,
- ('1', 'c'): 0x3220,
- ('2', 'c'): 0x3221,
- ('3', 'c'): 0x3222,
- ('4', 'c'): 0x3223,
- ('5', 'c'): 0x3224,
- ('6', 'c'): 0x3225,
- ('7', 'c'): 0x3226,
- ('8', 'c'): 0x3227,
- ('9', 'c'): 0x3228,
-
- # code points 0xe000 - 0xefff excluded, they have no assigned
- # characters, only used in proposals.
- ('f', 'f'): 0xfb00,
- ('f', 'i'): 0xfb01,
- ('f', 'l'): 0xfb02,
- ('f', 't'): 0xfb05,
- ('s', 't'): 0xfb06,
-
- # Vim 5.x compatible digraphs that don't conflict with the above
- ('~', '!'): 161,
- ('c', '|'): 162,
- ('$', '$'): 163,
- ('o', 'x'): 164, # currency symbol in ISO 8859-1
- ('Y', '-'): 165,
- ('|', '|'): 166,
- ('c', 'O'): 169,
- ('-', ','): 172,
- ('-', '='): 175,
- ('~', 'o'): 176,
- ('2', '2'): 178,
- ('3', '3'): 179,
- ('p', 'p'): 182,
- ('~', '.'): 183,
- ('1', '1'): 185,
- ('~', '?'): 191,
- ('A', '`'): 192,
- ('A', '^'): 194,
- ('A', '~'): 195,
- ('A', '"'): 196,
- ('A', '@'): 197,
- ('E', '`'): 200,
- ('E', '^'): 202,
- ('E', '"'): 203,
- ('I', '`'): 204,
- ('I', '^'): 206,
- ('I', '"'): 207,
- ('N', '~'): 209,
- ('O', '`'): 210,
- ('O', '^'): 212,
- ('O', '~'): 213,
- ('/', '\\'): 215, # multiplication symbol in ISO 8859-1
- ('U', '`'): 217,
- ('U', '^'): 219,
- ('I', 'p'): 222,
- ('a', '`'): 224,
- ('a', '^'): 226,
- ('a', '~'): 227,
- ('a', '"'): 228,
- ('a', '@'): 229,
- ('e', '`'): 232,
- ('e', '^'): 234,
- ('e', '"'): 235,
- ('i', '`'): 236,
- ('i', '^'): 238,
- ('n', '~'): 241,
- ('o', '`'): 242,
- ('o', '^'): 244,
- ('o', '~'): 245,
- ('u', '`'): 249,
- ('u', '^'): 251,
- ('y', '"'): 255,
-}
+# encoding: utf-8
+from __future__ import unicode_literals
+"""
+Vi Digraphs.
+This is a list of special characters that can be inserted in Vi insert mode by
+pressing Control-K followed by to normal characters.
+
+Taken from Neovim and translated to Python:
+https://raw.githubusercontent.com/neovim/neovim/master/src/nvim/digraph.c
+"""
+__all__ = ('DIGRAPHS', )
+
+# digraphs for Unicode from RFC1345
+# (also work for ISO-8859-1 aka latin1)
+DIGRAPHS = {
+ ('N', 'U'): 0x00,
+ ('S', 'H'): 0x01,
+ ('S', 'X'): 0x02,
+ ('E', 'X'): 0x03,
+ ('E', 'T'): 0x04,
+ ('E', 'Q'): 0x05,
+ ('A', 'K'): 0x06,
+ ('B', 'L'): 0x07,
+ ('B', 'S'): 0x08,
+ ('H', 'T'): 0x09,
+ ('L', 'F'): 0x0a,
+ ('V', 'T'): 0x0b,
+ ('F', 'F'): 0x0c,
+ ('C', 'R'): 0x0d,
+ ('S', 'O'): 0x0e,
+ ('S', 'I'): 0x0f,
+ ('D', 'L'): 0x10,
+ ('D', '1'): 0x11,
+ ('D', '2'): 0x12,
+ ('D', '3'): 0x13,
+ ('D', '4'): 0x14,
+ ('N', 'K'): 0x15,
+ ('S', 'Y'): 0x16,
+ ('E', 'B'): 0x17,
+ ('C', 'N'): 0x18,
+ ('E', 'M'): 0x19,
+ ('S', 'B'): 0x1a,
+ ('E', 'C'): 0x1b,
+ ('F', 'S'): 0x1c,
+ ('G', 'S'): 0x1d,
+ ('R', 'S'): 0x1e,
+ ('U', 'S'): 0x1f,
+ ('S', 'P'): 0x20,
+ ('N', 'b'): 0x23,
+ ('D', 'O'): 0x24,
+ ('A', 't'): 0x40,
+ ('<', '('): 0x5b,
+ ('/', '/'): 0x5c,
+ (')', '>'): 0x5d,
+ ('\'', '>'): 0x5e,
+ ('\'', '!'): 0x60,
+ ('(', '!'): 0x7b,
+ ('!', '!'): 0x7c,
+ ('!', ')'): 0x7d,
+ ('\'', '?'): 0x7e,
+ ('D', 'T'): 0x7f,
+ ('P', 'A'): 0x80,
+ ('H', 'O'): 0x81,
+ ('B', 'H'): 0x82,
+ ('N', 'H'): 0x83,
+ ('I', 'N'): 0x84,
+ ('N', 'L'): 0x85,
+ ('S', 'A'): 0x86,
+ ('E', 'S'): 0x87,
+ ('H', 'S'): 0x88,
+ ('H', 'J'): 0x89,
+ ('V', 'S'): 0x8a,
+ ('P', 'D'): 0x8b,
+ ('P', 'U'): 0x8c,
+ ('R', 'I'): 0x8d,
+ ('S', '2'): 0x8e,
+ ('S', '3'): 0x8f,
+ ('D', 'C'): 0x90,
+ ('P', '1'): 0x91,
+ ('P', '2'): 0x92,
+ ('T', 'S'): 0x93,
+ ('C', 'C'): 0x94,
+ ('M', 'W'): 0x95,
+ ('S', 'G'): 0x96,
+ ('E', 'G'): 0x97,
+ ('S', 'S'): 0x98,
+ ('G', 'C'): 0x99,
+ ('S', 'C'): 0x9a,
+ ('C', 'I'): 0x9b,
+ ('S', 'T'): 0x9c,
+ ('O', 'C'): 0x9d,
+ ('P', 'M'): 0x9e,
+ ('A', 'C'): 0x9f,
+ ('N', 'S'): 0xa0,
+ ('!', 'I'): 0xa1,
+ ('C', 't'): 0xa2,
+ ('P', 'd'): 0xa3,
+ ('C', 'u'): 0xa4,
+ ('Y', 'e'): 0xa5,
+ ('B', 'B'): 0xa6,
+ ('S', 'E'): 0xa7,
+ ('\'', ':'): 0xa8,
+ ('C', 'o'): 0xa9,
+ ('-', 'a'): 0xaa,
+ ('<', '<'): 0xab,
+ ('N', 'O'): 0xac,
+ ('-', '-'): 0xad,
+ ('R', 'g'): 0xae,
+ ('\'', 'm'): 0xaf,
+ ('D', 'G'): 0xb0,
+ ('+', '-'): 0xb1,
+ ('2', 'S'): 0xb2,
+ ('3', 'S'): 0xb3,
+ ('\'', '\''): 0xb4,
+ ('M', 'y'): 0xb5,
+ ('P', 'I'): 0xb6,
+ ('.', 'M'): 0xb7,
+ ('\'', ','): 0xb8,
+ ('1', 'S'): 0xb9,
+ ('-', 'o'): 0xba,
+ ('>', '>'): 0xbb,
+ ('1', '4'): 0xbc,
+ ('1', '2'): 0xbd,
+ ('3', '4'): 0xbe,
+ ('?', 'I'): 0xbf,
+ ('A', '!'): 0xc0,
+ ('A', '\''): 0xc1,
+ ('A', '>'): 0xc2,
+ ('A', '?'): 0xc3,
+ ('A', ':'): 0xc4,
+ ('A', 'A'): 0xc5,
+ ('A', 'E'): 0xc6,
+ ('C', ','): 0xc7,
+ ('E', '!'): 0xc8,
+ ('E', '\''): 0xc9,
+ ('E', '>'): 0xca,
+ ('E', ':'): 0xcb,
+ ('I', '!'): 0xcc,
+ ('I', '\''): 0xcd,
+ ('I', '>'): 0xce,
+ ('I', ':'): 0xcf,
+ ('D', '-'): 0xd0,
+ ('N', '?'): 0xd1,
+ ('O', '!'): 0xd2,
+ ('O', '\''): 0xd3,
+ ('O', '>'): 0xd4,
+ ('O', '?'): 0xd5,
+ ('O', ':'): 0xd6,
+ ('*', 'X'): 0xd7,
+ ('O', '/'): 0xd8,
+ ('U', '!'): 0xd9,
+ ('U', '\''): 0xda,
+ ('U', '>'): 0xdb,
+ ('U', ':'): 0xdc,
+ ('Y', '\''): 0xdd,
+ ('T', 'H'): 0xde,
+ ('s', 's'): 0xdf,
+ ('a', '!'): 0xe0,
+ ('a', '\''): 0xe1,
+ ('a', '>'): 0xe2,
+ ('a', '?'): 0xe3,
+ ('a', ':'): 0xe4,
+ ('a', 'a'): 0xe5,
+ ('a', 'e'): 0xe6,
+ ('c', ','): 0xe7,
+ ('e', '!'): 0xe8,
+ ('e', '\''): 0xe9,
+ ('e', '>'): 0xea,
+ ('e', ':'): 0xeb,
+ ('i', '!'): 0xec,
+ ('i', '\''): 0xed,
+ ('i', '>'): 0xee,
+ ('i', ':'): 0xef,
+ ('d', '-'): 0xf0,
+ ('n', '?'): 0xf1,
+ ('o', '!'): 0xf2,
+ ('o', '\''): 0xf3,
+ ('o', '>'): 0xf4,
+ ('o', '?'): 0xf5,
+ ('o', ':'): 0xf6,
+ ('-', ':'): 0xf7,
+ ('o', '/'): 0xf8,
+ ('u', '!'): 0xf9,
+ ('u', '\''): 0xfa,
+ ('u', '>'): 0xfb,
+ ('u', ':'): 0xfc,
+ ('y', '\''): 0xfd,
+ ('t', 'h'): 0xfe,
+ ('y', ':'): 0xff,
+
+ ('A', '-'): 0x0100,
+ ('a', '-'): 0x0101,
+ ('A', '('): 0x0102,
+ ('a', '('): 0x0103,
+ ('A', ';'): 0x0104,
+ ('a', ';'): 0x0105,
+ ('C', '\''): 0x0106,
+ ('c', '\''): 0x0107,
+ ('C', '>'): 0x0108,
+ ('c', '>'): 0x0109,
+ ('C', '.'): 0x010a,
+ ('c', '.'): 0x010b,
+ ('C', '<'): 0x010c,
+ ('c', '<'): 0x010d,
+ ('D', '<'): 0x010e,
+ ('d', '<'): 0x010f,
+ ('D', '/'): 0x0110,
+ ('d', '/'): 0x0111,
+ ('E', '-'): 0x0112,
+ ('e', '-'): 0x0113,
+ ('E', '('): 0x0114,
+ ('e', '('): 0x0115,
+ ('E', '.'): 0x0116,
+ ('e', '.'): 0x0117,
+ ('E', ';'): 0x0118,
+ ('e', ';'): 0x0119,
+ ('E', '<'): 0x011a,
+ ('e', '<'): 0x011b,
+ ('G', '>'): 0x011c,
+ ('g', '>'): 0x011d,
+ ('G', '('): 0x011e,
+ ('g', '('): 0x011f,
+ ('G', '.'): 0x0120,
+ ('g', '.'): 0x0121,
+ ('G', ','): 0x0122,
+ ('g', ','): 0x0123,
+ ('H', '>'): 0x0124,
+ ('h', '>'): 0x0125,
+ ('H', '/'): 0x0126,
+ ('h', '/'): 0x0127,
+ ('I', '?'): 0x0128,
+ ('i', '?'): 0x0129,
+ ('I', '-'): 0x012a,
+ ('i', '-'): 0x012b,
+ ('I', '('): 0x012c,
+ ('i', '('): 0x012d,
+ ('I', ';'): 0x012e,
+ ('i', ';'): 0x012f,
+ ('I', '.'): 0x0130,
+ ('i', '.'): 0x0131,
+ ('I', 'J'): 0x0132,
+ ('i', 'j'): 0x0133,
+ ('J', '>'): 0x0134,
+ ('j', '>'): 0x0135,
+ ('K', ','): 0x0136,
+ ('k', ','): 0x0137,
+ ('k', 'k'): 0x0138,
+ ('L', '\''): 0x0139,
+ ('l', '\''): 0x013a,
+ ('L', ','): 0x013b,
+ ('l', ','): 0x013c,
+ ('L', '<'): 0x013d,
+ ('l', '<'): 0x013e,
+ ('L', '.'): 0x013f,
+ ('l', '.'): 0x0140,
+ ('L', '/'): 0x0141,
+ ('l', '/'): 0x0142,
+ ('N', '\''): 0x0143,
+ ('n', '\''): 0x0144,
+ ('N', ','): 0x0145,
+ ('n', ','): 0x0146,
+ ('N', '<'): 0x0147,
+ ('n', '<'): 0x0148,
+ ('\'', 'n'): 0x0149,
+ ('N', 'G'): 0x014a,
+ ('n', 'g'): 0x014b,
+ ('O', '-'): 0x014c,
+ ('o', '-'): 0x014d,
+ ('O', '('): 0x014e,
+ ('o', '('): 0x014f,
+ ('O', '"'): 0x0150,
+ ('o', '"'): 0x0151,
+ ('O', 'E'): 0x0152,
+ ('o', 'e'): 0x0153,
+ ('R', '\''): 0x0154,
+ ('r', '\''): 0x0155,
+ ('R', ','): 0x0156,
+ ('r', ','): 0x0157,
+ ('R', '<'): 0x0158,
+ ('r', '<'): 0x0159,
+ ('S', '\''): 0x015a,
+ ('s', '\''): 0x015b,
+ ('S', '>'): 0x015c,
+ ('s', '>'): 0x015d,
+ ('S', ','): 0x015e,
+ ('s', ','): 0x015f,
+ ('S', '<'): 0x0160,
+ ('s', '<'): 0x0161,
+ ('T', ','): 0x0162,
+ ('t', ','): 0x0163,
+ ('T', '<'): 0x0164,
+ ('t', '<'): 0x0165,
+ ('T', '/'): 0x0166,
+ ('t', '/'): 0x0167,
+ ('U', '?'): 0x0168,
+ ('u', '?'): 0x0169,
+ ('U', '-'): 0x016a,
+ ('u', '-'): 0x016b,
+ ('U', '('): 0x016c,
+ ('u', '('): 0x016d,
+ ('U', '0'): 0x016e,
+ ('u', '0'): 0x016f,
+ ('U', '"'): 0x0170,
+ ('u', '"'): 0x0171,
+ ('U', ';'): 0x0172,
+ ('u', ';'): 0x0173,
+ ('W', '>'): 0x0174,
+ ('w', '>'): 0x0175,
+ ('Y', '>'): 0x0176,
+ ('y', '>'): 0x0177,
+ ('Y', ':'): 0x0178,
+ ('Z', '\''): 0x0179,
+ ('z', '\''): 0x017a,
+ ('Z', '.'): 0x017b,
+ ('z', '.'): 0x017c,
+ ('Z', '<'): 0x017d,
+ ('z', '<'): 0x017e,
+ ('O', '9'): 0x01a0,
+ ('o', '9'): 0x01a1,
+ ('O', 'I'): 0x01a2,
+ ('o', 'i'): 0x01a3,
+ ('y', 'r'): 0x01a6,
+ ('U', '9'): 0x01af,
+ ('u', '9'): 0x01b0,
+ ('Z', '/'): 0x01b5,
+ ('z', '/'): 0x01b6,
+ ('E', 'D'): 0x01b7,
+ ('A', '<'): 0x01cd,
+ ('a', '<'): 0x01ce,
+ ('I', '<'): 0x01cf,
+ ('i', '<'): 0x01d0,
+ ('O', '<'): 0x01d1,
+ ('o', '<'): 0x01d2,
+ ('U', '<'): 0x01d3,
+ ('u', '<'): 0x01d4,
+ ('A', '1'): 0x01de,
+ ('a', '1'): 0x01df,
+ ('A', '7'): 0x01e0,
+ ('a', '7'): 0x01e1,
+ ('A', '3'): 0x01e2,
+ ('a', '3'): 0x01e3,
+ ('G', '/'): 0x01e4,
+ ('g', '/'): 0x01e5,
+ ('G', '<'): 0x01e6,
+ ('g', '<'): 0x01e7,
+ ('K', '<'): 0x01e8,
+ ('k', '<'): 0x01e9,
+ ('O', ';'): 0x01ea,
+ ('o', ';'): 0x01eb,
+ ('O', '1'): 0x01ec,
+ ('o', '1'): 0x01ed,
+ ('E', 'Z'): 0x01ee,
+ ('e', 'z'): 0x01ef,
+ ('j', '<'): 0x01f0,
+ ('G', '\''): 0x01f4,
+ ('g', '\''): 0x01f5,
+ (';', 'S'): 0x02bf,
+ ('\'', '<'): 0x02c7,
+ ('\'', '('): 0x02d8,
+ ('\'', '.'): 0x02d9,
+ ('\'', '0'): 0x02da,
+ ('\'', ';'): 0x02db,
+ ('\'', '"'): 0x02dd,
+ ('A', '%'): 0x0386,
+ ('E', '%'): 0x0388,
+ ('Y', '%'): 0x0389,
+ ('I', '%'): 0x038a,
+ ('O', '%'): 0x038c,
+ ('U', '%'): 0x038e,
+ ('W', '%'): 0x038f,
+ ('i', '3'): 0x0390,
+ ('A', '*'): 0x0391,
+ ('B', '*'): 0x0392,
+ ('G', '*'): 0x0393,
+ ('D', '*'): 0x0394,
+ ('E', '*'): 0x0395,
+ ('Z', '*'): 0x0396,
+ ('Y', '*'): 0x0397,
+ ('H', '*'): 0x0398,
+ ('I', '*'): 0x0399,
+ ('K', '*'): 0x039a,
+ ('L', '*'): 0x039b,
+ ('M', '*'): 0x039c,
+ ('N', '*'): 0x039d,
+ ('C', '*'): 0x039e,
+ ('O', '*'): 0x039f,
+ ('P', '*'): 0x03a0,
+ ('R', '*'): 0x03a1,
+ ('S', '*'): 0x03a3,
+ ('T', '*'): 0x03a4,
+ ('U', '*'): 0x03a5,
+ ('F', '*'): 0x03a6,
+ ('X', '*'): 0x03a7,
+ ('Q', '*'): 0x03a8,
+ ('W', '*'): 0x03a9,
+ ('J', '*'): 0x03aa,
+ ('V', '*'): 0x03ab,
+ ('a', '%'): 0x03ac,
+ ('e', '%'): 0x03ad,
+ ('y', '%'): 0x03ae,
+ ('i', '%'): 0x03af,
+ ('u', '3'): 0x03b0,
+ ('a', '*'): 0x03b1,
+ ('b', '*'): 0x03b2,
+ ('g', '*'): 0x03b3,
+ ('d', '*'): 0x03b4,
+ ('e', '*'): 0x03b5,
+ ('z', '*'): 0x03b6,
+ ('y', '*'): 0x03b7,
+ ('h', '*'): 0x03b8,
+ ('i', '*'): 0x03b9,
+ ('k', '*'): 0x03ba,
+ ('l', '*'): 0x03bb,
+ ('m', '*'): 0x03bc,
+ ('n', '*'): 0x03bd,
+ ('c', '*'): 0x03be,
+ ('o', '*'): 0x03bf,
+ ('p', '*'): 0x03c0,
+ ('r', '*'): 0x03c1,
+ ('*', 's'): 0x03c2,
+ ('s', '*'): 0x03c3,
+ ('t', '*'): 0x03c4,
+ ('u', '*'): 0x03c5,
+ ('f', '*'): 0x03c6,
+ ('x', '*'): 0x03c7,
+ ('q', '*'): 0x03c8,
+ ('w', '*'): 0x03c9,
+ ('j', '*'): 0x03ca,
+ ('v', '*'): 0x03cb,
+ ('o', '%'): 0x03cc,
+ ('u', '%'): 0x03cd,
+ ('w', '%'): 0x03ce,
+ ('\'', 'G'): 0x03d8,
+ (',', 'G'): 0x03d9,
+ ('T', '3'): 0x03da,
+ ('t', '3'): 0x03db,
+ ('M', '3'): 0x03dc,
+ ('m', '3'): 0x03dd,
+ ('K', '3'): 0x03de,
+ ('k', '3'): 0x03df,
+ ('P', '3'): 0x03e0,
+ ('p', '3'): 0x03e1,
+ ('\'', '%'): 0x03f4,
+ ('j', '3'): 0x03f5,
+ ('I', 'O'): 0x0401,
+ ('D', '%'): 0x0402,
+ ('G', '%'): 0x0403,
+ ('I', 'E'): 0x0404,
+ ('D', 'S'): 0x0405,
+ ('I', 'I'): 0x0406,
+ ('Y', 'I'): 0x0407,
+ ('J', '%'): 0x0408,
+ ('L', 'J'): 0x0409,
+ ('N', 'J'): 0x040a,
+ ('T', 's'): 0x040b,
+ ('K', 'J'): 0x040c,
+ ('V', '%'): 0x040e,
+ ('D', 'Z'): 0x040f,
+ ('A', '='): 0x0410,
+ ('B', '='): 0x0411,
+ ('V', '='): 0x0412,
+ ('G', '='): 0x0413,
+ ('D', '='): 0x0414,
+ ('E', '='): 0x0415,
+ ('Z', '%'): 0x0416,
+ ('Z', '='): 0x0417,
+ ('I', '='): 0x0418,
+ ('J', '='): 0x0419,
+ ('K', '='): 0x041a,
+ ('L', '='): 0x041b,
+ ('M', '='): 0x041c,
+ ('N', '='): 0x041d,
+ ('O', '='): 0x041e,
+ ('P', '='): 0x041f,
+ ('R', '='): 0x0420,
+ ('S', '='): 0x0421,
+ ('T', '='): 0x0422,
+ ('U', '='): 0x0423,
+ ('F', '='): 0x0424,
+ ('H', '='): 0x0425,
+ ('C', '='): 0x0426,
+ ('C', '%'): 0x0427,
+ ('S', '%'): 0x0428,
+ ('S', 'c'): 0x0429,
+ ('=', '"'): 0x042a,
+ ('Y', '='): 0x042b,
+ ('%', '"'): 0x042c,
+ ('J', 'E'): 0x042d,
+ ('J', 'U'): 0x042e,
+ ('J', 'A'): 0x042f,
+ ('a', '='): 0x0430,
+ ('b', '='): 0x0431,
+ ('v', '='): 0x0432,
+ ('g', '='): 0x0433,
+ ('d', '='): 0x0434,
+ ('e', '='): 0x0435,
+ ('z', '%'): 0x0436,
+ ('z', '='): 0x0437,
+ ('i', '='): 0x0438,
+ ('j', '='): 0x0439,
+ ('k', '='): 0x043a,
+ ('l', '='): 0x043b,
+ ('m', '='): 0x043c,
+ ('n', '='): 0x043d,
+ ('o', '='): 0x043e,
+ ('p', '='): 0x043f,
+ ('r', '='): 0x0440,
+ ('s', '='): 0x0441,
+ ('t', '='): 0x0442,
+ ('u', '='): 0x0443,
+ ('f', '='): 0x0444,
+ ('h', '='): 0x0445,
+ ('c', '='): 0x0446,
+ ('c', '%'): 0x0447,
+ ('s', '%'): 0x0448,
+ ('s', 'c'): 0x0449,
+ ('=', '\''): 0x044a,
+ ('y', '='): 0x044b,
+ ('%', '\''): 0x044c,
+ ('j', 'e'): 0x044d,
+ ('j', 'u'): 0x044e,
+ ('j', 'a'): 0x044f,
+ ('i', 'o'): 0x0451,
+ ('d', '%'): 0x0452,
+ ('g', '%'): 0x0453,
+ ('i', 'e'): 0x0454,
+ ('d', 's'): 0x0455,
+ ('i', 'i'): 0x0456,
+ ('y', 'i'): 0x0457,
+ ('j', '%'): 0x0458,
+ ('l', 'j'): 0x0459,
+ ('n', 'j'): 0x045a,
+ ('t', 's'): 0x045b,
+ ('k', 'j'): 0x045c,
+ ('v', '%'): 0x045e,
+ ('d', 'z'): 0x045f,
+ ('Y', '3'): 0x0462,
+ ('y', '3'): 0x0463,
+ ('O', '3'): 0x046a,
+ ('o', '3'): 0x046b,
+ ('F', '3'): 0x0472,
+ ('f', '3'): 0x0473,
+ ('V', '3'): 0x0474,
+ ('v', '3'): 0x0475,
+ ('C', '3'): 0x0480,
+ ('c', '3'): 0x0481,
+ ('G', '3'): 0x0490,
+ ('g', '3'): 0x0491,
+ ('A', '+'): 0x05d0,
+ ('B', '+'): 0x05d1,
+ ('G', '+'): 0x05d2,
+ ('D', '+'): 0x05d3,
+ ('H', '+'): 0x05d4,
+ ('W', '+'): 0x05d5,
+ ('Z', '+'): 0x05d6,
+ ('X', '+'): 0x05d7,
+ ('T', 'j'): 0x05d8,
+ ('J', '+'): 0x05d9,
+ ('K', '%'): 0x05da,
+ ('K', '+'): 0x05db,
+ ('L', '+'): 0x05dc,
+ ('M', '%'): 0x05dd,
+ ('M', '+'): 0x05de,
+ ('N', '%'): 0x05df,
+ ('N', '+'): 0x05e0,
+ ('S', '+'): 0x05e1,
+ ('E', '+'): 0x05e2,
+ ('P', '%'): 0x05e3,
+ ('P', '+'): 0x05e4,
+ ('Z', 'j'): 0x05e5,
+ ('Z', 'J'): 0x05e6,
+ ('Q', '+'): 0x05e7,
+ ('R', '+'): 0x05e8,
+ ('S', 'h'): 0x05e9,
+ ('T', '+'): 0x05ea,
+ (',', '+'): 0x060c,
+ (';', '+'): 0x061b,
+ ('?', '+'): 0x061f,
+ ('H', '\''): 0x0621,
+ ('a', 'M'): 0x0622,
+ ('a', 'H'): 0x0623,
+ ('w', 'H'): 0x0624,
+ ('a', 'h'): 0x0625,
+ ('y', 'H'): 0x0626,
+ ('a', '+'): 0x0627,
+ ('b', '+'): 0x0628,
+ ('t', 'm'): 0x0629,
+ ('t', '+'): 0x062a,
+ ('t', 'k'): 0x062b,
+ ('g', '+'): 0x062c,
+ ('h', 'k'): 0x062d,
+ ('x', '+'): 0x062e,
+ ('d', '+'): 0x062f,
+ ('d', 'k'): 0x0630,
+ ('r', '+'): 0x0631,
+ ('z', '+'): 0x0632,
+ ('s', '+'): 0x0633,
+ ('s', 'n'): 0x0634,
+ ('c', '+'): 0x0635,
+ ('d', 'd'): 0x0636,
+ ('t', 'j'): 0x0637,
+ ('z', 'H'): 0x0638,
+ ('e', '+'): 0x0639,
+ ('i', '+'): 0x063a,
+ ('+', '+'): 0x0640,
+ ('f', '+'): 0x0641,
+ ('q', '+'): 0x0642,
+ ('k', '+'): 0x0643,
+ ('l', '+'): 0x0644,
+ ('m', '+'): 0x0645,
+ ('n', '+'): 0x0646,
+ ('h', '+'): 0x0647,
+ ('w', '+'): 0x0648,
+ ('j', '+'): 0x0649,
+ ('y', '+'): 0x064a,
+ (':', '+'): 0x064b,
+ ('"', '+'): 0x064c,
+ ('=', '+'): 0x064d,
+ ('/', '+'): 0x064e,
+ ('\'', '+'): 0x064f,
+ ('1', '+'): 0x0650,
+ ('3', '+'): 0x0651,
+ ('0', '+'): 0x0652,
+ ('a', 'S'): 0x0670,
+ ('p', '+'): 0x067e,
+ ('v', '+'): 0x06a4,
+ ('g', 'f'): 0x06af,
+ ('0', 'a'): 0x06f0,
+ ('1', 'a'): 0x06f1,
+ ('2', 'a'): 0x06f2,
+ ('3', 'a'): 0x06f3,
+ ('4', 'a'): 0x06f4,
+ ('5', 'a'): 0x06f5,
+ ('6', 'a'): 0x06f6,
+ ('7', 'a'): 0x06f7,
+ ('8', 'a'): 0x06f8,
+ ('9', 'a'): 0x06f9,
+ ('B', '.'): 0x1e02,
+ ('b', '.'): 0x1e03,
+ ('B', '_'): 0x1e06,
+ ('b', '_'): 0x1e07,
+ ('D', '.'): 0x1e0a,
+ ('d', '.'): 0x1e0b,
+ ('D', '_'): 0x1e0e,
+ ('d', '_'): 0x1e0f,
+ ('D', ','): 0x1e10,
+ ('d', ','): 0x1e11,
+ ('F', '.'): 0x1e1e,
+ ('f', '.'): 0x1e1f,
+ ('G', '-'): 0x1e20,
+ ('g', '-'): 0x1e21,
+ ('H', '.'): 0x1e22,
+ ('h', '.'): 0x1e23,
+ ('H', ':'): 0x1e26,
+ ('h', ':'): 0x1e27,
+ ('H', ','): 0x1e28,
+ ('h', ','): 0x1e29,
+ ('K', '\''): 0x1e30,
+ ('k', '\''): 0x1e31,
+ ('K', '_'): 0x1e34,
+ ('k', '_'): 0x1e35,
+ ('L', '_'): 0x1e3a,
+ ('l', '_'): 0x1e3b,
+ ('M', '\''): 0x1e3e,
+ ('m', '\''): 0x1e3f,
+ ('M', '.'): 0x1e40,
+ ('m', '.'): 0x1e41,
+ ('N', '.'): 0x1e44,
+ ('n', '.'): 0x1e45,
+ ('N', '_'): 0x1e48,
+ ('n', '_'): 0x1e49,
+ ('P', '\''): 0x1e54,
+ ('p', '\''): 0x1e55,
+ ('P', '.'): 0x1e56,
+ ('p', '.'): 0x1e57,
+ ('R', '.'): 0x1e58,
+ ('r', '.'): 0x1e59,
+ ('R', '_'): 0x1e5e,
+ ('r', '_'): 0x1e5f,
+ ('S', '.'): 0x1e60,
+ ('s', '.'): 0x1e61,
+ ('T', '.'): 0x1e6a,
+ ('t', '.'): 0x1e6b,
+ ('T', '_'): 0x1e6e,
+ ('t', '_'): 0x1e6f,
+ ('V', '?'): 0x1e7c,
+ ('v', '?'): 0x1e7d,
+ ('W', '!'): 0x1e80,
+ ('w', '!'): 0x1e81,
+ ('W', '\''): 0x1e82,
+ ('w', '\''): 0x1e83,
+ ('W', ':'): 0x1e84,
+ ('w', ':'): 0x1e85,
+ ('W', '.'): 0x1e86,
+ ('w', '.'): 0x1e87,
+ ('X', '.'): 0x1e8a,
+ ('x', '.'): 0x1e8b,
+ ('X', ':'): 0x1e8c,
+ ('x', ':'): 0x1e8d,
+ ('Y', '.'): 0x1e8e,
+ ('y', '.'): 0x1e8f,
+ ('Z', '>'): 0x1e90,
+ ('z', '>'): 0x1e91,
+ ('Z', '_'): 0x1e94,
+ ('z', '_'): 0x1e95,
+ ('h', '_'): 0x1e96,
+ ('t', ':'): 0x1e97,
+ ('w', '0'): 0x1e98,
+ ('y', '0'): 0x1e99,
+ ('A', '2'): 0x1ea2,
+ ('a', '2'): 0x1ea3,
+ ('E', '2'): 0x1eba,
+ ('e', '2'): 0x1ebb,
+ ('E', '?'): 0x1ebc,
+ ('e', '?'): 0x1ebd,
+ ('I', '2'): 0x1ec8,
+ ('i', '2'): 0x1ec9,
+ ('O', '2'): 0x1ece,
+ ('o', '2'): 0x1ecf,
+ ('U', '2'): 0x1ee6,
+ ('u', '2'): 0x1ee7,
+ ('Y', '!'): 0x1ef2,
+ ('y', '!'): 0x1ef3,
+ ('Y', '2'): 0x1ef6,
+ ('y', '2'): 0x1ef7,
+ ('Y', '?'): 0x1ef8,
+ ('y', '?'): 0x1ef9,
+ (';', '\''): 0x1f00,
+ (',', '\''): 0x1f01,
+ (';', '!'): 0x1f02,
+ (',', '!'): 0x1f03,
+ ('?', ';'): 0x1f04,
+ ('?', ','): 0x1f05,
+ ('!', ':'): 0x1f06,
+ ('?', ':'): 0x1f07,
+ ('1', 'N'): 0x2002,
+ ('1', 'M'): 0x2003,
+ ('3', 'M'): 0x2004,
+ ('4', 'M'): 0x2005,
+ ('6', 'M'): 0x2006,
+ ('1', 'T'): 0x2009,
+ ('1', 'H'): 0x200a,
+ ('-', '1'): 0x2010,
+ ('-', 'N'): 0x2013,
+ ('-', 'M'): 0x2014,
+ ('-', '3'): 0x2015,
+ ('!', '2'): 0x2016,
+ ('=', '2'): 0x2017,
+ ('\'', '6'): 0x2018,
+ ('\'', '9'): 0x2019,
+ ('.', '9'): 0x201a,
+ ('9', '\''): 0x201b,
+ ('"', '6'): 0x201c,
+ ('"', '9'): 0x201d,
+ (':', '9'): 0x201e,
+ ('9', '"'): 0x201f,
+ ('/', '-'): 0x2020,
+ ('/', '='): 0x2021,
+ ('.', '.'): 0x2025,
+ ('%', '0'): 0x2030,
+ ('1', '\''): 0x2032,
+ ('2', '\''): 0x2033,
+ ('3', '\''): 0x2034,
+ ('1', '"'): 0x2035,
+ ('2', '"'): 0x2036,
+ ('3', '"'): 0x2037,
+ ('C', 'a'): 0x2038,
+ ('<', '1'): 0x2039,
+ ('>', '1'): 0x203a,
+ (':', 'X'): 0x203b,
+ ('\'', '-'): 0x203e,
+ ('/', 'f'): 0x2044,
+ ('0', 'S'): 0x2070,
+ ('4', 'S'): 0x2074,
+ ('5', 'S'): 0x2075,
+ ('6', 'S'): 0x2076,
+ ('7', 'S'): 0x2077,
+ ('8', 'S'): 0x2078,
+ ('9', 'S'): 0x2079,
+ ('+', 'S'): 0x207a,
+ ('-', 'S'): 0x207b,
+ ('=', 'S'): 0x207c,
+ ('(', 'S'): 0x207d,
+ (')', 'S'): 0x207e,
+ ('n', 'S'): 0x207f,
+ ('0', 's'): 0x2080,
+ ('1', 's'): 0x2081,
+ ('2', 's'): 0x2082,
+ ('3', 's'): 0x2083,
+ ('4', 's'): 0x2084,
+ ('5', 's'): 0x2085,
+ ('6', 's'): 0x2086,
+ ('7', 's'): 0x2087,
+ ('8', 's'): 0x2088,
+ ('9', 's'): 0x2089,
+ ('+', 's'): 0x208a,
+ ('-', 's'): 0x208b,
+ ('=', 's'): 0x208c,
+ ('(', 's'): 0x208d,
+ (')', 's'): 0x208e,
+ ('L', 'i'): 0x20a4,
+ ('P', 't'): 0x20a7,
+ ('W', '='): 0x20a9,
+ ('=', 'e'): 0x20ac, # euro
+ ('E', 'u'): 0x20ac, # euro
+ ('=', 'R'): 0x20bd, # rouble
+ ('=', 'P'): 0x20bd, # rouble
+ ('o', 'C'): 0x2103,
+ ('c', 'o'): 0x2105,
+ ('o', 'F'): 0x2109,
+ ('N', '0'): 0x2116,
+ ('P', 'O'): 0x2117,
+ ('R', 'x'): 0x211e,
+ ('S', 'M'): 0x2120,
+ ('T', 'M'): 0x2122,
+ ('O', 'm'): 0x2126,
+ ('A', 'O'): 0x212b,
+ ('1', '3'): 0x2153,
+ ('2', '3'): 0x2154,
+ ('1', '5'): 0x2155,
+ ('2', '5'): 0x2156,
+ ('3', '5'): 0x2157,
+ ('4', '5'): 0x2158,
+ ('1', '6'): 0x2159,
+ ('5', '6'): 0x215a,
+ ('1', '8'): 0x215b,
+ ('3', '8'): 0x215c,
+ ('5', '8'): 0x215d,
+ ('7', '8'): 0x215e,
+ ('1', 'R'): 0x2160,
+ ('2', 'R'): 0x2161,
+ ('3', 'R'): 0x2162,
+ ('4', 'R'): 0x2163,
+ ('5', 'R'): 0x2164,
+ ('6', 'R'): 0x2165,
+ ('7', 'R'): 0x2166,
+ ('8', 'R'): 0x2167,
+ ('9', 'R'): 0x2168,
+ ('a', 'R'): 0x2169,
+ ('b', 'R'): 0x216a,
+ ('c', 'R'): 0x216b,
+ ('1', 'r'): 0x2170,
+ ('2', 'r'): 0x2171,
+ ('3', 'r'): 0x2172,
+ ('4', 'r'): 0x2173,
+ ('5', 'r'): 0x2174,
+ ('6', 'r'): 0x2175,
+ ('7', 'r'): 0x2176,
+ ('8', 'r'): 0x2177,
+ ('9', 'r'): 0x2178,
+ ('a', 'r'): 0x2179,
+ ('b', 'r'): 0x217a,
+ ('c', 'r'): 0x217b,
+ ('<', '-'): 0x2190,
+ ('-', '!'): 0x2191,
+ ('-', '>'): 0x2192,
+ ('-', 'v'): 0x2193,
+ ('<', '>'): 0x2194,
+ ('U', 'D'): 0x2195,
+ ('<', '='): 0x21d0,
+ ('=', '>'): 0x21d2,
+ ('=', '='): 0x21d4,
+ ('F', 'A'): 0x2200,
+ ('d', 'P'): 0x2202,
+ ('T', 'E'): 0x2203,
+ ('/', '0'): 0x2205,
+ ('D', 'E'): 0x2206,
+ ('N', 'B'): 0x2207,
+ ('(', '-'): 0x2208,
+ ('-', ')'): 0x220b,
+ ('*', 'P'): 0x220f,
+ ('+', 'Z'): 0x2211,
+ ('-', '2'): 0x2212,
+ ('-', '+'): 0x2213,
+ ('*', '-'): 0x2217,
+ ('O', 'b'): 0x2218,
+ ('S', 'b'): 0x2219,
+ ('R', 'T'): 0x221a,
+ ('0', '('): 0x221d,
+ ('0', '0'): 0x221e,
+ ('-', 'L'): 0x221f,
+ ('-', 'V'): 0x2220,
+ ('P', 'P'): 0x2225,
+ ('A', 'N'): 0x2227,
+ ('O', 'R'): 0x2228,
+ ('(', 'U'): 0x2229,
+ (')', 'U'): 0x222a,
+ ('I', 'n'): 0x222b,
+ ('D', 'I'): 0x222c,
+ ('I', 'o'): 0x222e,
+ ('.', ':'): 0x2234,
+ (':', '.'): 0x2235,
+ (':', 'R'): 0x2236,
+ (':', ':'): 0x2237,
+ ('?', '1'): 0x223c,
+ ('C', 'G'): 0x223e,
+ ('?', '-'): 0x2243,
+ ('?', '='): 0x2245,
+ ('?', '2'): 0x2248,
+ ('=', '?'): 0x224c,
+ ('H', 'I'): 0x2253,
+ ('!', '='): 0x2260,
+ ('=', '3'): 0x2261,
+ ('=', '<'): 0x2264,
+ ('>', '='): 0x2265,
+ ('<', '*'): 0x226a,
+ ('*', '>'): 0x226b,
+ ('!', '<'): 0x226e,
+ ('!', '>'): 0x226f,
+ ('(', 'C'): 0x2282,
+ (')', 'C'): 0x2283,
+ ('(', '_'): 0x2286,
+ (')', '_'): 0x2287,
+ ('0', '.'): 0x2299,
+ ('0', '2'): 0x229a,
+ ('-', 'T'): 0x22a5,
+ ('.', 'P'): 0x22c5,
+ (':', '3'): 0x22ee,
+ ('.', '3'): 0x22ef,
+ ('E', 'h'): 0x2302,
+ ('<', '7'): 0x2308,
+ ('>', '7'): 0x2309,
+ ('7', '<'): 0x230a,
+ ('7', '>'): 0x230b,
+ ('N', 'I'): 0x2310,
+ ('(', 'A'): 0x2312,
+ ('T', 'R'): 0x2315,
+ ('I', 'u'): 0x2320,
+ ('I', 'l'): 0x2321,
+ ('<', '/'): 0x2329,
+ ('/', '>'): 0x232a,
+ ('V', 's'): 0x2423,
+ ('1', 'h'): 0x2440,
+ ('3', 'h'): 0x2441,
+ ('2', 'h'): 0x2442,
+ ('4', 'h'): 0x2443,
+ ('1', 'j'): 0x2446,
+ ('2', 'j'): 0x2447,
+ ('3', 'j'): 0x2448,
+ ('4', 'j'): 0x2449,
+ ('1', '.'): 0x2488,
+ ('2', '.'): 0x2489,
+ ('3', '.'): 0x248a,
+ ('4', '.'): 0x248b,
+ ('5', '.'): 0x248c,
+ ('6', '.'): 0x248d,
+ ('7', '.'): 0x248e,
+ ('8', '.'): 0x248f,
+ ('9', '.'): 0x2490,
+ ('h', 'h'): 0x2500,
+ ('H', 'H'): 0x2501,
+ ('v', 'v'): 0x2502,
+ ('V', 'V'): 0x2503,
+ ('3', '-'): 0x2504,
+ ('3', '_'): 0x2505,
+ ('3', '!'): 0x2506,
+ ('3', '/'): 0x2507,
+ ('4', '-'): 0x2508,
+ ('4', '_'): 0x2509,
+ ('4', '!'): 0x250a,
+ ('4', '/'): 0x250b,
+ ('d', 'r'): 0x250c,
+ ('d', 'R'): 0x250d,
+ ('D', 'r'): 0x250e,
+ ('D', 'R'): 0x250f,
+ ('d', 'l'): 0x2510,
+ ('d', 'L'): 0x2511,
+ ('D', 'l'): 0x2512,
+ ('L', 'D'): 0x2513,
+ ('u', 'r'): 0x2514,
+ ('u', 'R'): 0x2515,
+ ('U', 'r'): 0x2516,
+ ('U', 'R'): 0x2517,
+ ('u', 'l'): 0x2518,
+ ('u', 'L'): 0x2519,
+ ('U', 'l'): 0x251a,
+ ('U', 'L'): 0x251b,
+ ('v', 'r'): 0x251c,
+ ('v', 'R'): 0x251d,
+ ('V', 'r'): 0x2520,
+ ('V', 'R'): 0x2523,
+ ('v', 'l'): 0x2524,
+ ('v', 'L'): 0x2525,
+ ('V', 'l'): 0x2528,
+ ('V', 'L'): 0x252b,
+ ('d', 'h'): 0x252c,
+ ('d', 'H'): 0x252f,
+ ('D', 'h'): 0x2530,
+ ('D', 'H'): 0x2533,
+ ('u', 'h'): 0x2534,
+ ('u', 'H'): 0x2537,
+ ('U', 'h'): 0x2538,
+ ('U', 'H'): 0x253b,
+ ('v', 'h'): 0x253c,
+ ('v', 'H'): 0x253f,
+ ('V', 'h'): 0x2542,
+ ('V', 'H'): 0x254b,
+ ('F', 'D'): 0x2571,
+ ('B', 'D'): 0x2572,
+ ('T', 'B'): 0x2580,
+ ('L', 'B'): 0x2584,
+ ('F', 'B'): 0x2588,
+ ('l', 'B'): 0x258c,
+ ('R', 'B'): 0x2590,
+ ('.', 'S'): 0x2591,
+ (':', 'S'): 0x2592,
+ ('?', 'S'): 0x2593,
+ ('f', 'S'): 0x25a0,
+ ('O', 'S'): 0x25a1,
+ ('R', 'O'): 0x25a2,
+ ('R', 'r'): 0x25a3,
+ ('R', 'F'): 0x25a4,
+ ('R', 'Y'): 0x25a5,
+ ('R', 'H'): 0x25a6,
+ ('R', 'Z'): 0x25a7,
+ ('R', 'K'): 0x25a8,
+ ('R', 'X'): 0x25a9,
+ ('s', 'B'): 0x25aa,
+ ('S', 'R'): 0x25ac,
+ ('O', 'r'): 0x25ad,
+ ('U', 'T'): 0x25b2,
+ ('u', 'T'): 0x25b3,
+ ('P', 'R'): 0x25b6,
+ ('T', 'r'): 0x25b7,
+ ('D', 't'): 0x25bc,
+ ('d', 'T'): 0x25bd,
+ ('P', 'L'): 0x25c0,
+ ('T', 'l'): 0x25c1,
+ ('D', 'b'): 0x25c6,
+ ('D', 'w'): 0x25c7,
+ ('L', 'Z'): 0x25ca,
+ ('0', 'm'): 0x25cb,
+ ('0', 'o'): 0x25ce,
+ ('0', 'M'): 0x25cf,
+ ('0', 'L'): 0x25d0,
+ ('0', 'R'): 0x25d1,
+ ('S', 'n'): 0x25d8,
+ ('I', 'c'): 0x25d9,
+ ('F', 'd'): 0x25e2,
+ ('B', 'd'): 0x25e3,
+ ('*', '2'): 0x2605,
+ ('*', '1'): 0x2606,
+ ('<', 'H'): 0x261c,
+ ('>', 'H'): 0x261e,
+ ('0', 'u'): 0x263a,
+ ('0', 'U'): 0x263b,
+ ('S', 'U'): 0x263c,
+ ('F', 'm'): 0x2640,
+ ('M', 'l'): 0x2642,
+ ('c', 'S'): 0x2660,
+ ('c', 'H'): 0x2661,
+ ('c', 'D'): 0x2662,
+ ('c', 'C'): 0x2663,
+ ('M', 'd'): 0x2669,
+ ('M', '8'): 0x266a,
+ ('M', '2'): 0x266b,
+ ('M', 'b'): 0x266d,
+ ('M', 'x'): 0x266e,
+ ('M', 'X'): 0x266f,
+ ('O', 'K'): 0x2713,
+ ('X', 'X'): 0x2717,
+ ('-', 'X'): 0x2720,
+ ('I', 'S'): 0x3000,
+ (',', '_'): 0x3001,
+ ('.', '_'): 0x3002,
+ ('+', '"'): 0x3003,
+ ('+', '_'): 0x3004,
+ ('*', '_'): 0x3005,
+ (';', '_'): 0x3006,
+ ('0', '_'): 0x3007,
+ ('<', '+'): 0x300a,
+ ('>', '+'): 0x300b,
+ ('<', '\''): 0x300c,
+ ('>', '\''): 0x300d,
+ ('<', '"'): 0x300e,
+ ('>', '"'): 0x300f,
+ ('(', '"'): 0x3010,
+ (')', '"'): 0x3011,
+ ('=', 'T'): 0x3012,
+ ('=', '_'): 0x3013,
+ ('(', '\''): 0x3014,
+ (')', '\''): 0x3015,
+ ('(', 'I'): 0x3016,
+ (')', 'I'): 0x3017,
+ ('-', '?'): 0x301c,
+ ('A', '5'): 0x3041,
+ ('a', '5'): 0x3042,
+ ('I', '5'): 0x3043,
+ ('i', '5'): 0x3044,
+ ('U', '5'): 0x3045,
+ ('u', '5'): 0x3046,
+ ('E', '5'): 0x3047,
+ ('e', '5'): 0x3048,
+ ('O', '5'): 0x3049,
+ ('o', '5'): 0x304a,
+ ('k', 'a'): 0x304b,
+ ('g', 'a'): 0x304c,
+ ('k', 'i'): 0x304d,
+ ('g', 'i'): 0x304e,
+ ('k', 'u'): 0x304f,
+ ('g', 'u'): 0x3050,
+ ('k', 'e'): 0x3051,
+ ('g', 'e'): 0x3052,
+ ('k', 'o'): 0x3053,
+ ('g', 'o'): 0x3054,
+ ('s', 'a'): 0x3055,
+ ('z', 'a'): 0x3056,
+ ('s', 'i'): 0x3057,
+ ('z', 'i'): 0x3058,
+ ('s', 'u'): 0x3059,
+ ('z', 'u'): 0x305a,
+ ('s', 'e'): 0x305b,
+ ('z', 'e'): 0x305c,
+ ('s', 'o'): 0x305d,
+ ('z', 'o'): 0x305e,
+ ('t', 'a'): 0x305f,
+ ('d', 'a'): 0x3060,
+ ('t', 'i'): 0x3061,
+ ('d', 'i'): 0x3062,
+ ('t', 'U'): 0x3063,
+ ('t', 'u'): 0x3064,
+ ('d', 'u'): 0x3065,
+ ('t', 'e'): 0x3066,
+ ('d', 'e'): 0x3067,
+ ('t', 'o'): 0x3068,
+ ('d', 'o'): 0x3069,
+ ('n', 'a'): 0x306a,
+ ('n', 'i'): 0x306b,
+ ('n', 'u'): 0x306c,
+ ('n', 'e'): 0x306d,
+ ('n', 'o'): 0x306e,
+ ('h', 'a'): 0x306f,
+ ('b', 'a'): 0x3070,
+ ('p', 'a'): 0x3071,
+ ('h', 'i'): 0x3072,
+ ('b', 'i'): 0x3073,
+ ('p', 'i'): 0x3074,
+ ('h', 'u'): 0x3075,
+ ('b', 'u'): 0x3076,
+ ('p', 'u'): 0x3077,
+ ('h', 'e'): 0x3078,
+ ('b', 'e'): 0x3079,
+ ('p', 'e'): 0x307a,
+ ('h', 'o'): 0x307b,
+ ('b', 'o'): 0x307c,
+ ('p', 'o'): 0x307d,
+ ('m', 'a'): 0x307e,
+ ('m', 'i'): 0x307f,
+ ('m', 'u'): 0x3080,
+ ('m', 'e'): 0x3081,
+ ('m', 'o'): 0x3082,
+ ('y', 'A'): 0x3083,
+ ('y', 'a'): 0x3084,
+ ('y', 'U'): 0x3085,
+ ('y', 'u'): 0x3086,
+ ('y', 'O'): 0x3087,
+ ('y', 'o'): 0x3088,
+ ('r', 'a'): 0x3089,
+ ('r', 'i'): 0x308a,
+ ('r', 'u'): 0x308b,
+ ('r', 'e'): 0x308c,
+ ('r', 'o'): 0x308d,
+ ('w', 'A'): 0x308e,
+ ('w', 'a'): 0x308f,
+ ('w', 'i'): 0x3090,
+ ('w', 'e'): 0x3091,
+ ('w', 'o'): 0x3092,
+ ('n', '5'): 0x3093,
+ ('v', 'u'): 0x3094,
+ ('"', '5'): 0x309b,
+ ('0', '5'): 0x309c,
+ ('*', '5'): 0x309d,
+ ('+', '5'): 0x309e,
+ ('a', '6'): 0x30a1,
+ ('A', '6'): 0x30a2,
+ ('i', '6'): 0x30a3,
+ ('I', '6'): 0x30a4,
+ ('u', '6'): 0x30a5,
+ ('U', '6'): 0x30a6,
+ ('e', '6'): 0x30a7,
+ ('E', '6'): 0x30a8,
+ ('o', '6'): 0x30a9,
+ ('O', '6'): 0x30aa,
+ ('K', 'a'): 0x30ab,
+ ('G', 'a'): 0x30ac,
+ ('K', 'i'): 0x30ad,
+ ('G', 'i'): 0x30ae,
+ ('K', 'u'): 0x30af,
+ ('G', 'u'): 0x30b0,
+ ('K', 'e'): 0x30b1,
+ ('G', 'e'): 0x30b2,
+ ('K', 'o'): 0x30b3,
+ ('G', 'o'): 0x30b4,
+ ('S', 'a'): 0x30b5,
+ ('Z', 'a'): 0x30b6,
+ ('S', 'i'): 0x30b7,
+ ('Z', 'i'): 0x30b8,
+ ('S', 'u'): 0x30b9,
+ ('Z', 'u'): 0x30ba,
+ ('S', 'e'): 0x30bb,
+ ('Z', 'e'): 0x30bc,
+ ('S', 'o'): 0x30bd,
+ ('Z', 'o'): 0x30be,
+ ('T', 'a'): 0x30bf,
+ ('D', 'a'): 0x30c0,
+ ('T', 'i'): 0x30c1,
+ ('D', 'i'): 0x30c2,
+ ('T', 'U'): 0x30c3,
+ ('T', 'u'): 0x30c4,
+ ('D', 'u'): 0x30c5,
+ ('T', 'e'): 0x30c6,
+ ('D', 'e'): 0x30c7,
+ ('T', 'o'): 0x30c8,
+ ('D', 'o'): 0x30c9,
+ ('N', 'a'): 0x30ca,
+ ('N', 'i'): 0x30cb,
+ ('N', 'u'): 0x30cc,
+ ('N', 'e'): 0x30cd,
+ ('N', 'o'): 0x30ce,
+ ('H', 'a'): 0x30cf,
+ ('B', 'a'): 0x30d0,
+ ('P', 'a'): 0x30d1,
+ ('H', 'i'): 0x30d2,
+ ('B', 'i'): 0x30d3,
+ ('P', 'i'): 0x30d4,
+ ('H', 'u'): 0x30d5,
+ ('B', 'u'): 0x30d6,
+ ('P', 'u'): 0x30d7,
+ ('H', 'e'): 0x30d8,
+ ('B', 'e'): 0x30d9,
+ ('P', 'e'): 0x30da,
+ ('H', 'o'): 0x30db,
+ ('B', 'o'): 0x30dc,
+ ('P', 'o'): 0x30dd,
+ ('M', 'a'): 0x30de,
+ ('M', 'i'): 0x30df,
+ ('M', 'u'): 0x30e0,
+ ('M', 'e'): 0x30e1,
+ ('M', 'o'): 0x30e2,
+ ('Y', 'A'): 0x30e3,
+ ('Y', 'a'): 0x30e4,
+ ('Y', 'U'): 0x30e5,
+ ('Y', 'u'): 0x30e6,
+ ('Y', 'O'): 0x30e7,
+ ('Y', 'o'): 0x30e8,
+ ('R', 'a'): 0x30e9,
+ ('R', 'i'): 0x30ea,
+ ('R', 'u'): 0x30eb,
+ ('R', 'e'): 0x30ec,
+ ('R', 'o'): 0x30ed,
+ ('W', 'A'): 0x30ee,
+ ('W', 'a'): 0x30ef,
+ ('W', 'i'): 0x30f0,
+ ('W', 'e'): 0x30f1,
+ ('W', 'o'): 0x30f2,
+ ('N', '6'): 0x30f3,
+ ('V', 'u'): 0x30f4,
+ ('K', 'A'): 0x30f5,
+ ('K', 'E'): 0x30f6,
+ ('V', 'a'): 0x30f7,
+ ('V', 'i'): 0x30f8,
+ ('V', 'e'): 0x30f9,
+ ('V', 'o'): 0x30fa,
+ ('.', '6'): 0x30fb,
+ ('-', '6'): 0x30fc,
+ ('*', '6'): 0x30fd,
+ ('+', '6'): 0x30fe,
+ ('b', '4'): 0x3105,
+ ('p', '4'): 0x3106,
+ ('m', '4'): 0x3107,
+ ('f', '4'): 0x3108,
+ ('d', '4'): 0x3109,
+ ('t', '4'): 0x310a,
+ ('n', '4'): 0x310b,
+ ('l', '4'): 0x310c,
+ ('g', '4'): 0x310d,
+ ('k', '4'): 0x310e,
+ ('h', '4'): 0x310f,
+ ('j', '4'): 0x3110,
+ ('q', '4'): 0x3111,
+ ('x', '4'): 0x3112,
+ ('z', 'h'): 0x3113,
+ ('c', 'h'): 0x3114,
+ ('s', 'h'): 0x3115,
+ ('r', '4'): 0x3116,
+ ('z', '4'): 0x3117,
+ ('c', '4'): 0x3118,
+ ('s', '4'): 0x3119,
+ ('a', '4'): 0x311a,
+ ('o', '4'): 0x311b,
+ ('e', '4'): 0x311c,
+ ('a', 'i'): 0x311e,
+ ('e', 'i'): 0x311f,
+ ('a', 'u'): 0x3120,
+ ('o', 'u'): 0x3121,
+ ('a', 'n'): 0x3122,
+ ('e', 'n'): 0x3123,
+ ('a', 'N'): 0x3124,
+ ('e', 'N'): 0x3125,
+ ('e', 'r'): 0x3126,
+ ('i', '4'): 0x3127,
+ ('u', '4'): 0x3128,
+ ('i', 'u'): 0x3129,
+ ('v', '4'): 0x312a,
+ ('n', 'G'): 0x312b,
+ ('g', 'n'): 0x312c,
+ ('1', 'c'): 0x3220,
+ ('2', 'c'): 0x3221,
+ ('3', 'c'): 0x3222,
+ ('4', 'c'): 0x3223,
+ ('5', 'c'): 0x3224,
+ ('6', 'c'): 0x3225,
+ ('7', 'c'): 0x3226,
+ ('8', 'c'): 0x3227,
+ ('9', 'c'): 0x3228,
+
+ # code points 0xe000 - 0xefff excluded, they have no assigned
+ # characters, only used in proposals.
+ ('f', 'f'): 0xfb00,
+ ('f', 'i'): 0xfb01,
+ ('f', 'l'): 0xfb02,
+ ('f', 't'): 0xfb05,
+ ('s', 't'): 0xfb06,
+
+ # Vim 5.x compatible digraphs that don't conflict with the above
+ ('~', '!'): 161,
+ ('c', '|'): 162,
+ ('$', '$'): 163,
+ ('o', 'x'): 164, # currency symbol in ISO 8859-1
+ ('Y', '-'): 165,
+ ('|', '|'): 166,
+ ('c', 'O'): 169,
+ ('-', ','): 172,
+ ('-', '='): 175,
+ ('~', 'o'): 176,
+ ('2', '2'): 178,
+ ('3', '3'): 179,
+ ('p', 'p'): 182,
+ ('~', '.'): 183,
+ ('1', '1'): 185,
+ ('~', '?'): 191,
+ ('A', '`'): 192,
+ ('A', '^'): 194,
+ ('A', '~'): 195,
+ ('A', '"'): 196,
+ ('A', '@'): 197,
+ ('E', '`'): 200,
+ ('E', '^'): 202,
+ ('E', '"'): 203,
+ ('I', '`'): 204,
+ ('I', '^'): 206,
+ ('I', '"'): 207,
+ ('N', '~'): 209,
+ ('O', '`'): 210,
+ ('O', '^'): 212,
+ ('O', '~'): 213,
+ ('/', '\\'): 215, # multiplication symbol in ISO 8859-1
+ ('U', '`'): 217,
+ ('U', '^'): 219,
+ ('I', 'p'): 222,
+ ('a', '`'): 224,
+ ('a', '^'): 226,
+ ('a', '~'): 227,
+ ('a', '"'): 228,
+ ('a', '@'): 229,
+ ('e', '`'): 232,
+ ('e', '^'): 234,
+ ('e', '"'): 235,
+ ('i', '`'): 236,
+ ('i', '^'): 238,
+ ('n', '~'): 241,
+ ('o', '`'): 242,
+ ('o', '^'): 244,
+ ('o', '~'): 245,
+ ('u', '`'): 249,
+ ('u', '^'): 251,
+ ('y', '"'): 255,
+}
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/input_processor.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/input_processor.py
index e2d706d915..51a3110827 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/input_processor.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/input_processor.py
@@ -4,20 +4,20 @@ An :class:`~.InputProcessor` receives callbacks for the keystrokes parsed from
the input in the :class:`~prompt_toolkit.inputstream.InputStream` instance.
The `InputProcessor` will according to the implemented keybindings call the
-correct callbacks when new key presses are feed through `feed`.
+correct callbacks when new key presses are feed through `feed`.
"""
from __future__ import unicode_literals
from prompt_toolkit.buffer import EditReadOnlyBuffer
-from prompt_toolkit.filters.cli import ViNavigationMode
-from prompt_toolkit.keys import Keys, Key
-from prompt_toolkit.utils import Event
+from prompt_toolkit.filters.cli import ViNavigationMode
+from prompt_toolkit.keys import Keys, Key
+from prompt_toolkit.utils import Event
from .registry import BaseRegistry
-
-from collections import deque
-from six.moves import range
+
+from collections import deque
+from six.moves import range
import weakref
-import six
+import six
__all__ = (
'InputProcessor',
@@ -27,16 +27,16 @@ __all__ = (
class KeyPress(object):
"""
- :param key: A `Keys` instance or text (one character).
+ :param key: A `Keys` instance or text (one character).
:param data: The received string on stdin. (Often vt100 escape codes.)
"""
- def __init__(self, key, data=None):
- assert isinstance(key, (six.text_type, Key))
- assert data is None or isinstance(data, six.text_type)
-
- if data is None:
- data = key.name if isinstance(key, Key) else key
-
+ def __init__(self, key, data=None):
+ assert isinstance(key, (six.text_type, Key))
+ assert data is None or isinstance(data, six.text_type)
+
+ if data is None:
+ data = key.name if isinstance(key, Key) else key
+
self.key = key
self.data = data
@@ -58,12 +58,12 @@ class InputProcessor(object):
p = InputProcessor(registry)
# Send keys into the processor.
- p.feed(KeyPress(Keys.ControlX, '\x18'))
- p.feed(KeyPress(Keys.ControlC, '\x03')
+ p.feed(KeyPress(Keys.ControlX, '\x18'))
+ p.feed(KeyPress(Keys.ControlC, '\x03')
+
+ # Process all the keys in the queue.
+ p.process_keys()
- # Process all the keys in the queue.
- p.process_keys()
-
# Now the ControlX-ControlC callback will be called if this sequence is
# registered in the registry.
@@ -72,20 +72,20 @@ class InputProcessor(object):
"""
def __init__(self, registry, cli_ref):
assert isinstance(registry, BaseRegistry)
-
+
self._registry = registry
self._cli_ref = cli_ref
-
- self.beforeKeyPress = Event(self)
- self.afterKeyPress = Event(self)
-
- # The queue of keys not yet send to our _process generator/state machine.
- self.input_queue = deque()
-
- # The key buffer that is matched in the generator state machine.
- # (This is at at most the amount of keys that make up for one key binding.)
- self.key_buffer = []
-
+
+ self.beforeKeyPress = Event(self)
+ self.afterKeyPress = Event(self)
+
+ # The queue of keys not yet send to our _process generator/state machine.
+ self.input_queue = deque()
+
+ # The key buffer that is matched in the generator state machine.
+ # (This is at at most the amount of keys that make up for one key binding.)
+ self.key_buffer = []
+
# Simple macro recording. (Like readline does.)
self.record_macro = False
self.macro = []
@@ -125,7 +125,7 @@ class InputProcessor(object):
cli = self._cli_ref()
# Try match, with mode flag
- return [b for b in self._registry.get_bindings_for_keys(keys) if b.filter(cli)]
+ return [b for b in self._registry.get_bindings_for_keys(keys) if b.filter(cli)]
def _is_prefix_of_longer_match(self, key_presses):
"""
@@ -149,7 +149,7 @@ class InputProcessor(object):
Coroutine implementing the key match algorithm. Key strokes are sent
into this generator, and it calls the appropriate handlers.
"""
- buffer = self.key_buffer
+ buffer = self.key_buffer
retry = False
while True:
@@ -174,7 +174,7 @@ class InputProcessor(object):
# Exact matches found, call handler.
if not is_prefix_of_longer_match and matches:
self._call_handler(matches[-1], key_sequence=buffer[:])
- del buffer[:] # Keep reference.
+ del buffer[:] # Keep reference.
# No match found.
elif not is_prefix_of_longer_match and not matches:
@@ -186,70 +186,70 @@ class InputProcessor(object):
matches = self._get_matches(buffer[:i])
if matches:
self._call_handler(matches[-1], key_sequence=buffer[:i])
- del buffer[:i]
+ del buffer[:i]
found = True
- break
+ break
if not found:
- del buffer[:1]
+ del buffer[:1]
- def feed(self, key_press):
+ def feed(self, key_press):
"""
- Add a new :class:`KeyPress` to the input queue.
- (Don't forget to call `process_keys` in order to process the queue.)
+ Add a new :class:`KeyPress` to the input queue.
+ (Don't forget to call `process_keys` in order to process the queue.)
"""
assert isinstance(key_press, KeyPress)
- self.input_queue.append(key_press)
-
- def process_keys(self):
- """
- Process all the keys in the `input_queue`.
- (To be called after `feed`.)
-
- Note: because of the `feed`/`process_keys` separation, it is
- possible to call `feed` from inside a key binding.
- This function keeps looping until the queue is empty.
- """
- while self.input_queue:
- key_press = self.input_queue.popleft()
-
- if key_press.key != Keys.CPRResponse:
- self.beforeKeyPress.fire()
-
- self._process_coroutine.send(key_press)
-
- if key_press.key != Keys.CPRResponse:
- self.afterKeyPress.fire()
-
- # Invalidate user interface.
- cli = self._cli_ref()
- if cli:
- cli.invalidate()
-
+ self.input_queue.append(key_press)
+
+ def process_keys(self):
+ """
+ Process all the keys in the `input_queue`.
+ (To be called after `feed`.)
+
+ Note: because of the `feed`/`process_keys` separation, it is
+ possible to call `feed` from inside a key binding.
+ This function keeps looping until the queue is empty.
+ """
+ while self.input_queue:
+ key_press = self.input_queue.popleft()
+
+ if key_press.key != Keys.CPRResponse:
+ self.beforeKeyPress.fire()
+
+ self._process_coroutine.send(key_press)
+
+ if key_press.key != Keys.CPRResponse:
+ self.afterKeyPress.fire()
+
+ # Invalidate user interface.
+ cli = self._cli_ref()
+ if cli:
+ cli.invalidate()
+
def _call_handler(self, handler, key_sequence=None):
was_recording = self.record_macro
arg = self.arg
self.arg = None
- event = KeyPressEvent(
- weakref.ref(self), arg=arg, key_sequence=key_sequence,
- previous_key_sequence=self._previous_key_sequence,
- is_repeat=(handler == self._previous_handler))
-
- # Save the state of the current buffer.
- cli = event.cli # Can be `None` (In unit-tests only.)
-
- if handler.save_before(event) and cli:
- cli.current_buffer.save_to_undo_stack()
-
- # Call handler.
+ event = KeyPressEvent(
+ weakref.ref(self), arg=arg, key_sequence=key_sequence,
+ previous_key_sequence=self._previous_key_sequence,
+ is_repeat=(handler == self._previous_handler))
+
+ # Save the state of the current buffer.
+ cli = event.cli # Can be `None` (In unit-tests only.)
+
+ if handler.save_before(event) and cli:
+ cli.current_buffer.save_to_undo_stack()
+
+ # Call handler.
try:
handler.call(event)
- self._fix_vi_cursor_position(event)
+ self._fix_vi_cursor_position(event)
except EditReadOnlyBuffer:
- # When a key binding does an attempt to change a buffer which is
- # read-only, we can just silently ignore that.
+ # When a key binding does an attempt to change a buffer which is
+ # read-only, we can just silently ignore that.
pass
self._previous_key_sequence = key_sequence
@@ -260,29 +260,29 @@ class InputProcessor(object):
if self.record_macro and was_recording:
self.macro.extend(key_sequence)
- def _fix_vi_cursor_position(self, event):
- """
- After every command, make sure that if we are in Vi navigation mode, we
- never put the cursor after the last character of a line. (Unless it's
- an empty line.)
- """
+ def _fix_vi_cursor_position(self, event):
+ """
+ After every command, make sure that if we are in Vi navigation mode, we
+ never put the cursor after the last character of a line. (Unless it's
+ an empty line.)
+ """
cli = self._cli_ref()
- if cli:
- buff = cli.current_buffer
- preferred_column = buff.preferred_column
-
- if (ViNavigationMode()(event.cli) and
- buff.document.is_cursor_at_the_end_of_line and
- len(buff.document.current_line) > 0):
- buff.cursor_position -= 1
-
- # Set the preferred_column for arrow up/down again.
- # (This was cleared after changing the cursor position.)
- buff.preferred_column = preferred_column
-
-
-
-class KeyPressEvent(object):
+ if cli:
+ buff = cli.current_buffer
+ preferred_column = buff.preferred_column
+
+ if (ViNavigationMode()(event.cli) and
+ buff.document.is_cursor_at_the_end_of_line and
+ len(buff.document.current_line) > 0):
+ buff.cursor_position -= 1
+
+ # Set the preferred_column for arrow up/down again.
+ # (This was cleared after changing the cursor position.)
+ buff.preferred_column = preferred_column
+
+
+
+class KeyPressEvent(object):
"""
Key press event, delivered to key bindings.
@@ -304,7 +304,7 @@ class KeyPressEvent(object):
self._arg = arg
def __repr__(self):
- return 'KeyPressEvent(arg=%r, key_sequence=%r, is_repeat=%r)' % (
+ return 'KeyPressEvent(arg=%r, key_sequence=%r, is_repeat=%r)' % (
self.arg, self.key_sequence, self.is_repeat)
@property
@@ -334,24 +334,24 @@ class KeyPressEvent(object):
"""
Repetition argument.
"""
- if self._arg == '-':
- return -1
-
- result = int(self._arg or 1)
-
- # Don't exceed a million.
- if int(result) >= 1000000:
- result = 1
-
- return result
-
- @property
- def arg_present(self):
- """
- True if repetition argument was explicitly provided.
- """
- return self._arg is not None
-
+ if self._arg == '-':
+ return -1
+
+ result = int(self._arg or 1)
+
+ # Don't exceed a million.
+ if int(result) >= 1000000:
+ result = 1
+
+ return result
+
+ @property
+ def arg_present(self):
+ """
+ True if repetition argument was explicitly provided.
+ """
+ return self._arg is not None
+
def append_to_arg_count(self, data):
"""
Add digit to the input argument.
@@ -361,12 +361,12 @@ class KeyPressEvent(object):
assert data in '-0123456789'
current = self._arg
- if data == '-':
- assert current is None or current == '-'
- result = data
- elif current is None:
- result = data
+ if data == '-':
+ assert current is None or current == '-'
+ result = data
+ elif current is None:
+ result = data
else:
- result = "%s%s" % (current, data)
+ result = "%s%s" % (current, data)
self.input_processor.arg = result
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/manager.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/manager.py
index dc0e18e3cb..83612c2a5c 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/manager.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/manager.py
@@ -37,12 +37,12 @@ class KeyBindingManager(object):
:param enable_extra_page_navigation: Filter for enabling extra page navigation.
(Bindings for up/down scrolling through long pages, like in Emacs or Vi.)
:param enable_auto_suggest_bindings: Filter to enable fish-style suggestions.
-
- :param enable_vi_mode: Deprecated!
+
+ :param enable_vi_mode: Deprecated!
"""
def __init__(self,
registry=None, # XXX: not used anymore.
- enable_vi_mode=None, # (`enable_vi_mode` is deprecated.)
+ enable_vi_mode=None, # (`enable_vi_mode` is deprecated.)
enable_all=True, #
get_search_state=None,
enable_abort_and_exit_bindings=False,
@@ -76,7 +76,7 @@ class KeyBindingManager(object):
def for_prompt(cls, **kw):
"""
Create a ``KeyBindingManager`` with the defaults for an input prompt.
- This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D),
+ This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D),
incremental search and auto suggestions.
(Not for full screen applications.)
@@ -88,9 +88,9 @@ class KeyBindingManager(object):
return cls(**kw)
def reset(self, cli):
- # For backwards compatibility.
- pass
-
- def get_vi_state(self, cli):
- # Deprecated!
- return cli.vi_state
+ # For backwards compatibility.
+ pass
+
+ def get_vi_state(self, cli):
+ # Deprecated!
+ return cli.vi_state
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/registry.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/registry.py
index f7258a822d..24d0e729a1 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/registry.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/registry.py
@@ -26,9 +26,9 @@ key bindings at once.
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
-from prompt_toolkit.cache import SimpleCache
-from prompt_toolkit.filters import CLIFilter, to_cli_filter, Never
-from prompt_toolkit.keys import Key, Keys
+from prompt_toolkit.cache import SimpleCache
+from prompt_toolkit.filters import CLIFilter, to_cli_filter, Never
+from prompt_toolkit.keys import Key, Keys
from six import text_type, with_metaclass
@@ -44,18 +44,18 @@ class _Binding(object):
"""
(Immutable binding class.)
"""
- def __init__(self, keys, handler, filter=None, eager=None, save_before=None):
+ def __init__(self, keys, handler, filter=None, eager=None, save_before=None):
assert isinstance(keys, tuple)
assert callable(handler)
assert isinstance(filter, CLIFilter)
assert isinstance(eager, CLIFilter)
- assert callable(save_before)
+ assert callable(save_before)
self.keys = keys
self.handler = handler
self.filter = filter
self.eager = eager
- self.save_before = save_before
+ self.save_before = save_before
def call(self, event):
return self.handler(event)
@@ -89,14 +89,14 @@ class Registry(BaseRegistry):
"""
def __init__(self):
self.key_bindings = []
- self._get_bindings_for_keys_cache = SimpleCache(maxsize=10000)
- self._get_bindings_starting_with_keys_cache = SimpleCache(maxsize=1000)
+ self._get_bindings_for_keys_cache = SimpleCache(maxsize=10000)
+ self._get_bindings_starting_with_keys_cache = SimpleCache(maxsize=1000)
self._version = 0 # For cache invalidation.
- def _clear_cache(self):
+ def _clear_cache(self):
self._version += 1
- self._get_bindings_for_keys_cache.clear()
- self._get_bindings_starting_with_keys_cache.clear()
+ self._get_bindings_for_keys_cache.clear()
+ self._get_bindings_starting_with_keys_cache.clear()
def add_binding(self, *keys, **kwargs):
"""
@@ -109,35 +109,35 @@ class Registry(BaseRegistry):
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
- :param save_before: Callable that takes an `Event` and returns True if
- we should save the current buffer, before handling the event.
- (That's the default.)
+ :param save_before: Callable that takes an `Event` and returns True if
+ we should save the current buffer, before handling the event.
+ (That's the default.)
"""
filter = to_cli_filter(kwargs.pop('filter', True))
eager = to_cli_filter(kwargs.pop('eager', False))
- save_before = kwargs.pop('save_before', lambda e: True)
- to_cli_filter(kwargs.pop('invalidate_ui', True)) # Deprecated! (ignored.)
+ save_before = kwargs.pop('save_before', lambda e: True)
+ to_cli_filter(kwargs.pop('invalidate_ui', True)) # Deprecated! (ignored.)
assert not kwargs
assert keys
assert all(isinstance(k, (Key, text_type)) for k in keys), \
'Key bindings should consist of Key and string (unicode) instances.'
- assert callable(save_before)
+ assert callable(save_before)
- if isinstance(filter, Never):
+ if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that case
# don't bother putting it in the registry. It will slow down every key
- # press otherwise.
- def decorator(func):
- return func
- else:
- def decorator(func):
- self.key_bindings.append(
- _Binding(keys, func, filter=filter, eager=eager,
- save_before=save_before))
- self._clear_cache()
-
- return func
+ # press otherwise.
+ def decorator(func):
+ return func
+ else:
+ def decorator(func):
+ self.key_bindings.append(
+ _Binding(keys, func, filter=filter, eager=eager,
+ save_before=save_before))
+ self._clear_cache()
+
+ return func
return decorator
def remove_binding(self, function):
@@ -153,7 +153,7 @@ class Registry(BaseRegistry):
for b in self.key_bindings:
if b.handler == function:
self.key_bindings.remove(b)
- self._clear_cache()
+ self._clear_cache()
return
# No key binding found for this function. Raise ValueError.
@@ -167,31 +167,31 @@ class Registry(BaseRegistry):
:param keys: tuple of keys.
"""
- def get():
- result = []
- for b in self.key_bindings:
- if len(keys) == len(b.keys):
- match = True
- any_count = 0
-
- for i, j in zip(b.keys, keys):
- if i != j and i != Keys.Any:
- match = False
- break
-
- if i == Keys.Any:
- any_count += 1
-
- if match:
- result.append((any_count, b))
-
- # Place bindings that have more 'Any' occurences in them at the end.
- result = sorted(result, key=lambda item: -item[0])
-
- return [item[1] for item in result]
-
- return self._get_bindings_for_keys_cache.get(keys, get)
-
+ def get():
+ result = []
+ for b in self.key_bindings:
+ if len(keys) == len(b.keys):
+ match = True
+ any_count = 0
+
+ for i, j in zip(b.keys, keys):
+ if i != j and i != Keys.Any:
+ match = False
+ break
+
+ if i == Keys.Any:
+ any_count += 1
+
+ if match:
+ result.append((any_count, b))
+
+ # Place bindings that have more 'Any' occurences in them at the end.
+ result = sorted(result, key=lambda item: -item[0])
+
+ return [item[1] for item in result]
+
+ return self._get_bindings_for_keys_cache.get(keys, get)
+
def get_bindings_starting_with_keys(self, keys):
"""
Return a list of key bindings that handle a key sequence starting with
@@ -201,20 +201,20 @@ class Registry(BaseRegistry):
:param keys: tuple of keys.
"""
- def get():
- result = []
- for b in self.key_bindings:
- if len(keys) < len(b.keys):
- match = True
- for i, j in zip(b.keys, keys):
- if i != j and i != Keys.Any:
- match = False
- break
- if match:
- result.append(b)
- return result
-
- return self._get_bindings_starting_with_keys_cache.get(keys, get)
+ def get():
+ result = []
+ for b in self.key_bindings:
+ if len(keys) < len(b.keys):
+ match = True
+ for i, j in zip(b.keys, keys):
+ if i != j and i != Keys.Any:
+ match = False
+ break
+ if match:
+ result.append(b)
+ return result
+
+ return self._get_bindings_starting_with_keys_cache.get(keys, get)
class _AddRemoveMixin(BaseRegistry):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/vi_state.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/vi_state.py
index c99bef01b1..92ce3cbd29 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/vi_state.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/vi_state.py
@@ -9,7 +9,7 @@ __all__ = (
class InputMode(object):
INSERT = 'vi-insert'
- INSERT_MULTIPLE = 'vi-insert-multiple'
+ INSERT_MULTIPLE = 'vi-insert-multiple'
NAVIGATION = 'vi-navigation'
REPLACE = 'vi-replace'
@@ -29,33 +29,33 @@ class ViState(object):
#: search in Vi mode, by pressing the 'n' or 'N' in navigation mode.)
self.last_character_find = None
- # When an operator is given and we are waiting for text object,
- # -- e.g. in the case of 'dw', after the 'd' --, an operator callback
- # is set here.
- self.operator_func = None
- self.operator_arg = None
-
- #: Named registers. Maps register name (e.g. 'a') to
- #: :class:`ClipboardData` instances.
- self.named_registers = {}
-
+ # When an operator is given and we are waiting for text object,
+ # -- e.g. in the case of 'dw', after the 'd' --, an operator callback
+ # is set here.
+ self.operator_func = None
+ self.operator_arg = None
+
+ #: Named registers. Maps register name (e.g. 'a') to
+ #: :class:`ClipboardData` instances.
+ self.named_registers = {}
+
#: The Vi mode we're currently in to.
self.input_mode = InputMode.INSERT
- #: Waiting for digraph.
- self.waiting_for_digraph = False
- self.digraph_symbol1 = None # (None or a symbol.)
-
- #: When true, make ~ act as an operator.
- self.tilde_operator = False
-
- def reset(self, mode=InputMode.INSERT):
- """
- Reset state, go back to the given mode. INSERT by default.
- """
+ #: Waiting for digraph.
+ self.waiting_for_digraph = False
+ self.digraph_symbol1 = None # (None or a symbol.)
+
+ #: When true, make ~ act as an operator.
+ self.tilde_operator = False
+
+ def reset(self, mode=InputMode.INSERT):
+ """
+ Reset state, go back to the given mode. INSERT by default.
+ """
# Go back to insert mode.
- self.input_mode = mode
-
- self.waiting_for_digraph = False
- self.operator_func = None
- self.operator_arg = None
+ self.input_mode = mode
+
+ self.waiting_for_digraph = False
+ self.operator_func = None
+ self.operator_arg = None
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/keys.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/keys.py
index b264fbdb0d..d5df9bff41 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/keys.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/keys.py
@@ -61,35 +61,35 @@ class Keys(object):
Down = Key('<Down>')
Right = Key('<Right>')
Left = Key('<Left>')
-
- ShiftLeft = Key('<ShiftLeft>')
- ShiftUp = Key('<ShiftUp>')
- ShiftDown = Key('<ShiftDown>')
- ShiftRight = Key('<ShiftRight>')
-
+
+ ShiftLeft = Key('<ShiftLeft>')
+ ShiftUp = Key('<ShiftUp>')
+ ShiftDown = Key('<ShiftDown>')
+ ShiftRight = Key('<ShiftRight>')
+
Home = Key('<Home>')
End = Key('<End>')
Delete = Key('<Delete>')
ShiftDelete = Key('<ShiftDelete>')
- ControlDelete = Key('<C-Delete>')
+ ControlDelete = Key('<C-Delete>')
PageUp = Key('<PageUp>')
PageDown = Key('<PageDown>')
BackTab = Key('<BackTab>') # shift + tab
Insert = Key('<Insert>')
- Backspace = Key('<Backspace>')
+ Backspace = Key('<Backspace>')
- # Aliases.
+ # Aliases.
Tab = ControlI
- Enter = ControlJ
- # XXX: Actually Enter equals ControlM, not ControlJ,
- # However, in prompt_toolkit, we made the mistake of translating
- # \r into \n during the input, so everyone is now handling the
- # enter key by binding ControlJ.
-
- # From now on, it's better to bind `Keys.Enter` everywhere,
- # because that's future compatible, and will still work when we
- # stop replacing \r by \n.
-
+ Enter = ControlJ
+ # XXX: Actually Enter equals ControlM, not ControlJ,
+ # However, in prompt_toolkit, we made the mistake of translating
+ # \r into \n during the input, so everyone is now handling the
+ # enter key by binding ControlJ.
+
+ # From now on, it's better to bind `Keys.Enter` everywhere,
+ # because that's future compatible, and will still work when we
+ # stop replacing \r by \n.
+
F1 = Key('<F1>')
F2 = Key('<F2>')
F3 = Key('<F3>')
@@ -110,10 +110,10 @@ class Keys(object):
F18 = Key('<F18>')
F19 = Key('<F19>')
F20 = Key('<F20>')
- F21 = Key('<F21>')
- F22 = Key('<F22>')
- F23 = Key('<F23>')
- F24 = Key('<F24>')
+ F21 = Key('<F21>')
+ F22 = Key('<F22>')
+ F23 = Key('<F23>')
+ F24 = Key('<F24>')
# Matches any key.
Any = Key('<Any>')
@@ -123,7 +123,7 @@ class Keys(object):
Vt100MouseEvent = Key('<Vt100-Mouse-Event>')
WindowsMouseEvent = Key('<Windows-Mouse-Event>')
BracketedPaste = Key('<Bracketed-Paste>')
-
- # Key which is ignored. (The key binding for this key should not do
- # anything.)
- Ignore = Key('<Ignore>')
+
+ # Key which is ignored. (The key binding for this key should not do
+ # anything.)
+ Ignore = Key('<Ignore>')
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/__init__.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/__init__.py
index 25590d8a2e..0dec5ecfaf 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/__init__.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/__init__.py
@@ -8,7 +8,7 @@ There are two main groups of classes here. Containers and controls:
- A container can contain other containers or controls, it can have multiple
children and it decides about the dimensions.
- A control is responsible for rendering the actual content to a screen.
- A control can propose some dimensions, but it's the container who decides
+ A control can propose some dimensions, but it's the container who decides
about the dimensions -- or when the control consumes more space -- which part
of the control will be visible.
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py
index 2901461e88..0bdafe18e0 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py
@@ -6,19 +6,19 @@ from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from six import with_metaclass
-from six.moves import range
+from six.moves import range
-from .controls import UIControl, TokenListControl, UIContent
+from .controls import UIControl, TokenListControl, UIContent
from .dimension import LayoutDimension, sum_layout_dimensions, max_layout_dimensions
from .margins import Margin
-from .screen import Point, WritePosition, _CHAR_CACHE
-from .utils import token_list_to_text, explode_tokens
-from prompt_toolkit.cache import SimpleCache
-from prompt_toolkit.filters import to_cli_filter, ViInsertMode, EmacsInsertMode
-from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
-from prompt_toolkit.reactive import Integer
-from prompt_toolkit.token import Token
-from prompt_toolkit.utils import take_using_weights, get_cwidth
+from .screen import Point, WritePosition, _CHAR_CACHE
+from .utils import token_list_to_text, explode_tokens
+from prompt_toolkit.cache import SimpleCache
+from prompt_toolkit.filters import to_cli_filter, ViInsertMode, EmacsInsertMode
+from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
+from prompt_toolkit.reactive import Integer
+from prompt_toolkit.token import Token
+from prompt_toolkit.utils import take_using_weights, get_cwidth
__all__ = (
'Container',
@@ -29,8 +29,8 @@ __all__ = (
'Window',
'WindowRenderInfo',
'ConditionalContainer',
- 'ScrollOffsets',
- 'ColorColumn',
+ 'ScrollOffsets',
+ 'ColorColumn',
)
Transparent = Token.Transparent
@@ -57,7 +57,7 @@ class Container(with_metaclass(ABCMeta, object)):
"""
@abstractmethod
- def preferred_height(self, cli, width, max_available_height):
+ def preferred_height(self, cli, width, max_available_height):
"""
Return a :class:`~prompt_toolkit.layout.dimension.LayoutDimension` that
represents the desired height for this container.
@@ -124,8 +124,8 @@ class HSplit(Container):
else:
return LayoutDimension(0)
- def preferred_height(self, cli, width, max_available_height):
- dimensions = [c.preferred_height(cli, width, max_available_height) for c in self.children]
+ def preferred_height(self, cli, width, max_available_height):
+ dimensions = [c.preferred_height(cli, width, max_available_height) for c in self.children]
return sum_layout_dimensions(dimensions)
def reset(self):
@@ -172,7 +172,7 @@ class HSplit(Container):
if given_dimensions and given_dimensions[index] is not None:
return given_dimensions[index]
else:
- return c.preferred_height(cli, write_position.width, write_position.extended_height)
+ return c.preferred_height(cli, write_position.width, write_position.extended_height)
dimensions = [get_dimension_for_child(c, index) for index, c in enumerate(self.children)]
@@ -250,12 +250,12 @@ class VSplit(Container):
dimensions = [c.preferred_width(cli, max_available_width) for c in self.children]
return sum_layout_dimensions(dimensions)
- def preferred_height(self, cli, width, max_available_height):
+ def preferred_height(self, cli, width, max_available_height):
sizes = self._divide_widths(cli, width)
if sizes is None:
return LayoutDimension()
else:
- dimensions = [c.preferred_height(cli, s, max_available_height)
+ dimensions = [c.preferred_height(cli, s, max_available_height)
for s, c in zip(sizes, self.children)]
return max_layout_dimensions(dimensions)
@@ -336,7 +336,7 @@ class VSplit(Container):
return
# Calculate heights, take the largest possible, but not larger than write_position.extended_height.
- heights = [child.preferred_height(cli, width, write_position.extended_height).preferred
+ heights = [child.preferred_height(cli, width, write_position.extended_height).preferred
for width, child in zip(sizes, self.children)]
height = max(write_position.height, min(write_position.extended_height, max(heights)))
@@ -386,13 +386,13 @@ class FloatContainer(Container):
def preferred_width(self, cli, write_position):
return self.content.preferred_width(cli, write_position)
- def preferred_height(self, cli, width, max_available_height):
+ def preferred_height(self, cli, width, max_available_height):
"""
Return the preferred height of the float container.
(We don't care about the height of the floats, they should always fit
into the dimensions provided by the container.)
"""
- return self.content.preferred_height(cli, width, max_available_height)
+ return self.content.preferred_height(cli, width, max_available_height)
def write_to_screen(self, cli, screen, mouse_handlers, write_position):
self.content.write_to_screen(cli, screen, mouse_handlers, write_position)
@@ -467,8 +467,8 @@ class FloatContainer(Container):
height = fl_height
if height is None:
- height = fl.content.preferred_height(
- cli, width, write_position.extended_height).preferred
+ height = fl.content.preferred_height(
+ cli, width, write_position.extended_height).preferred
# Reduce height if not enough space. (We can use the
# extended_height when the content requires it.)
@@ -488,8 +488,8 @@ class FloatContainer(Container):
height = fl_height
# Otherwise, take preferred height from content.
else:
- height = fl.content.preferred_height(
- cli, width, write_position.extended_height).preferred
+ height = fl.content.preferred_height(
+ cli, width, write_position.extended_height).preferred
if fl.top is not None:
ypos = fl.top
@@ -508,28 +508,28 @@ class FloatContainer(Container):
ypos=ypos + write_position.ypos,
width=width, height=height)
- if not fl.hide_when_covering_content or self._area_is_empty(screen, wp):
- fl.content.write_to_screen(cli, screen, mouse_handlers, wp)
-
- def _area_is_empty(self, screen, write_position):
- """
- Return True when the area below the write position is still empty.
- (For floats that should not hide content underneath.)
- """
- wp = write_position
- Transparent = Token.Transparent
-
- for y in range(wp.ypos, wp.ypos + wp.height):
- if y in screen.data_buffer:
- row = screen.data_buffer[y]
-
- for x in range(wp.xpos, wp.xpos + wp.width):
- c = row[x]
- if c.char != ' ' or c.token != Transparent:
- return False
-
- return True
-
+ if not fl.hide_when_covering_content or self._area_is_empty(screen, wp):
+ fl.content.write_to_screen(cli, screen, mouse_handlers, wp)
+
+ def _area_is_empty(self, screen, write_position):
+ """
+ Return True when the area below the write position is still empty.
+ (For floats that should not hide content underneath.)
+ """
+ wp = write_position
+ Transparent = Token.Transparent
+
+ for y in range(wp.ypos, wp.ypos + wp.height):
+ if y in screen.data_buffer:
+ row = screen.data_buffer[y]
+
+ for x in range(wp.xpos, wp.xpos + wp.width):
+ c = row[x]
+ if c.char != ' ' or c.token != Transparent:
+ return False
+
+ return True
+
def walk(self, cli):
""" Walk through children. """
yield self
@@ -547,12 +547,12 @@ class Float(object):
Float for use in a :class:`.FloatContainer`.
:param content: :class:`.Container` instance.
- :param hide_when_covering_content: Hide the float when it covers content underneath.
+ :param hide_when_covering_content: Hide the float when it covers content underneath.
"""
def __init__(self, top=None, right=None, bottom=None, left=None,
width=None, height=None, get_width=None, get_height=None,
- xcursor=False, ycursor=False, content=None,
- hide_when_covering_content=False):
+ xcursor=False, ycursor=False, content=None,
+ hide_when_covering_content=False):
assert isinstance(content, Container)
assert width is None or get_width is None
assert height is None or get_height is None
@@ -572,7 +572,7 @@ class Float(object):
self.ycursor = ycursor
self.content = content
- self.hide_when_covering_content = hide_when_covering_content
+ self.hide_when_covering_content = hide_when_covering_content
def get_width(self, cli):
if self._width:
@@ -600,135 +600,135 @@ class WindowRenderInfo(object):
(Could be used for implementation of the Vi 'H' and 'L' key bindings as
well as implementing mouse support.)
- :param ui_content: The original :class:`.UIContent` instance that contains
- the whole input, without clipping. (ui_content)
+ :param ui_content: The original :class:`.UIContent` instance that contains
+ the whole input, without clipping. (ui_content)
:param horizontal_scroll: The horizontal scroll of the :class:`.Window` instance.
:param vertical_scroll: The vertical scroll of the :class:`.Window` instance.
- :param window_width: The width of the window that displays the content,
- without the margins.
- :param window_height: The height of the window that displays the content.
- :param configured_scroll_offsets: The scroll offsets as configured for the
- :class:`Window` instance.
- :param visible_line_to_row_col: Mapping that maps the row numbers on the
- displayed screen (starting from zero for the first visible line) to
- (row, col) tuples pointing to the row and column of the :class:`.UIContent`.
- :param rowcol_to_yx: Mapping that maps (row, column) tuples representing
- coordinates of the :class:`UIContent` to (y, x) absolute coordinates at
- the rendered screen.
+ :param window_width: The width of the window that displays the content,
+ without the margins.
+ :param window_height: The height of the window that displays the content.
+ :param configured_scroll_offsets: The scroll offsets as configured for the
+ :class:`Window` instance.
+ :param visible_line_to_row_col: Mapping that maps the row numbers on the
+ displayed screen (starting from zero for the first visible line) to
+ (row, col) tuples pointing to the row and column of the :class:`.UIContent`.
+ :param rowcol_to_yx: Mapping that maps (row, column) tuples representing
+ coordinates of the :class:`UIContent` to (y, x) absolute coordinates at
+ the rendered screen.
"""
- def __init__(self, ui_content, horizontal_scroll, vertical_scroll,
- window_width, window_height,
- configured_scroll_offsets,
- visible_line_to_row_col, rowcol_to_yx,
- x_offset, y_offset, wrap_lines):
- assert isinstance(ui_content, UIContent)
- assert isinstance(horizontal_scroll, int)
- assert isinstance(vertical_scroll, int)
- assert isinstance(window_width, int)
- assert isinstance(window_height, int)
- assert isinstance(configured_scroll_offsets, ScrollOffsets)
- assert isinstance(visible_line_to_row_col, dict)
- assert isinstance(rowcol_to_yx, dict)
- assert isinstance(x_offset, int)
- assert isinstance(y_offset, int)
- assert isinstance(wrap_lines, bool)
-
- self.ui_content = ui_content
+ def __init__(self, ui_content, horizontal_scroll, vertical_scroll,
+ window_width, window_height,
+ configured_scroll_offsets,
+ visible_line_to_row_col, rowcol_to_yx,
+ x_offset, y_offset, wrap_lines):
+ assert isinstance(ui_content, UIContent)
+ assert isinstance(horizontal_scroll, int)
+ assert isinstance(vertical_scroll, int)
+ assert isinstance(window_width, int)
+ assert isinstance(window_height, int)
+ assert isinstance(configured_scroll_offsets, ScrollOffsets)
+ assert isinstance(visible_line_to_row_col, dict)
+ assert isinstance(rowcol_to_yx, dict)
+ assert isinstance(x_offset, int)
+ assert isinstance(y_offset, int)
+ assert isinstance(wrap_lines, bool)
+
+ self.ui_content = ui_content
self.vertical_scroll = vertical_scroll
- self.window_width = window_width # Width without margins.
+ self.window_width = window_width # Width without margins.
self.window_height = window_height
-
+
self.configured_scroll_offsets = configured_scroll_offsets
- self.visible_line_to_row_col = visible_line_to_row_col
- self.wrap_lines = wrap_lines
-
- self._rowcol_to_yx = rowcol_to_yx # row/col from input to absolute y/x
- # screen coordinates.
- self._x_offset = x_offset
- self._y_offset = y_offset
-
+ self.visible_line_to_row_col = visible_line_to_row_col
+ self.wrap_lines = wrap_lines
+
+ self._rowcol_to_yx = rowcol_to_yx # row/col from input to absolute y/x
+ # screen coordinates.
+ self._x_offset = x_offset
+ self._y_offset = y_offset
+
@property
- def visible_line_to_input_line(self):
- return dict(
- (visible_line, rowcol[0])
- for visible_line, rowcol in self.visible_line_to_row_col.items())
-
- @property
- def cursor_position(self):
+ def visible_line_to_input_line(self):
+ return dict(
+ (visible_line, rowcol[0])
+ for visible_line, rowcol in self.visible_line_to_row_col.items())
+
+ @property
+ def cursor_position(self):
"""
- Return the cursor position coordinates, relative to the left/top corner
- of the rendered screen.
+ Return the cursor position coordinates, relative to the left/top corner
+ of the rendered screen.
"""
- cpos = self.ui_content.cursor_position
- y, x = self._rowcol_to_yx[cpos.y, cpos.x]
- return Point(x=x - self._x_offset, y=y - self._y_offset)
+ cpos = self.ui_content.cursor_position
+ y, x = self._rowcol_to_yx[cpos.y, cpos.x]
+ return Point(x=x - self._x_offset, y=y - self._y_offset)
@property
- def applied_scroll_offsets(self):
- """
- Return a :class:`.ScrollOffsets` instance that indicates the actual
- offset. This can be less than or equal to what's configured. E.g, when
- the cursor is completely at the top, the top offset will be zero rather
- than what's configured.
- """
- if self.displayed_lines[0] == 0:
- top = 0
- else:
- # Get row where the cursor is displayed.
- y = self.input_line_to_visible_line[self.ui_content.cursor_position.y]
- top = min(y, self.configured_scroll_offsets.top)
-
- return ScrollOffsets(
- top=top,
- bottom=min(self.ui_content.line_count - self.displayed_lines[-1] - 1,
- self.configured_scroll_offsets.bottom),
-
- # For left/right, it probably doesn't make sense to return something.
- # (We would have to calculate the widths of all the lines and keep
- # double width characters in mind.)
- left=0, right=0)
-
+ def applied_scroll_offsets(self):
+ """
+ Return a :class:`.ScrollOffsets` instance that indicates the actual
+ offset. This can be less than or equal to what's configured. E.g, when
+ the cursor is completely at the top, the top offset will be zero rather
+ than what's configured.
+ """
+ if self.displayed_lines[0] == 0:
+ top = 0
+ else:
+ # Get row where the cursor is displayed.
+ y = self.input_line_to_visible_line[self.ui_content.cursor_position.y]
+ top = min(y, self.configured_scroll_offsets.top)
+
+ return ScrollOffsets(
+ top=top,
+ bottom=min(self.ui_content.line_count - self.displayed_lines[-1] - 1,
+ self.configured_scroll_offsets.bottom),
+
+ # For left/right, it probably doesn't make sense to return something.
+ # (We would have to calculate the widths of all the lines and keep
+ # double width characters in mind.)
+ left=0, right=0)
+
@property
- def displayed_lines(self):
- """
- List of all the visible rows. (Line numbers of the input buffer.)
- The last line may not be entirely visible.
- """
- return sorted(row for row, col in self.visible_line_to_row_col.values())
-
- @property
- def input_line_to_visible_line(self):
- """
- Return the dictionary mapping the line numbers of the input buffer to
- the lines of the screen. When a line spans several rows at the screen,
- the first row appears in the dictionary.
- """
- result = {}
- for k, v in self.visible_line_to_input_line.items():
- if v in result:
- result[v] = min(result[v], k)
- else:
- result[v] = k
- return result
-
+ def displayed_lines(self):
+ """
+ List of all the visible rows. (Line numbers of the input buffer.)
+ The last line may not be entirely visible.
+ """
+ return sorted(row for row, col in self.visible_line_to_row_col.values())
+
+ @property
+ def input_line_to_visible_line(self):
+ """
+ Return the dictionary mapping the line numbers of the input buffer to
+ the lines of the screen. When a line spans several rows at the screen,
+ the first row appears in the dictionary.
+ """
+ result = {}
+ for k, v in self.visible_line_to_input_line.items():
+ if v in result:
+ result[v] = min(result[v], k)
+ else:
+ result[v] = k
+ return result
+
def first_visible_line(self, after_scroll_offset=False):
"""
Return the line number (0 based) of the input document that corresponds
with the first visible line.
"""
if after_scroll_offset:
- return self.displayed_lines[self.applied_scroll_offsets.top]
- else:
- return self.displayed_lines[0]
+ return self.displayed_lines[self.applied_scroll_offsets.top]
+ else:
+ return self.displayed_lines[0]
def last_visible_line(self, before_scroll_offset=False):
"""
Like `first_visible_line`, but for the last visible line.
"""
if before_scroll_offset:
- return self.displayed_lines[-1 - self.applied_scroll_offsets.bottom]
- else:
- return self.displayed_lines[-1]
+ return self.displayed_lines[-1 - self.applied_scroll_offsets.bottom]
+ else:
+ return self.displayed_lines[-1]
def center_visible_line(self, before_scroll_offset=False,
after_scroll_offset=False):
@@ -737,7 +737,7 @@ class WindowRenderInfo(object):
"""
return (self.first_visible_line(after_scroll_offset) +
(self.last_visible_line(before_scroll_offset) -
- self.first_visible_line(after_scroll_offset)) // 2
+ self.first_visible_line(after_scroll_offset)) // 2
)
@property
@@ -745,14 +745,14 @@ class WindowRenderInfo(object):
"""
The full height of the user control.
"""
- return self.ui_content.line_count
+ return self.ui_content.line_count
@property
def full_height_visible(self):
"""
True when the full height is visible (There is no vertical scroll.)
"""
- return self.vertical_scroll == 0 and self.last_visible_line() == self.content_height
+ return self.vertical_scroll == 0 and self.last_visible_line() == self.content_height
@property
def top_visible(self):
@@ -766,7 +766,7 @@ class WindowRenderInfo(object):
"""
True when the bottom of the buffer is visible.
"""
- return self.last_visible_line() == self.content_height - 1
+ return self.last_visible_line() == self.content_height - 1
@property
def vertical_scroll_percentage(self):
@@ -774,22 +774,22 @@ class WindowRenderInfo(object):
Vertical scroll as a percentage. (0 means: the top is visible,
100 means: the bottom is visible.)
"""
- if self.bottom_visible:
- return 100
- else:
- return (100 * self.vertical_scroll // self.content_height)
-
- def get_height_for_line(self, lineno):
- """
- Return the height of the given line.
- (The height that it would take, if this line became visible.)
- """
- if self.wrap_lines:
- return self.ui_content.get_height_for_line(lineno, self.window_width)
- else:
- return 1
-
-
+ if self.bottom_visible:
+ return 100
+ else:
+ return (100 * self.vertical_scroll // self.content_height)
+
+ def get_height_for_line(self, lineno):
+ """
+ Return the height of the given line.
+ (The height that it would take, if this line became visible.)
+ """
+ if self.wrap_lines:
+ return self.ui_content.get_height_for_line(lineno, self.window_width)
+ else:
+ return 1
+
+
class ScrollOffsets(object):
"""
Scroll offsets for the :class:`.Window` class.
@@ -797,46 +797,46 @@ class ScrollOffsets(object):
Note that left/right offsets only make sense if line wrapping is disabled.
"""
def __init__(self, top=0, bottom=0, left=0, right=0):
- assert isinstance(top, Integer)
- assert isinstance(bottom, Integer)
- assert isinstance(left, Integer)
- assert isinstance(right, Integer)
-
- self._top = top
- self._bottom = bottom
- self._left = left
- self._right = right
-
- @property
- def top(self):
- return int(self._top)
-
- @property
- def bottom(self):
- return int(self._bottom)
-
- @property
- def left(self):
- return int(self._left)
-
- @property
- def right(self):
- return int(self._right)
-
+ assert isinstance(top, Integer)
+ assert isinstance(bottom, Integer)
+ assert isinstance(left, Integer)
+ assert isinstance(right, Integer)
+
+ self._top = top
+ self._bottom = bottom
+ self._left = left
+ self._right = right
+
+ @property
+ def top(self):
+ return int(self._top)
+
+ @property
+ def bottom(self):
+ return int(self._bottom)
+
+ @property
+ def left(self):
+ return int(self._left)
+
+ @property
+ def right(self):
+ return int(self._right)
+
def __repr__(self):
return 'ScrollOffsets(top=%r, bottom=%r, left=%r, right=%r)' % (
self.top, self.bottom, self.left, self.right)
-class ColorColumn(object):
- def __init__(self, position, token=Token.ColorColumn):
- self.position = position
- self.token = token
-
-
-_in_insert_mode = ViInsertMode() | EmacsInsertMode()
-
-
+class ColorColumn(object):
+ def __init__(self, position, token=Token.ColorColumn):
+ self.position = position
+ self.token = token
+
+
+_in_insert_mode = ViInsertMode() | EmacsInsertMode()
+
+
class Window(Container):
"""
Container that holds a control.
@@ -865,8 +865,8 @@ class Window(Container):
anymore, while there is still empty space available at the bottom of
the window. In the Vi editor for instance, this is possible. You will
see tildes while the top part of the body is hidden.
- :param wrap_lines: A `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
- instance. When True, don't scroll horizontally, but wrap lines instead.
+ :param wrap_lines: A `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
+ instance. When True, don't scroll horizontally, but wrap lines instead.
:param get_vertical_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
(When this is `None`, the scroll is only determined by the last and
@@ -877,25 +877,25 @@ class Window(Container):
:class:`~prompt_toolkit.filters.CLIFilter` instance. When True, never
display the cursor, even when the user control specifies a cursor
position.
- :param cursorline: A `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
- instance. When True, display a cursorline.
- :param cursorcolumn: A `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
- instance. When True, display a cursorcolumn.
- :param get_colorcolumns: A callable that takes a `CommandLineInterface` and
- returns a a list of :class:`.ColorColumn` instances that describe the
- columns to be highlighted.
- :param cursorline_token: The token to be used for highlighting the current line,
- if `cursorline` is True.
- :param cursorcolumn_token: The token to be used for highlighting the current line,
- if `cursorcolumn` is True.
+ :param cursorline: A `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
+ instance. When True, display a cursorline.
+ :param cursorcolumn: A `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
+ instance. When True, display a cursorcolumn.
+ :param get_colorcolumns: A callable that takes a `CommandLineInterface` and
+ returns a a list of :class:`.ColorColumn` instances that describe the
+ columns to be highlighted.
+ :param cursorline_token: The token to be used for highlighting the current line,
+ if `cursorline` is True.
+ :param cursorcolumn_token: The token to be used for highlighting the current line,
+ if `cursorcolumn` is True.
"""
def __init__(self, content, width=None, height=None, get_width=None,
get_height=None, dont_extend_width=False, dont_extend_height=False,
left_margins=None, right_margins=None, scroll_offsets=None,
- allow_scroll_beyond_bottom=False, wrap_lines=False,
- get_vertical_scroll=None, get_horizontal_scroll=None, always_hide_cursor=False,
- cursorline=False, cursorcolumn=False, get_colorcolumns=None,
- cursorline_token=Token.CursorLine, cursorcolumn_token=Token.CursorColumn):
+ allow_scroll_beyond_bottom=False, wrap_lines=False,
+ get_vertical_scroll=None, get_horizontal_scroll=None, always_hide_cursor=False,
+ cursorline=False, cursorcolumn=False, get_colorcolumns=None,
+ cursorline_token=Token.CursorLine, cursorcolumn_token=Token.CursorColumn):
assert isinstance(content, UIControl)
assert width is None or isinstance(width, LayoutDimension)
assert height is None or isinstance(height, LayoutDimension)
@@ -908,13 +908,13 @@ class Window(Container):
assert right_margins is None or all(isinstance(m, Margin) for m in right_margins)
assert get_vertical_scroll is None or callable(get_vertical_scroll)
assert get_horizontal_scroll is None or callable(get_horizontal_scroll)
- assert get_colorcolumns is None or callable(get_colorcolumns)
+ assert get_colorcolumns is None or callable(get_colorcolumns)
self.allow_scroll_beyond_bottom = to_cli_filter(allow_scroll_beyond_bottom)
self.always_hide_cursor = to_cli_filter(always_hide_cursor)
- self.wrap_lines = to_cli_filter(wrap_lines)
- self.cursorline = to_cli_filter(cursorline)
- self.cursorcolumn = to_cli_filter(cursorcolumn)
+ self.wrap_lines = to_cli_filter(wrap_lines)
+ self.cursorline = to_cli_filter(cursorline)
+ self.cursorcolumn = to_cli_filter(cursorcolumn)
self.content = content
self.dont_extend_width = dont_extend_width
@@ -926,13 +926,13 @@ class Window(Container):
self.get_horizontal_scroll = get_horizontal_scroll
self._width = get_width or (lambda cli: width)
self._height = get_height or (lambda cli: height)
- self.get_colorcolumns = get_colorcolumns or (lambda cli: [])
- self.cursorline_token = cursorline_token
- self.cursorcolumn_token = cursorcolumn_token
+ self.get_colorcolumns = get_colorcolumns or (lambda cli: [])
+ self.cursorline_token = cursorline_token
+ self.cursorcolumn_token = cursorcolumn_token
# Cache for the screens generated by the margin.
- self._ui_content_cache = SimpleCache(maxsize=8)
- self._margin_width_cache = SimpleCache(maxsize=1)
+ self._ui_content_cache = SimpleCache(maxsize=8)
+ self._margin_width_cache = SimpleCache(maxsize=1)
self.reset()
@@ -946,41 +946,41 @@ class Window(Container):
self.vertical_scroll = 0
self.horizontal_scroll = 0
- # Vertical scroll 2: this is the vertical offset that a line is
- # scrolled if a single line (the one that contains the cursor) consumes
- # all of the vertical space.
- self.vertical_scroll_2 = 0
-
+ # Vertical scroll 2: this is the vertical offset that a line is
+ # scrolled if a single line (the one that contains the cursor) consumes
+ # all of the vertical space.
+ self.vertical_scroll_2 = 0
+
#: Keep render information (mappings between buffer input and render
#: output.)
self.render_info = None
- def _get_margin_width(self, cli, margin):
- """
- Return the width for this margin.
- (Calculate only once per render time.)
- """
- # Margin.get_width, needs to have a UIContent instance.
- def get_ui_content():
- return self._get_ui_content(cli, width=0, height=0)
-
- def get_width():
- return margin.get_width(cli, get_ui_content)
-
- key = (margin, cli.render_counter)
- return self._margin_width_cache.get(key, get_width)
-
+ def _get_margin_width(self, cli, margin):
+ """
+ Return the width for this margin.
+ (Calculate only once per render time.)
+ """
+ # Margin.get_width, needs to have a UIContent instance.
+ def get_ui_content():
+ return self._get_ui_content(cli, width=0, height=0)
+
+ def get_width():
+ return margin.get_width(cli, get_ui_content)
+
+ key = (margin, cli.render_counter)
+ return self._margin_width_cache.get(key, get_width)
+
def preferred_width(self, cli, max_available_width):
- # Calculate the width of the margin.
- total_margin_width = sum(self._get_margin_width(cli, m) for m in
+ # Calculate the width of the margin.
+ total_margin_width = sum(self._get_margin_width(cli, m) for m in
self.left_margins + self.right_margins)
- # Window of the content. (Can be `None`.)
+ # Window of the content. (Can be `None`.)
preferred_width = self.content.preferred_width(
cli, max_available_width - total_margin_width)
if preferred_width is not None:
- # Include width of the margins.
+ # Include width of the margins.
preferred_width += total_margin_width
# Merge.
@@ -989,15 +989,15 @@ class Window(Container):
preferred=preferred_width,
dont_extend=self.dont_extend_width)
- def preferred_height(self, cli, width, max_available_height):
- total_margin_width = sum(self._get_margin_width(cli, m) for m in
- self.left_margins + self.right_margins)
- wrap_lines = self.wrap_lines(cli)
-
+ def preferred_height(self, cli, width, max_available_height):
+ total_margin_width = sum(self._get_margin_width(cli, m) for m in
+ self.left_margins + self.right_margins)
+ wrap_lines = self.wrap_lines(cli)
+
return self._merge_dimensions(
dimension=self._height(cli),
- preferred=self.content.preferred_height(
- cli, width - total_margin_width, max_available_height, wrap_lines),
+ preferred=self.content.preferred_height(
+ cli, width - total_margin_width, max_available_height, wrap_lines),
dont_extend=self.dont_extend_height)
@staticmethod
@@ -1030,115 +1030,115 @@ class Window(Container):
else:
max_ = dimension.max
- return LayoutDimension(
- min=dimension.min, max=max_,
- preferred=preferred, weight=dimension.weight)
-
- def _get_ui_content(self, cli, width, height):
- """
- Create a `UIContent` instance.
- """
- def get_content():
- return self.content.create_content(cli, width=width, height=height)
-
- key = (cli.render_counter, width, height)
- return self._ui_content_cache.get(key, get_content)
-
- def _get_digraph_char(self, cli):
- " Return `False`, or the Digraph symbol to be used. "
+ return LayoutDimension(
+ min=dimension.min, max=max_,
+ preferred=preferred, weight=dimension.weight)
+
+ def _get_ui_content(self, cli, width, height):
+ """
+ Create a `UIContent` instance.
+ """
+ def get_content():
+ return self.content.create_content(cli, width=width, height=height)
+
+ key = (cli.render_counter, width, height)
+ return self._ui_content_cache.get(key, get_content)
+
+ def _get_digraph_char(self, cli):
+ " Return `False`, or the Digraph symbol to be used. "
if cli.quoted_insert:
return '^'
- if cli.vi_state.waiting_for_digraph:
- if cli.vi_state.digraph_symbol1:
- return cli.vi_state.digraph_symbol1
- return '?'
- return False
-
+ if cli.vi_state.waiting_for_digraph:
+ if cli.vi_state.digraph_symbol1:
+ return cli.vi_state.digraph_symbol1
+ return '?'
+ return False
+
def write_to_screen(self, cli, screen, mouse_handlers, write_position):
"""
Write window to screen. This renders the user control, the margins and
copies everything over to the absolute position at the given screen.
"""
# Calculate margin sizes.
- left_margin_widths = [self._get_margin_width(cli, m) for m in self.left_margins]
- right_margin_widths = [self._get_margin_width(cli, m) for m in self.right_margins]
+ left_margin_widths = [self._get_margin_width(cli, m) for m in self.left_margins]
+ right_margin_widths = [self._get_margin_width(cli, m) for m in self.right_margins]
total_margin_width = sum(left_margin_widths + right_margin_widths)
# Render UserControl.
- ui_content = self.content.create_content(
+ ui_content = self.content.create_content(
cli, write_position.width - total_margin_width, write_position.height)
- assert isinstance(ui_content, UIContent)
+ assert isinstance(ui_content, UIContent)
# Scroll content.
- wrap_lines = self.wrap_lines(cli)
- scroll_func = self._scroll_when_linewrapping if wrap_lines else self._scroll_without_linewrapping
-
- scroll_func(
- ui_content, write_position.width - total_margin_width, write_position.height, cli)
-
- # Write body
- visible_line_to_row_col, rowcol_to_yx = self._copy_body(
- cli, ui_content, screen, write_position,
- sum(left_margin_widths), write_position.width - total_margin_width,
- self.vertical_scroll, self.horizontal_scroll,
- has_focus=self.content.has_focus(cli),
- wrap_lines=wrap_lines, highlight_lines=True,
- vertical_scroll_2=self.vertical_scroll_2,
- always_hide_cursor=self.always_hide_cursor(cli))
-
+ wrap_lines = self.wrap_lines(cli)
+ scroll_func = self._scroll_when_linewrapping if wrap_lines else self._scroll_without_linewrapping
+
+ scroll_func(
+ ui_content, write_position.width - total_margin_width, write_position.height, cli)
+
+ # Write body
+ visible_line_to_row_col, rowcol_to_yx = self._copy_body(
+ cli, ui_content, screen, write_position,
+ sum(left_margin_widths), write_position.width - total_margin_width,
+ self.vertical_scroll, self.horizontal_scroll,
+ has_focus=self.content.has_focus(cli),
+ wrap_lines=wrap_lines, highlight_lines=True,
+ vertical_scroll_2=self.vertical_scroll_2,
+ always_hide_cursor=self.always_hide_cursor(cli))
+
# Remember render info. (Set before generating the margins. They need this.)
- x_offset=write_position.xpos + sum(left_margin_widths)
- y_offset=write_position.ypos
-
+ x_offset=write_position.xpos + sum(left_margin_widths)
+ y_offset=write_position.ypos
+
self.render_info = WindowRenderInfo(
- ui_content=ui_content,
+ ui_content=ui_content,
horizontal_scroll=self.horizontal_scroll,
vertical_scroll=self.vertical_scroll,
- window_width=write_position.width - total_margin_width,
+ window_width=write_position.width - total_margin_width,
window_height=write_position.height,
configured_scroll_offsets=self.scroll_offsets,
- visible_line_to_row_col=visible_line_to_row_col,
- rowcol_to_yx=rowcol_to_yx,
- x_offset=x_offset,
- y_offset=y_offset,
- wrap_lines=wrap_lines)
+ visible_line_to_row_col=visible_line_to_row_col,
+ rowcol_to_yx=rowcol_to_yx,
+ x_offset=x_offset,
+ y_offset=y_offset,
+ wrap_lines=wrap_lines)
# Set mouse handlers.
def mouse_handler(cli, mouse_event):
""" Wrapper around the mouse_handler of the `UIControl` that turns
- screen coordinates into line coordinates. """
- # Find row/col position first.
- yx_to_rowcol = dict((v, k) for k, v in rowcol_to_yx.items())
- y = mouse_event.position.y
- x = mouse_event.position.x
-
- # If clicked below the content area, look for a position in the
- # last line instead.
- max_y = write_position.ypos + len(visible_line_to_row_col) - 1
- y = min(max_y, y)
-
- while x >= 0:
- try:
- row, col = yx_to_rowcol[y, x]
- except KeyError:
- # Try again. (When clicking on the right side of double
- # width characters, or on the right side of the input.)
- x -= 1
- else:
- # Found position, call handler of UIControl.
- result = self.content.mouse_handler(
- cli, MouseEvent(position=Point(x=col, y=row),
- event_type=mouse_event.event_type))
- break
- else:
- # nobreak.
- # (No x/y coordinate found for the content. This happens in
- # case of a FillControl, that only specifies a background, but
- # doesn't have a content. Report (0,0) instead.)
- result = self.content.mouse_handler(
- cli, MouseEvent(position=Point(x=0, y=0),
- event_type=mouse_event.event_type))
-
+ screen coordinates into line coordinates. """
+ # Find row/col position first.
+ yx_to_rowcol = dict((v, k) for k, v in rowcol_to_yx.items())
+ y = mouse_event.position.y
+ x = mouse_event.position.x
+
+ # If clicked below the content area, look for a position in the
+ # last line instead.
+ max_y = write_position.ypos + len(visible_line_to_row_col) - 1
+ y = min(max_y, y)
+
+ while x >= 0:
+ try:
+ row, col = yx_to_rowcol[y, x]
+ except KeyError:
+ # Try again. (When clicking on the right side of double
+ # width characters, or on the right side of the input.)
+ x -= 1
+ else:
+ # Found position, call handler of UIControl.
+ result = self.content.mouse_handler(
+ cli, MouseEvent(position=Point(x=col, y=row),
+ event_type=mouse_event.event_type))
+ break
+ else:
+ # nobreak.
+ # (No x/y coordinate found for the content. This happens in
+ # case of a FillControl, that only specifies a background, but
+ # doesn't have a content. Report (0,0) instead.)
+ result = self.content.mouse_handler(
+ cli, MouseEvent(position=Point(x=0, y=0),
+ event_type=mouse_event.event_type))
+
# If it returns NotImplemented, handle it here.
if result == NotImplemented:
return self._mouse_handler(cli, mouse_event)
@@ -1160,17 +1160,17 @@ class Window(Container):
# Retrieve margin tokens.
tokens = m.create_margin(cli, self.render_info, width, write_position.height)
- # Turn it into a UIContent object.
+ # Turn it into a UIContent object.
# already rendered those tokens using this size.)
- return TokenListControl.static(tokens).create_content(
- cli, width + 1, write_position.height)
+ return TokenListControl.static(tokens).create_content(
+ cli, width + 1, write_position.height)
for m, width in zip(self.left_margins, left_margin_widths):
# Create screen for margin.
margin_screen = render_margin(m, width)
# Copy and shift X.
- self._copy_margin(cli, margin_screen, screen, write_position, move_x, width)
+ self._copy_margin(cli, margin_screen, screen, write_position, move_x, width)
move_x += width
move_x = write_position.width - sum(right_margin_widths)
@@ -1180,351 +1180,351 @@ class Window(Container):
margin_screen = render_margin(m, width)
# Copy and shift X.
- self._copy_margin(cli, margin_screen, screen, write_position, move_x, width)
+ self._copy_margin(cli, margin_screen, screen, write_position, move_x, width)
move_x += width
- def _copy_body(self, cli, ui_content, new_screen, write_position, move_x,
- width, vertical_scroll=0, horizontal_scroll=0,
- has_focus=False, wrap_lines=False, highlight_lines=False,
- vertical_scroll_2=0, always_hide_cursor=False):
+ def _copy_body(self, cli, ui_content, new_screen, write_position, move_x,
+ width, vertical_scroll=0, horizontal_scroll=0,
+ has_focus=False, wrap_lines=False, highlight_lines=False,
+ vertical_scroll_2=0, always_hide_cursor=False):
"""
- Copy the UIContent into the output screen.
+ Copy the UIContent into the output screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
- line_count = ui_content.line_count
+ line_count = ui_content.line_count
new_buffer = new_screen.data_buffer
- empty_char = _CHAR_CACHE['', Token]
- ZeroWidthEscape = Token.ZeroWidthEscape
-
- # Map visible line number to (row, col) of input.
- # 'col' will always be zero if line wrapping is off.
- visible_line_to_row_col = {}
- rowcol_to_yx = {} # Maps (row, col) from the input to (y, x) screen coordinates.
-
- # Fill background with default_char first.
- default_char = ui_content.default_char
-
- if default_char:
- for y in range(ypos, ypos + write_position.height):
- new_buffer_row = new_buffer[y]
- for x in range(xpos, xpos + width):
- new_buffer_row[x] = default_char
-
- # Copy content.
- def copy():
- y = - vertical_scroll_2
- lineno = vertical_scroll
-
- while y < write_position.height and lineno < line_count:
- # Take the next line and copy it in the real screen.
- line = ui_content.get_line(lineno)
-
- col = 0
- x = -horizontal_scroll
-
- visible_line_to_row_col[y] = (lineno, horizontal_scroll)
- new_buffer_row = new_buffer[y + ypos]
-
- for token, text in line:
- # Remember raw VT escape sequences. (E.g. FinalTerm's
- # escape sequences.)
- if token == ZeroWidthEscape:
- new_screen.zero_width_escapes[y + ypos][x + xpos] += text
- continue
-
- for c in text:
- char = _CHAR_CACHE[c, token]
- char_width = char.width
-
- # Wrap when the line width is exceeded.
- if wrap_lines and x + char_width > width:
- visible_line_to_row_col[y + 1] = (
- lineno, visible_line_to_row_col[y][1] + x)
- y += 1
- x = -horizontal_scroll # This would be equal to zero.
- # (horizontal_scroll=0 when wrap_lines.)
- new_buffer_row = new_buffer[y + ypos]
-
- if y >= write_position.height:
- return y # Break out of all for loops.
-
- # Set character in screen and shift 'x'.
- if x >= 0 and y >= 0 and x < write_position.width:
- new_buffer_row[x + xpos] = char
-
- # When we print a multi width character, make sure
- # to erase the neighbous positions in the screen.
- # (The empty string if different from everything,
- # so next redraw this cell will repaint anyway.)
- if char_width > 1:
- for i in range(1, char_width):
- new_buffer_row[x + xpos + i] = empty_char
-
- # If this is a zero width characters, then it's
- # probably part of a decomposed unicode character.
- # See: https://en.wikipedia.org/wiki/Unicode_equivalence
- # Merge it in the previous cell.
- elif char_width == 0 and x - 1 >= 0:
- prev_char = new_buffer_row[x + xpos - 1]
- char2 = _CHAR_CACHE[prev_char.char + c, prev_char.token]
- new_buffer_row[x + xpos - 1] = char2
-
- # Keep track of write position for each character.
- rowcol_to_yx[lineno, col] = (y + ypos, x + xpos)
-
- col += 1
- x += char_width
-
- lineno += 1
- y += 1
- return y
-
- y = copy()
-
- def cursor_pos_to_screen_pos(row, col):
- " Translate row/col from UIContent to real Screen coordinates. "
- try:
- y, x = rowcol_to_yx[row, col]
- except KeyError:
- # Normally this should never happen. (It is a bug, if it happens.)
- # But to be sure, return (0, 0)
- return Point(y=0, x=0)
-
- # raise ValueError(
- # 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
- # 'horizontal_scroll=%r, height=%r' %
- # (row, col, vertical_scroll, horizontal_scroll, write_position.height))
+ empty_char = _CHAR_CACHE['', Token]
+ ZeroWidthEscape = Token.ZeroWidthEscape
+
+ # Map visible line number to (row, col) of input.
+ # 'col' will always be zero if line wrapping is off.
+ visible_line_to_row_col = {}
+ rowcol_to_yx = {} # Maps (row, col) from the input to (y, x) screen coordinates.
+
+ # Fill background with default_char first.
+ default_char = ui_content.default_char
+
+ if default_char:
+ for y in range(ypos, ypos + write_position.height):
+ new_buffer_row = new_buffer[y]
+ for x in range(xpos, xpos + width):
+ new_buffer_row[x] = default_char
+
+ # Copy content.
+ def copy():
+ y = - vertical_scroll_2
+ lineno = vertical_scroll
+
+ while y < write_position.height and lineno < line_count:
+ # Take the next line and copy it in the real screen.
+ line = ui_content.get_line(lineno)
+
+ col = 0
+ x = -horizontal_scroll
+
+ visible_line_to_row_col[y] = (lineno, horizontal_scroll)
+ new_buffer_row = new_buffer[y + ypos]
+
+ for token, text in line:
+ # Remember raw VT escape sequences. (E.g. FinalTerm's
+ # escape sequences.)
+ if token == ZeroWidthEscape:
+ new_screen.zero_width_escapes[y + ypos][x + xpos] += text
+ continue
+
+ for c in text:
+ char = _CHAR_CACHE[c, token]
+ char_width = char.width
+
+ # Wrap when the line width is exceeded.
+ if wrap_lines and x + char_width > width:
+ visible_line_to_row_col[y + 1] = (
+ lineno, visible_line_to_row_col[y][1] + x)
+ y += 1
+ x = -horizontal_scroll # This would be equal to zero.
+ # (horizontal_scroll=0 when wrap_lines.)
+ new_buffer_row = new_buffer[y + ypos]
+
+ if y >= write_position.height:
+ return y # Break out of all for loops.
+
+ # Set character in screen and shift 'x'.
+ if x >= 0 and y >= 0 and x < write_position.width:
+ new_buffer_row[x + xpos] = char
+
+ # When we print a multi width character, make sure
+ # to erase the neighbous positions in the screen.
+ # (The empty string if different from everything,
+ # so next redraw this cell will repaint anyway.)
+ if char_width > 1:
+ for i in range(1, char_width):
+ new_buffer_row[x + xpos + i] = empty_char
+
+ # If this is a zero width characters, then it's
+ # probably part of a decomposed unicode character.
+ # See: https://en.wikipedia.org/wiki/Unicode_equivalence
+ # Merge it in the previous cell.
+ elif char_width == 0 and x - 1 >= 0:
+ prev_char = new_buffer_row[x + xpos - 1]
+ char2 = _CHAR_CACHE[prev_char.char + c, prev_char.token]
+ new_buffer_row[x + xpos - 1] = char2
+
+ # Keep track of write position for each character.
+ rowcol_to_yx[lineno, col] = (y + ypos, x + xpos)
+
+ col += 1
+ x += char_width
+
+ lineno += 1
+ y += 1
+ return y
+
+ y = copy()
+
+ def cursor_pos_to_screen_pos(row, col):
+ " Translate row/col from UIContent to real Screen coordinates. "
+ try:
+ y, x = rowcol_to_yx[row, col]
+ except KeyError:
+ # Normally this should never happen. (It is a bug, if it happens.)
+ # But to be sure, return (0, 0)
+ return Point(y=0, x=0)
+
+ # raise ValueError(
+ # 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
+ # 'horizontal_scroll=%r, height=%r' %
+ # (row, col, vertical_scroll, horizontal_scroll, write_position.height))
else:
- return Point(y=y, x=x)
-
- # Set cursor and menu positions.
- if ui_content.cursor_position:
- screen_cursor_position = cursor_pos_to_screen_pos(
- ui_content.cursor_position.y, ui_content.cursor_position.x)
-
- if has_focus:
- new_screen.cursor_position = screen_cursor_position
-
- if always_hide_cursor:
- new_screen.show_cursor = False
- else:
- new_screen.show_cursor = ui_content.show_cursor
-
- self._highlight_digraph(cli, new_screen)
-
- if highlight_lines:
- self._highlight_cursorlines(
- cli, new_screen, screen_cursor_position, xpos, ypos, width,
- write_position.height)
-
- # Draw input characters from the input processor queue.
- if has_focus and ui_content.cursor_position:
- self._show_input_processor_key_buffer(cli, new_screen)
-
- # Set menu position.
- if not new_screen.menu_position and ui_content.menu_position:
- new_screen.menu_position = cursor_pos_to_screen_pos(
- ui_content.menu_position.y, ui_content.menu_position.x)
-
- # Update output screne height.
- new_screen.height = max(new_screen.height, ypos + write_position.height)
-
- return visible_line_to_row_col, rowcol_to_yx
-
- def _highlight_digraph(self, cli, new_screen):
- """
- When we are in Vi digraph mode, put a question mark underneath the
- cursor.
- """
- digraph_char = self._get_digraph_char(cli)
- if digraph_char:
- cpos = new_screen.cursor_position
- new_screen.data_buffer[cpos.y][cpos.x] = \
- _CHAR_CACHE[digraph_char, Token.Digraph]
-
- def _show_input_processor_key_buffer(self, cli, new_screen):
- """
- When the user is typing a key binding that consists of several keys,
- display the last pressed key if the user is in insert mode and the key
- is meaningful to be displayed.
- E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
- first 'j' needs to be displayed in order to get some feedback.
- """
- key_buffer = cli.input_processor.key_buffer
-
- if key_buffer and _in_insert_mode(cli) and not cli.is_done:
- # The textual data for the given key. (Can be a VT100 escape
- # sequence.)
- data = key_buffer[-1].data
-
- # Display only if this is a 1 cell width character.
- if get_cwidth(data) == 1:
- cpos = new_screen.cursor_position
- new_screen.data_buffer[cpos.y][cpos.x] = \
- _CHAR_CACHE[data, Token.PartialKeyBinding]
-
- def _highlight_cursorlines(self, cli, new_screen, cpos, x, y, width, height):
- """
- Highlight cursor row/column.
- """
- cursor_line_token = (':', ) + self.cursorline_token
- cursor_column_token = (':', ) + self.cursorcolumn_token
-
- data_buffer = new_screen.data_buffer
-
- # Highlight cursor line.
- if self.cursorline(cli):
- row = data_buffer[cpos.y]
- for x in range(x, x + width):
- original_char = row[x]
- row[x] = _CHAR_CACHE[
- original_char.char, original_char.token + cursor_line_token]
-
- # Highlight cursor column.
- if self.cursorcolumn(cli):
- for y2 in range(y, y + height):
- row = data_buffer[y2]
- original_char = row[cpos.x]
- row[cpos.x] = _CHAR_CACHE[
- original_char.char, original_char.token + cursor_column_token]
-
- # Highlight color columns
- for cc in self.get_colorcolumns(cli):
- assert isinstance(cc, ColorColumn)
- color_column_token = (':', ) + cc.token
- column = cc.position
-
- for y2 in range(y, y + height):
- row = data_buffer[y2]
- original_char = row[column]
- row[column] = _CHAR_CACHE[
- original_char.char, original_char.token + color_column_token]
-
- def _copy_margin(self, cli, lazy_screen, new_screen, write_position, move_x, width):
- """
+ return Point(y=y, x=x)
+
+ # Set cursor and menu positions.
+ if ui_content.cursor_position:
+ screen_cursor_position = cursor_pos_to_screen_pos(
+ ui_content.cursor_position.y, ui_content.cursor_position.x)
+
+ if has_focus:
+ new_screen.cursor_position = screen_cursor_position
+
+ if always_hide_cursor:
+ new_screen.show_cursor = False
+ else:
+ new_screen.show_cursor = ui_content.show_cursor
+
+ self._highlight_digraph(cli, new_screen)
+
+ if highlight_lines:
+ self._highlight_cursorlines(
+ cli, new_screen, screen_cursor_position, xpos, ypos, width,
+ write_position.height)
+
+ # Draw input characters from the input processor queue.
+ if has_focus and ui_content.cursor_position:
+ self._show_input_processor_key_buffer(cli, new_screen)
+
+ # Set menu position.
+ if not new_screen.menu_position and ui_content.menu_position:
+ new_screen.menu_position = cursor_pos_to_screen_pos(
+ ui_content.menu_position.y, ui_content.menu_position.x)
+
+ # Update output screne height.
+ new_screen.height = max(new_screen.height, ypos + write_position.height)
+
+ return visible_line_to_row_col, rowcol_to_yx
+
+ def _highlight_digraph(self, cli, new_screen):
+ """
+ When we are in Vi digraph mode, put a question mark underneath the
+ cursor.
+ """
+ digraph_char = self._get_digraph_char(cli)
+ if digraph_char:
+ cpos = new_screen.cursor_position
+ new_screen.data_buffer[cpos.y][cpos.x] = \
+ _CHAR_CACHE[digraph_char, Token.Digraph]
+
+ def _show_input_processor_key_buffer(self, cli, new_screen):
+ """
+ When the user is typing a key binding that consists of several keys,
+ display the last pressed key if the user is in insert mode and the key
+ is meaningful to be displayed.
+ E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
+ first 'j' needs to be displayed in order to get some feedback.
+ """
+ key_buffer = cli.input_processor.key_buffer
+
+ if key_buffer and _in_insert_mode(cli) and not cli.is_done:
+ # The textual data for the given key. (Can be a VT100 escape
+ # sequence.)
+ data = key_buffer[-1].data
+
+ # Display only if this is a 1 cell width character.
+ if get_cwidth(data) == 1:
+ cpos = new_screen.cursor_position
+ new_screen.data_buffer[cpos.y][cpos.x] = \
+ _CHAR_CACHE[data, Token.PartialKeyBinding]
+
+ def _highlight_cursorlines(self, cli, new_screen, cpos, x, y, width, height):
+ """
+ Highlight cursor row/column.
+ """
+ cursor_line_token = (':', ) + self.cursorline_token
+ cursor_column_token = (':', ) + self.cursorcolumn_token
+
+ data_buffer = new_screen.data_buffer
+
+ # Highlight cursor line.
+ if self.cursorline(cli):
+ row = data_buffer[cpos.y]
+ for x in range(x, x + width):
+ original_char = row[x]
+ row[x] = _CHAR_CACHE[
+ original_char.char, original_char.token + cursor_line_token]
+
+ # Highlight cursor column.
+ if self.cursorcolumn(cli):
+ for y2 in range(y, y + height):
+ row = data_buffer[y2]
+ original_char = row[cpos.x]
+ row[cpos.x] = _CHAR_CACHE[
+ original_char.char, original_char.token + cursor_column_token]
+
+ # Highlight color columns
+ for cc in self.get_colorcolumns(cli):
+ assert isinstance(cc, ColorColumn)
+ color_column_token = (':', ) + cc.token
+ column = cc.position
+
+ for y2 in range(y, y + height):
+ row = data_buffer[y2]
+ original_char = row[column]
+ row[column] = _CHAR_CACHE[
+ original_char.char, original_char.token + color_column_token]
+
+ def _copy_margin(self, cli, lazy_screen, new_screen, write_position, move_x, width):
+ """
Copy characters from the margin screen to the real screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
- margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
- self._copy_body(cli, lazy_screen, new_screen, margin_write_position, 0, width)
-
- def _scroll_when_linewrapping(self, ui_content, width, height, cli):
- """
- Scroll to make sure the cursor position is visible and that we maintain
- the requested scroll offset.
-
- Set `self.horizontal_scroll/vertical_scroll`.
- """
- scroll_offsets_bottom = self.scroll_offsets.bottom
- scroll_offsets_top = self.scroll_offsets.top
-
- # We don't have horizontal scrolling.
- self.horizontal_scroll = 0
-
- # If the current line consumes more than the whole window height,
- # then we have to scroll vertically inside this line. (We don't take
- # the scroll offsets into account for this.)
- # Also, ignore the scroll offsets in this case. Just set the vertical
- # scroll to this line.
- if ui_content.get_height_for_line(ui_content.cursor_position.y, width) > height - scroll_offsets_top:
- # Calculate the height of the text before the cursor, with the line
- # containing the cursor included, and the character belowe the
- # cursor included as well.
- line = explode_tokens(ui_content.get_line(ui_content.cursor_position.y))
- text_before_cursor = token_list_to_text(line[:ui_content.cursor_position.x + 1])
- text_before_height = UIContent.get_height_for_text(text_before_cursor, width)
-
- # Adjust scroll offset.
- self.vertical_scroll = ui_content.cursor_position.y
- self.vertical_scroll_2 = min(text_before_height - 1, self.vertical_scroll_2)
- self.vertical_scroll_2 = max(0, text_before_height - height, self.vertical_scroll_2)
- return
- else:
- self.vertical_scroll_2 = 0
-
- # Current line doesn't consume the whole height. Take scroll offsets into account.
- def get_min_vertical_scroll():
- # Make sure that the cursor line is not below the bottom.
- # (Calculate how many lines can be shown between the cursor and the .)
- used_height = 0
- prev_lineno = ui_content.cursor_position.y
-
- for lineno in range(ui_content.cursor_position.y, -1, -1):
- used_height += ui_content.get_height_for_line(lineno, width)
-
- if used_height > height - scroll_offsets_bottom:
- return prev_lineno
- else:
- prev_lineno = lineno
- return 0
-
- def get_max_vertical_scroll():
- # Make sure that the cursor line is not above the top.
- prev_lineno = ui_content.cursor_position.y
- used_height = 0
-
- for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
- used_height += ui_content.get_height_for_line(lineno, width)
-
- if used_height > scroll_offsets_top:
- return prev_lineno
- else:
- prev_lineno = lineno
- return prev_lineno
-
- def get_topmost_visible():
- """
- Calculate the upper most line that can be visible, while the bottom
- is still visible. We should not allow scroll more than this if
- `allow_scroll_beyond_bottom` is false.
- """
- prev_lineno = ui_content.line_count - 1
- used_height = 0
- for lineno in range(ui_content.line_count - 1, -1, -1):
- used_height += ui_content.get_height_for_line(lineno, width)
- if used_height > height:
- return prev_lineno
- else:
- prev_lineno = lineno
- return prev_lineno
-
- # Scroll vertically. (Make sure that the whole line which contains the
- # cursor is visible.
- topmost_visible = get_topmost_visible()
-
- # Note: the `min(topmost_visible, ...)` is to make sure that we
- # don't require scrolling up because of the bottom scroll offset,
- # when we are at the end of the document.
- self.vertical_scroll = max(self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll()))
- self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
-
- # Disallow scrolling beyond bottom?
- if not self.allow_scroll_beyond_bottom(cli):
- self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
-
- def _scroll_without_linewrapping(self, ui_content, width, height, cli):
- """
- Scroll to make sure the cursor position is visible and that we maintain
- the requested scroll offset.
-
- Set `self.horizontal_scroll/vertical_scroll`.
- """
- cursor_position = ui_content.cursor_position or Point(0, 0)
-
- # Without line wrapping, we will never have to scroll vertically inside
- # a single line.
- self.vertical_scroll_2 = 0
-
- if ui_content.line_count == 0:
- self.vertical_scroll = 0
- self.horizontal_scroll = 0
- return
- else:
- current_line_text = token_list_to_text(ui_content.get_line(cursor_position.y))
-
+ margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
+ self._copy_body(cli, lazy_screen, new_screen, margin_write_position, 0, width)
+
+ def _scroll_when_linewrapping(self, ui_content, width, height, cli):
+ """
+ Scroll to make sure the cursor position is visible and that we maintain
+ the requested scroll offset.
+
+ Set `self.horizontal_scroll/vertical_scroll`.
+ """
+ scroll_offsets_bottom = self.scroll_offsets.bottom
+ scroll_offsets_top = self.scroll_offsets.top
+
+ # We don't have horizontal scrolling.
+ self.horizontal_scroll = 0
+
+ # If the current line consumes more than the whole window height,
+ # then we have to scroll vertically inside this line. (We don't take
+ # the scroll offsets into account for this.)
+ # Also, ignore the scroll offsets in this case. Just set the vertical
+ # scroll to this line.
+ if ui_content.get_height_for_line(ui_content.cursor_position.y, width) > height - scroll_offsets_top:
+ # Calculate the height of the text before the cursor, with the line
+ # containing the cursor included, and the character belowe the
+ # cursor included as well.
+ line = explode_tokens(ui_content.get_line(ui_content.cursor_position.y))
+ text_before_cursor = token_list_to_text(line[:ui_content.cursor_position.x + 1])
+ text_before_height = UIContent.get_height_for_text(text_before_cursor, width)
+
+ # Adjust scroll offset.
+ self.vertical_scroll = ui_content.cursor_position.y
+ self.vertical_scroll_2 = min(text_before_height - 1, self.vertical_scroll_2)
+ self.vertical_scroll_2 = max(0, text_before_height - height, self.vertical_scroll_2)
+ return
+ else:
+ self.vertical_scroll_2 = 0
+
+ # Current line doesn't consume the whole height. Take scroll offsets into account.
+ def get_min_vertical_scroll():
+ # Make sure that the cursor line is not below the bottom.
+ # (Calculate how many lines can be shown between the cursor and the .)
+ used_height = 0
+ prev_lineno = ui_content.cursor_position.y
+
+ for lineno in range(ui_content.cursor_position.y, -1, -1):
+ used_height += ui_content.get_height_for_line(lineno, width)
+
+ if used_height > height - scroll_offsets_bottom:
+ return prev_lineno
+ else:
+ prev_lineno = lineno
+ return 0
+
+ def get_max_vertical_scroll():
+ # Make sure that the cursor line is not above the top.
+ prev_lineno = ui_content.cursor_position.y
+ used_height = 0
+
+ for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
+ used_height += ui_content.get_height_for_line(lineno, width)
+
+ if used_height > scroll_offsets_top:
+ return prev_lineno
+ else:
+ prev_lineno = lineno
+ return prev_lineno
+
+ def get_topmost_visible():
+ """
+ Calculate the upper most line that can be visible, while the bottom
+ is still visible. We should not allow scroll more than this if
+ `allow_scroll_beyond_bottom` is false.
+ """
+ prev_lineno = ui_content.line_count - 1
+ used_height = 0
+ for lineno in range(ui_content.line_count - 1, -1, -1):
+ used_height += ui_content.get_height_for_line(lineno, width)
+ if used_height > height:
+ return prev_lineno
+ else:
+ prev_lineno = lineno
+ return prev_lineno
+
+ # Scroll vertically. (Make sure that the whole line which contains the
+ # cursor is visible.
+ topmost_visible = get_topmost_visible()
+
+ # Note: the `min(topmost_visible, ...)` is to make sure that we
+ # don't require scrolling up because of the bottom scroll offset,
+ # when we are at the end of the document.
+ self.vertical_scroll = max(self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll()))
+ self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
+
+ # Disallow scrolling beyond bottom?
+ if not self.allow_scroll_beyond_bottom(cli):
+ self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
+
+ def _scroll_without_linewrapping(self, ui_content, width, height, cli):
+ """
+ Scroll to make sure the cursor position is visible and that we maintain
+ the requested scroll offset.
+
+ Set `self.horizontal_scroll/vertical_scroll`.
+ """
+ cursor_position = ui_content.cursor_position or Point(0, 0)
+
+ # Without line wrapping, we will never have to scroll vertically inside
+ # a single line.
+ self.vertical_scroll_2 = 0
+
+ if ui_content.line_count == 0:
+ self.vertical_scroll = 0
+ self.horizontal_scroll = 0
+ return
+ else:
+ current_line_text = token_list_to_text(ui_content.get_line(cursor_position.y))
+
def do_scroll(current_scroll, scroll_offset_start, scroll_offset_end,
cursor_pos, window_size, content_size):
" Scrolling algorithm. Used for both horizontal and vertical scrolling. "
@@ -1552,7 +1552,7 @@ class Window(Container):
if current_scroll < (cursor_pos + 1) - window_size + scroll_offset_end:
current_scroll = (cursor_pos + 1) - window_size + scroll_offset_end
- return current_scroll
+ return current_scroll
# When a preferred scroll is given, take that first into account.
if self.get_vertical_scroll:
@@ -1566,32 +1566,32 @@ class Window(Container):
# remains visible.
offsets = self.scroll_offsets
- self.vertical_scroll = do_scroll(
+ self.vertical_scroll = do_scroll(
current_scroll=self.vertical_scroll,
scroll_offset_start=offsets.top,
scroll_offset_end=offsets.bottom,
- cursor_pos=ui_content.cursor_position.y,
+ cursor_pos=ui_content.cursor_position.y,
window_size=height,
- content_size=ui_content.line_count)
+ content_size=ui_content.line_count)
- self.horizontal_scroll = do_scroll(
+ self.horizontal_scroll = do_scroll(
current_scroll=self.horizontal_scroll,
scroll_offset_start=offsets.left,
scroll_offset_end=offsets.right,
- cursor_pos=get_cwidth(current_line_text[:ui_content.cursor_position.x]),
+ cursor_pos=get_cwidth(current_line_text[:ui_content.cursor_position.x]),
window_size=width,
- # We can only analyse the current line. Calculating the width off
- # all the lines is too expensive.
- content_size=max(get_cwidth(current_line_text), self.horizontal_scroll + width))
+ # We can only analyse the current line. Calculating the width off
+ # all the lines is too expensive.
+ content_size=max(get_cwidth(current_line_text), self.horizontal_scroll + width))
def _mouse_handler(self, cli, mouse_event):
"""
Mouse handler. Called when the UI control doesn't handle this
particular event.
"""
- if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
+ if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
self._scroll_down(cli)
- elif mouse_event.event_type == MouseEventType.SCROLL_UP:
+ elif mouse_event.event_type == MouseEventType.SCROLL_UP:
self._scroll_up(cli)
def _scroll_down(self, cli):
@@ -1609,7 +1609,7 @@ class Window(Container):
info = self.render_info
if info.vertical_scroll > 0:
- # TODO: not entirely correct yet in case of line wrapping and long lines.
+ # TODO: not entirely correct yet in case of line wrapping and long lines.
if info.cursor_position.y >= info.window_height - 1 - info.configured_scroll_offsets.bottom:
self.content.move_cursor_up(cli)
@@ -1635,9 +1635,9 @@ class ConditionalContainer(Container):
self.content = content
self.filter = to_cli_filter(filter)
- def __repr__(self):
- return 'ConditionalContainer(%r, filter=%r)' % (self.content, self.filter)
-
+ def __repr__(self):
+ return 'ConditionalContainer(%r, filter=%r)' % (self.content, self.filter)
+
def reset(self):
self.content.reset()
@@ -1647,9 +1647,9 @@ class ConditionalContainer(Container):
else:
return LayoutDimension.exact(0)
- def preferred_height(self, cli, width, max_available_height):
+ def preferred_height(self, cli, width, max_available_height):
if self.filter(cli):
- return self.content.preferred_height(cli, width, max_available_height)
+ return self.content.preferred_height(cli, width, max_available_height)
else:
return LayoutDimension.exact(0)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py
index 951110f82b..ca74931dbc 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py
@@ -4,34 +4,34 @@ User interface Controls for the layout.
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
-from collections import namedtuple
+from collections import namedtuple
from six import with_metaclass
-from six.moves import range
+from six.moves import range
-from prompt_toolkit.cache import SimpleCache
+from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
from prompt_toolkit.filters import to_cli_filter
-from prompt_toolkit.mouse_events import MouseEventType
+from prompt_toolkit.mouse_events import MouseEventType
from prompt_toolkit.search_state import SearchState
from prompt_toolkit.selection import SelectionType
-from prompt_toolkit.token import Token
-from prompt_toolkit.utils import get_cwidth
+from prompt_toolkit.token import Token
+from prompt_toolkit.utils import get_cwidth
from .lexers import Lexer, SimpleLexer
-from .processors import Processor
-from .screen import Char, Point
-from .utils import token_list_width, split_lines, token_list_to_text
+from .processors import Processor
+from .screen import Char, Point
+from .utils import token_list_width, split_lines, token_list_to_text
-import six
+import six
import time
-
+
__all__ = (
'BufferControl',
'FillControl',
'TokenListControl',
'UIControl',
- 'UIContent',
+ 'UIContent',
)
@@ -46,7 +46,7 @@ class UIControl(with_metaclass(ABCMeta, object)):
def preferred_width(self, cli, max_available_width):
return None
- def preferred_height(self, cli, width, max_available_height, wrap_lines):
+ def preferred_height(self, cli, width, max_available_height, wrap_lines):
return None
def has_focus(self, cli):
@@ -54,18 +54,18 @@ class UIControl(with_metaclass(ABCMeta, object)):
Return ``True`` when this user control has the focus.
If so, the cursor will be displayed according to the cursor position
- reported by :meth:`.UIControl.create_content`. If the created content
- has the property ``show_cursor=False``, the cursor will be hidden from
- the output.
+ reported by :meth:`.UIControl.create_content`. If the created content
+ has the property ``show_cursor=False``, the cursor will be hidden from
+ the output.
"""
return False
@abstractmethod
- def create_content(self, cli, width, height):
+ def create_content(self, cli, width, height):
"""
- Generate the content for this user control.
+ Generate the content for this user control.
- Returns a :class:`.UIContent` instance.
+ Returns a :class:`.UIContent` instance.
"""
def mouse_handler(self, cli, mouse_event):
@@ -94,78 +94,78 @@ class UIControl(with_metaclass(ABCMeta, object)):
"""
-class UIContent(object):
- """
- Content generated by a user control. This content consists of a list of
- lines.
-
- :param get_line: Callable that returns the current line. This is a list of
- (Token, text) tuples.
- :param line_count: The number of lines.
- :param cursor_position: a :class:`.Point` for the cursor position.
- :param menu_position: a :class:`.Point` for the menu position.
- :param show_cursor: Make the cursor visible.
- :param default_char: The default :class:`.Char` for filling the background.
- """
- def __init__(self, get_line=None, line_count=0,
- cursor_position=None, menu_position=None, show_cursor=True,
- default_char=None):
- assert callable(get_line)
- assert isinstance(line_count, six.integer_types)
- assert cursor_position is None or isinstance(cursor_position, Point)
- assert menu_position is None or isinstance(menu_position, Point)
- assert default_char is None or isinstance(default_char, Char)
-
- self.get_line = get_line
- self.line_count = line_count
- self.cursor_position = cursor_position or Point(0, 0)
- self.menu_position = menu_position
- self.show_cursor = show_cursor
- self.default_char = default_char
-
- # Cache for line heights. Maps (lineno, width) -> height.
- self._line_heights = {}
-
- def __getitem__(self, lineno):
- " Make it iterable (iterate line by line). "
- if lineno < self.line_count:
- return self.get_line(lineno)
- else:
- raise IndexError
-
- def get_height_for_line(self, lineno, width):
- """
- Return the height that a given line would need if it is rendered in a
- space with the given width.
- """
- try:
- return self._line_heights[lineno, width]
- except KeyError:
- text = token_list_to_text(self.get_line(lineno))
- result = self.get_height_for_text(text, width)
-
- # Cache and return
- self._line_heights[lineno, width] = result
- return result
-
- @staticmethod
- def get_height_for_text(text, width):
- # Get text width for this line.
- line_width = get_cwidth(text)
-
- # Calculate height.
- try:
- quotient, remainder = divmod(line_width, width)
- except ZeroDivisionError:
- # Return something very big.
- # (This can happen, when the Window gets very small.)
- return 10 ** 10
- else:
- if remainder:
- quotient += 1 # Like math.ceil.
- return max(1, quotient)
-
-
+class UIContent(object):
+ """
+ Content generated by a user control. This content consists of a list of
+ lines.
+
+ :param get_line: Callable that returns the current line. This is a list of
+ (Token, text) tuples.
+ :param line_count: The number of lines.
+ :param cursor_position: a :class:`.Point` for the cursor position.
+ :param menu_position: a :class:`.Point` for the menu position.
+ :param show_cursor: Make the cursor visible.
+ :param default_char: The default :class:`.Char` for filling the background.
+ """
+ def __init__(self, get_line=None, line_count=0,
+ cursor_position=None, menu_position=None, show_cursor=True,
+ default_char=None):
+ assert callable(get_line)
+ assert isinstance(line_count, six.integer_types)
+ assert cursor_position is None or isinstance(cursor_position, Point)
+ assert menu_position is None or isinstance(menu_position, Point)
+ assert default_char is None or isinstance(default_char, Char)
+
+ self.get_line = get_line
+ self.line_count = line_count
+ self.cursor_position = cursor_position or Point(0, 0)
+ self.menu_position = menu_position
+ self.show_cursor = show_cursor
+ self.default_char = default_char
+
+ # Cache for line heights. Maps (lineno, width) -> height.
+ self._line_heights = {}
+
+ def __getitem__(self, lineno):
+ " Make it iterable (iterate line by line). "
+ if lineno < self.line_count:
+ return self.get_line(lineno)
+ else:
+ raise IndexError
+
+ def get_height_for_line(self, lineno, width):
+ """
+ Return the height that a given line would need if it is rendered in a
+ space with the given width.
+ """
+ try:
+ return self._line_heights[lineno, width]
+ except KeyError:
+ text = token_list_to_text(self.get_line(lineno))
+ result = self.get_height_for_text(text, width)
+
+ # Cache and return
+ self._line_heights[lineno, width] = result
+ return result
+
+ @staticmethod
+ def get_height_for_text(text, width):
+ # Get text width for this line.
+ line_width = get_cwidth(text)
+
+ # Calculate height.
+ try:
+ quotient, remainder = divmod(line_width, width)
+ except ZeroDivisionError:
+ # Return something very big.
+ # (This can happen, when the Window gets very small.)
+ return 10 ** 10
+ else:
+ if remainder:
+ quotient += 1 # Like math.ceil.
+ return max(1, quotient)
+
+
class TokenListControl(UIControl):
"""
Control that displays a list of (Token, text) tuples.
@@ -195,8 +195,8 @@ class TokenListControl(UIControl):
cursor will be shown there.
"""
def __init__(self, get_tokens, default_char=None, get_default_char=None,
- align_right=False, align_center=False, has_focus=False):
- assert callable(get_tokens)
+ align_right=False, align_center=False, has_focus=False):
+ assert callable(get_tokens)
assert default_char is None or isinstance(default_char, Char)
assert get_default_char is None or callable(get_default_char)
assert not (default_char and get_default_char)
@@ -211,21 +211,21 @@ class TokenListControl(UIControl):
if default_char:
get_default_char = lambda _: default_char
elif not get_default_char:
- get_default_char = lambda _: Char(' ', Token.Transparent)
+ get_default_char = lambda _: Char(' ', Token.Transparent)
self.get_default_char = get_default_char
- #: Cache for the content.
- self._content_cache = SimpleCache(maxsize=18)
- self._token_cache = SimpleCache(maxsize=1)
+ #: Cache for the content.
+ self._content_cache = SimpleCache(maxsize=18)
+ self._token_cache = SimpleCache(maxsize=1)
# Only cache one token list. We don't need the previous item.
# Render info for the mouse support.
- self._tokens = None
+ self._tokens = None
+
+ def reset(self):
+ self._tokens = None
- def reset(self):
- self._tokens = None
-
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.get_tokens)
@@ -235,7 +235,7 @@ class TokenListControl(UIControl):
(This function is called several times during one rendering, because
we also need those for calculating the dimensions.)
"""
- return self._token_cache.get(
+ return self._token_cache.get(
cli.render_counter, lambda: self.get_tokens(cli))
def has_focus(self, cli):
@@ -246,15 +246,15 @@ class TokenListControl(UIControl):
Return the preferred width for this control.
That is the width of the longest line.
"""
- text = token_list_to_text(self._get_tokens_cached(cli))
+ text = token_list_to_text(self._get_tokens_cached(cli))
line_lengths = [get_cwidth(l) for l in text.split('\n')]
return max(line_lengths)
- def preferred_height(self, cli, width, max_available_height, wrap_lines):
- content = self.create_content(cli, width, None)
- return content.line_count
+ def preferred_height(self, cli, width, max_available_height, wrap_lines):
+ content = self.create_content(cli, width, None)
+ return content.line_count
- def create_content(self, cli, width, height):
+ def create_content(self, cli, width, height):
# Get tokens
tokens_with_mouse_handlers = self._get_tokens_cached(cli)
@@ -270,51 +270,51 @@ class TokenListControl(UIControl):
padding = width - used_width
if center:
padding = int(padding / 2)
- return [(default_char.token, default_char.char * padding)] + line
+ return [(default_char.token, default_char.char * padding)] + line
if right or center:
- token_lines_with_mouse_handlers = []
-
+ token_lines_with_mouse_handlers = []
+
for line in split_lines(tokens_with_mouse_handlers):
- token_lines_with_mouse_handlers.append(process_line(line))
- else:
- token_lines_with_mouse_handlers = list(split_lines(tokens_with_mouse_handlers))
+ token_lines_with_mouse_handlers.append(process_line(line))
+ else:
+ token_lines_with_mouse_handlers = list(split_lines(tokens_with_mouse_handlers))
# Strip mouse handlers from tokens.
- token_lines = [
- [tuple(item[:2]) for item in line]
- for line in token_lines_with_mouse_handlers
- ]
+ token_lines = [
+ [tuple(item[:2]) for item in line]
+ for line in token_lines_with_mouse_handlers
+ ]
- # Keep track of the tokens with mouse handler, for later use in
- # `mouse_handler`.
+ # Keep track of the tokens with mouse handler, for later use in
+ # `mouse_handler`.
self._tokens = tokens_with_mouse_handlers
- # If there is a `Token.SetCursorPosition` in the token list, set the
- # cursor position here.
- def get_cursor_position():
- SetCursorPosition = Token.SetCursorPosition
-
- for y, line in enumerate(token_lines):
- x = 0
- for token, text in line:
- if token == SetCursorPosition:
- return Point(x=x, y=y)
- x += len(text)
- return None
-
- # Create content, or take it from the cache.
- key = (default_char.char, default_char.token,
- tuple(tokens_with_mouse_handlers), width, right, center)
-
- def get_content():
- return UIContent(get_line=lambda i: token_lines[i],
- line_count=len(token_lines),
- default_char=default_char,
- cursor_position=get_cursor_position())
-
- return self._content_cache.get(key, get_content)
-
+ # If there is a `Token.SetCursorPosition` in the token list, set the
+ # cursor position here.
+ def get_cursor_position():
+ SetCursorPosition = Token.SetCursorPosition
+
+ for y, line in enumerate(token_lines):
+ x = 0
+ for token, text in line:
+ if token == SetCursorPosition:
+ return Point(x=x, y=y)
+ x += len(text)
+ return None
+
+ # Create content, or take it from the cache.
+ key = (default_char.char, default_char.token,
+ tuple(tokens_with_mouse_handlers), width, right, center)
+
+ def get_content():
+ return UIContent(get_line=lambda i: token_lines[i],
+ line_count=len(token_lines),
+ default_char=default_char,
+ cursor_position=get_cursor_position())
+
+ return self._content_cache.get(key, get_content)
+
@classmethod
def static(cls, tokens):
def get_static_tokens(cli):
@@ -330,29 +330,29 @@ class TokenListControl(UIControl):
return `NotImplemented` in case we want the `Window` to handle this
particular event.)
"""
- if self._tokens:
- # Read the generator.
- tokens_for_line = list(split_lines(self._tokens))
-
- try:
- tokens = tokens_for_line[mouse_event.position.y]
- except IndexError:
- return NotImplemented
- else:
- # Find position in the token list.
- xpos = mouse_event.position.x
-
+ if self._tokens:
+ # Read the generator.
+ tokens_for_line = list(split_lines(self._tokens))
+
+ try:
+ tokens = tokens_for_line[mouse_event.position.y]
+ except IndexError:
+ return NotImplemented
+ else:
+ # Find position in the token list.
+ xpos = mouse_event.position.x
+
# Find mouse handler for this character.
count = 0
- for item in tokens:
+ for item in tokens:
count += len(item[1])
- if count >= xpos:
+ if count >= xpos:
if len(item) >= 3:
# Handler found. Call it.
- # (Handler can return NotImplemented, so return
- # that result.)
+ # (Handler can return NotImplemented, so return
+ # that result.)
handler = item[2]
- return handler(cli, mouse_event)
+ return handler(cli, mouse_event)
else:
break
@@ -364,38 +364,38 @@ class FillControl(UIControl):
"""
Fill whole control with characters with this token.
(Also helpful for debugging.)
-
- :param char: :class:`.Char` instance to use for filling.
- :param get_char: A callable that takes a CommandLineInterface and returns a
- :class:`.Char` object.
+
+ :param char: :class:`.Char` instance to use for filling.
+ :param get_char: A callable that takes a CommandLineInterface and returns a
+ :class:`.Char` object.
"""
- def __init__(self, character=None, token=Token, char=None, get_char=None): # 'character' and 'token' parameters are deprecated.
- assert char is None or isinstance(char, Char)
- assert get_char is None or callable(get_char)
- assert not (char and get_char)
-
- self.char = char
-
- if character:
- # Passing (character=' ', token=token) is deprecated.
- self.character = character
- self.token = token
-
- self.get_char = lambda cli: Char(character, token)
- elif get_char:
- # When 'get_char' is given.
- self.get_char = get_char
- else:
- # When 'char' is given.
- self.char = self.char or Char()
- self.get_char = lambda cli: self.char
- self.char = char
-
+ def __init__(self, character=None, token=Token, char=None, get_char=None): # 'character' and 'token' parameters are deprecated.
+ assert char is None or isinstance(char, Char)
+ assert get_char is None or callable(get_char)
+ assert not (char and get_char)
+
+ self.char = char
+
+ if character:
+ # Passing (character=' ', token=token) is deprecated.
+ self.character = character
+ self.token = token
+
+ self.get_char = lambda cli: Char(character, token)
+ elif get_char:
+ # When 'get_char' is given.
+ self.get_char = get_char
+ else:
+ # When 'char' is given.
+ self.char = self.char or Char()
+ self.get_char = lambda cli: self.char
+ self.char = char
+
def __repr__(self):
- if self.char:
- return '%s(char=%r)' % (self.__class__.__name__, self.char)
- else:
- return '%s(get_char=%r)' % (self.__class__.__name__, self.get_char)
+ if self.char:
+ return '%s(char=%r)' % (self.__class__.__name__, self.char)
+ else:
+ return '%s(get_char=%r)' % (self.__class__.__name__, self.get_char)
def reset(self):
pass
@@ -403,19 +403,19 @@ class FillControl(UIControl):
def has_focus(self, cli):
return False
- def create_content(self, cli, width, height):
- def get_line(i):
- return []
+ def create_content(self, cli, width, height):
+ def get_line(i):
+ return []
+
+ return UIContent(
+ get_line=get_line,
+ line_count=100 ** 100, # Something very big.
+ default_char=self.get_char(cli))
+
+
+_ProcessedLine = namedtuple('_ProcessedLine', 'tokens source_to_display display_to_source')
- return UIContent(
- get_line=get_line,
- line_count=100 ** 100, # Something very big.
- default_char=self.get_char(cli))
-
-_ProcessedLine = namedtuple('_ProcessedLine', 'tokens source_to_display display_to_source')
-
-
class BufferControl(UIControl):
"""
Control for visualising the content of a `Buffer`.
@@ -444,7 +444,7 @@ class BufferControl(UIControl):
assert menu_position is None or callable(menu_position)
assert lexer is None or isinstance(lexer, Lexer)
assert get_search_state is None or callable(get_search_state)
- assert default_char is None or isinstance(default_char, Char)
+ assert default_char is None or isinstance(default_char, Char)
self.preview_search = to_cli_filter(preview_search)
self.get_search_state = get_search_state
@@ -457,15 +457,15 @@ class BufferControl(UIControl):
self.default_char = default_char or Char(token=Token.Transparent)
self.search_buffer_name = search_buffer_name
- #: Cache for the lexer.
+ #: Cache for the lexer.
#: Often, due to cursor movement, undo/redo and window resizing
#: operations, it happens that a short time, the same document has to be
#: lexed. This is a faily easy way to cache such an expensive operation.
- self._token_cache = SimpleCache(maxsize=8)
+ self._token_cache = SimpleCache(maxsize=8)
self._xy_to_cursor_position = None
self._last_click_timestamp = None
- self._last_get_processed_line = None
+ self._last_get_processed_line = None
def _buffer(self, cli):
"""
@@ -483,114 +483,114 @@ class BufferControl(UIControl):
any(i.has_focus(cli) for i in self.input_processors)
def preferred_width(self, cli, max_available_width):
- """
- This should return the preferred width.
-
- Note: We don't specify a preferred width according to the content,
- because it would be too expensive. Calculating the preferred
- width can be done by calculating the longest line, but this would
- require applying all the processors to each line. This is
- unfeasible for a larger document, and doing it for small
- documents only would result in inconsistent behaviour.
"""
- return None
-
- def preferred_height(self, cli, width, max_available_height, wrap_lines):
- # Calculate the content height, if it was drawn on a screen with the
- # given width.
- height = 0
- content = self.create_content(cli, width, None)
-
- # When line wrapping is off, the height should be equal to the amount
- # of lines.
- if not wrap_lines:
- return content.line_count
-
- # When the number of lines exceeds the max_available_height, just
- # return max_available_height. No need to calculate anything.
- if content.line_count >= max_available_height:
- return max_available_height
-
- for i in range(content.line_count):
- height += content.get_height_for_line(i, width)
-
- if height >= max_available_height:
- return max_available_height
-
- return height
-
- def _get_tokens_for_line_func(self, cli, document):
+ This should return the preferred width.
+
+ Note: We don't specify a preferred width according to the content,
+ because it would be too expensive. Calculating the preferred
+ width can be done by calculating the longest line, but this would
+ require applying all the processors to each line. This is
+ unfeasible for a larger document, and doing it for small
+ documents only would result in inconsistent behaviour.
+ """
+ return None
+
+ def preferred_height(self, cli, width, max_available_height, wrap_lines):
+ # Calculate the content height, if it was drawn on a screen with the
+ # given width.
+ height = 0
+ content = self.create_content(cli, width, None)
+
+ # When line wrapping is off, the height should be equal to the amount
+ # of lines.
+ if not wrap_lines:
+ return content.line_count
+
+ # When the number of lines exceeds the max_available_height, just
+ # return max_available_height. No need to calculate anything.
+ if content.line_count >= max_available_height:
+ return max_available_height
+
+ for i in range(content.line_count):
+ height += content.get_height_for_line(i, width)
+
+ if height >= max_available_height:
+ return max_available_height
+
+ return height
+
+ def _get_tokens_for_line_func(self, cli, document):
+ """
+ Create a function that returns the tokens for a given line.
"""
- Create a function that returns the tokens for a given line.
- """
- # Cache using `document.text`.
- def get_tokens_for_line():
- return self.lexer.lex_document(cli, document)
-
- return self._token_cache.get(document.text, get_tokens_for_line)
-
- def _create_get_processed_line_func(self, cli, document):
- """
- Create a function that takes a line number of the current document and
- returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source)
- tuple.
- """
- def transform(lineno, tokens):
- " Transform the tokens for a given line number. "
+ # Cache using `document.text`.
+ def get_tokens_for_line():
+ return self.lexer.lex_document(cli, document)
+
+ return self._token_cache.get(document.text, get_tokens_for_line)
+
+ def _create_get_processed_line_func(self, cli, document):
+ """
+ Create a function that takes a line number of the current document and
+ returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source)
+ tuple.
+ """
+ def transform(lineno, tokens):
+ " Transform the tokens for a given line number. "
source_to_display_functions = []
display_to_source_functions = []
- # Get cursor position at this line.
- if document.cursor_position_row == lineno:
- cursor_column = document.cursor_position_col
- else:
- cursor_column = None
-
- def source_to_display(i):
- """ Translate x position from the buffer to the x position in the
- processed token list. """
- for f in source_to_display_functions:
- i = f(i)
- return i
-
- # Apply each processor.
+ # Get cursor position at this line.
+ if document.cursor_position_row == lineno:
+ cursor_column = document.cursor_position_col
+ else:
+ cursor_column = None
+
+ def source_to_display(i):
+ """ Translate x position from the buffer to the x position in the
+ processed token list. """
+ for f in source_to_display_functions:
+ i = f(i)
+ return i
+
+ # Apply each processor.
for p in self.input_processors:
- transformation = p.apply_transformation(
- cli, document, lineno, source_to_display, tokens)
+ transformation = p.apply_transformation(
+ cli, document, lineno, source_to_display, tokens)
tokens = transformation.tokens
- if cursor_column:
- cursor_column = transformation.source_to_display(cursor_column)
+ if cursor_column:
+ cursor_column = transformation.source_to_display(cursor_column)
- display_to_source_functions.append(transformation.display_to_source)
- source_to_display_functions.append(transformation.source_to_display)
+ display_to_source_functions.append(transformation.display_to_source)
+ source_to_display_functions.append(transformation.source_to_display)
- def display_to_source(i):
+ def display_to_source(i):
for f in reversed(display_to_source_functions):
- i = f(i)
- return i
-
- return _ProcessedLine(tokens, source_to_display, display_to_source)
-
- def create_func():
- get_line = self._get_tokens_for_line_func(cli, document)
- cache = {}
-
- def get_processed_line(i):
- try:
- return cache[i]
- except KeyError:
- processed_line = transform(i, get_line(i))
- cache[i] = processed_line
- return processed_line
- return get_processed_line
-
- return create_func()
-
- def create_content(self, cli, width, height):
- """
- Create a UIContent.
- """
+ i = f(i)
+ return i
+
+ return _ProcessedLine(tokens, source_to_display, display_to_source)
+
+ def create_func():
+ get_line = self._get_tokens_for_line_func(cli, document)
+ cache = {}
+
+ def get_processed_line(i):
+ try:
+ return cache[i]
+ except KeyError:
+ processed_line = transform(i, get_line(i))
+ cache[i] = processed_line
+ return processed_line
+ return get_processed_line
+
+ return create_func()
+
+ def create_content(self, cli, width, height):
+ """
+ Create a UIContent.
+ """
buffer = self._buffer(cli)
# Get the document to be shown. If we are currently searching (the
@@ -615,31 +615,31 @@ class BufferControl(UIControl):
else:
document = buffer.document
- get_processed_line = self._create_get_processed_line_func(cli, document)
- self._last_get_processed_line = get_processed_line
+ get_processed_line = self._create_get_processed_line_func(cli, document)
+ self._last_get_processed_line = get_processed_line
- def translate_rowcol(row, col):
- " Return the content column for this coordinate. "
- return Point(y=row, x=get_processed_line(row).source_to_display(col))
+ def translate_rowcol(row, col):
+ " Return the content column for this coordinate. "
+ return Point(y=row, x=get_processed_line(row).source_to_display(col))
- def get_line(i):
- " Return the tokens for a given line number. "
- tokens = get_processed_line(i).tokens
+ def get_line(i):
+ " Return the tokens for a given line number. "
+ tokens = get_processed_line(i).tokens
- # Add a space at the end, because that is a possible cursor
- # position. (When inserting after the input.) We should do this on
- # all the lines, not just the line containing the cursor. (Because
- # otherwise, line wrapping/scrolling could change when moving the
- # cursor around.)
- tokens = tokens + [(self.default_char.token, ' ')]
- return tokens
+ # Add a space at the end, because that is a possible cursor
+ # position. (When inserting after the input.) We should do this on
+ # all the lines, not just the line containing the cursor. (Because
+ # otherwise, line wrapping/scrolling could change when moving the
+ # cursor around.)
+ tokens = tokens + [(self.default_char.token, ' ')]
+ return tokens
- content = UIContent(
- get_line=get_line,
- line_count=document.line_count,
- cursor_position=translate_rowcol(document.cursor_position_row,
- document.cursor_position_col),
- default_char=self.default_char)
+ content = UIContent(
+ get_line=get_line,
+ line_count=document.line_count,
+ cursor_position=translate_rowcol(document.cursor_position_row,
+ document.cursor_position_col),
+ default_char=self.default_char)
# If there is an auto completion going on, use that start point for a
# pop-up menu position. (But only when this buffer has the focus --
@@ -648,22 +648,22 @@ class BufferControl(UIControl):
menu_position = self.menu_position(cli) if self.menu_position else None
if menu_position is not None:
assert isinstance(menu_position, int)
- menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
- content.menu_position = translate_rowcol(menu_row, menu_col)
+ menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
+ content.menu_position = translate_rowcol(menu_row, menu_col)
elif buffer.complete_state:
# Position for completion menu.
# Note: We use 'min', because the original cursor position could be
# behind the input string when the actual completion is for
# some reason shorter than the text we had before. (A completion
# can change and shorten the input.)
- menu_row, menu_col = buffer.document.translate_index_to_position(
+ menu_row, menu_col = buffer.document.translate_index_to_position(
min(buffer.cursor_position,
buffer.complete_state.original_document.cursor_position))
- content.menu_position = translate_rowcol(menu_row, menu_col)
+ content.menu_position = translate_rowcol(menu_row, menu_col)
else:
- content.menu_position = None
+ content.menu_position = None
- return content
+ return content
def mouse_handler(self, cli, mouse_event):
"""
@@ -674,46 +674,46 @@ class BufferControl(UIControl):
# Focus buffer when clicked.
if self.has_focus(cli):
- if self._last_get_processed_line:
- processed_line = self._last_get_processed_line(position.y)
-
+ if self._last_get_processed_line:
+ processed_line = self._last_get_processed_line(position.y)
+
# Translate coordinates back to the cursor position of the
# original input.
- xpos = processed_line.display_to_source(position.x)
- index = buffer.document.translate_row_col_to_index(position.y, xpos)
+ xpos = processed_line.display_to_source(position.x)
+ index = buffer.document.translate_row_col_to_index(position.y, xpos)
# Set the cursor position.
- if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
- buffer.exit_selection()
- buffer.cursor_position = index
-
- elif mouse_event.event_type == MouseEventType.MOUSE_UP:
- # When the cursor was moved to another place, select the text.
- # (The >1 is actually a small but acceptable workaround for
- # selecting text in Vi navigation mode. In navigation mode,
- # the cursor can never be after the text, so the cursor
- # will be repositioned automatically.)
- if abs(buffer.cursor_position - index) > 1:
- buffer.start_selection(selection_type=SelectionType.CHARACTERS)
- buffer.cursor_position = index
-
- # Select word around cursor on double click.
- # Two MOUSE_UP events in a short timespan are considered a double click.
- double_click = self._last_click_timestamp and time.time() - self._last_click_timestamp < .3
- self._last_click_timestamp = time.time()
-
- if double_click:
- start, end = buffer.document.find_boundaries_of_current_word()
- buffer.cursor_position += start
- buffer.start_selection(selection_type=SelectionType.CHARACTERS)
- buffer.cursor_position += end - start
- else:
- # Don't handle scroll events here.
- return NotImplemented
+ if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
+ buffer.exit_selection()
+ buffer.cursor_position = index
+
+ elif mouse_event.event_type == MouseEventType.MOUSE_UP:
+ # When the cursor was moved to another place, select the text.
+ # (The >1 is actually a small but acceptable workaround for
+ # selecting text in Vi navigation mode. In navigation mode,
+ # the cursor can never be after the text, so the cursor
+ # will be repositioned automatically.)
+ if abs(buffer.cursor_position - index) > 1:
+ buffer.start_selection(selection_type=SelectionType.CHARACTERS)
+ buffer.cursor_position = index
+
+ # Select word around cursor on double click.
+ # Two MOUSE_UP events in a short timespan are considered a double click.
+ double_click = self._last_click_timestamp and time.time() - self._last_click_timestamp < .3
+ self._last_click_timestamp = time.time()
+
+ if double_click:
+ start, end = buffer.document.find_boundaries_of_current_word()
+ buffer.cursor_position += start
+ buffer.start_selection(selection_type=SelectionType.CHARACTERS)
+ buffer.cursor_position += end - start
+ else:
+ # Don't handle scroll events here.
+ return NotImplemented
# Not focussed, but focussing on click events.
else:
- if self.focus_on_click(cli) and mouse_event.event_type == MouseEventType.MOUSE_UP:
+ if self.focus_on_click(cli) and mouse_event.event_type == MouseEventType.MOUSE_UP:
# Focus happens on mouseup. (If we did this on mousedown, the
# up event will be received at the point where this widget is
# focussed and be handled anyway.)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py
index 9808f2edb5..a928fd8226 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py
@@ -5,22 +5,22 @@ Used for syntax highlighting.
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from six import with_metaclass
-from six.moves import range
-
-from prompt_toolkit.token import Token
-from prompt_toolkit.filters import to_cli_filter
-from .utils import split_lines
-
-import re
-import six
-
+from six.moves import range
+
+from prompt_toolkit.token import Token
+from prompt_toolkit.filters import to_cli_filter
+from .utils import split_lines
+
+import re
+import six
+
__all__ = (
'Lexer',
'SimpleLexer',
'PygmentsLexer',
- 'SyntaxSync',
- 'SyncFromStart',
- 'RegexSync',
+ 'SyntaxSync',
+ 'SyncFromStart',
+ 'RegexSync',
)
@@ -29,127 +29,127 @@ class Lexer(with_metaclass(ABCMeta, object)):
Base class for all lexers.
"""
@abstractmethod
- def lex_document(self, cli, document):
+ def lex_document(self, cli, document):
"""
- Takes a :class:`~prompt_toolkit.document.Document` and returns a
- callable that takes a line number and returns the tokens for that line.
+ Takes a :class:`~prompt_toolkit.document.Document` and returns a
+ callable that takes a line number and returns the tokens for that line.
"""
class SimpleLexer(Lexer):
"""
- Lexer that doesn't do any tokenizing and returns the whole input as one token.
-
- :param token: The `Token` for this lexer.
+ Lexer that doesn't do any tokenizing and returns the whole input as one token.
+
+ :param token: The `Token` for this lexer.
+ """
+ # `default_token` parameter is deprecated!
+ def __init__(self, token=Token, default_token=None):
+ self.token = token
+
+ if default_token is not None:
+ self.token = default_token
+
+ def lex_document(self, cli, document):
+ lines = document.lines
+
+ def get_line(lineno):
+ " Return the tokens for the given line. "
+ try:
+ return [(self.token, lines[lineno])]
+ except IndexError:
+ return []
+ return get_line
+
+
+class SyntaxSync(with_metaclass(ABCMeta, object)):
+ """
+ Syntax synchroniser. This is a tool that finds a start position for the
+ lexer. This is especially important when editing big documents; we don't
+ want to start the highlighting by running the lexer from the beginning of
+ the file. That is very slow when editing.
+ """
+ @abstractmethod
+ def get_sync_start_position(self, document, lineno):
+ """
+ Return the position from where we can start lexing as a (row, column)
+ tuple.
+
+ :param document: `Document` instance that contains all the lines.
+ :param lineno: The line that we want to highlight. (We need to return
+ this line, or an earlier position.)
+ """
+
+class SyncFromStart(SyntaxSync):
+ """
+ Always start the syntax highlighting from the beginning.
+ """
+ def get_sync_start_position(self, document, lineno):
+ return 0, 0
+
+
+class RegexSync(SyntaxSync):
+ """
+ Synchronize by starting at a line that matches the given regex pattern.
"""
- # `default_token` parameter is deprecated!
- def __init__(self, token=Token, default_token=None):
- self.token = token
-
- if default_token is not None:
- self.token = default_token
-
- def lex_document(self, cli, document):
- lines = document.lines
-
- def get_line(lineno):
- " Return the tokens for the given line. "
- try:
- return [(self.token, lines[lineno])]
- except IndexError:
- return []
- return get_line
-
-
-class SyntaxSync(with_metaclass(ABCMeta, object)):
- """
- Syntax synchroniser. This is a tool that finds a start position for the
- lexer. This is especially important when editing big documents; we don't
- want to start the highlighting by running the lexer from the beginning of
- the file. That is very slow when editing.
- """
- @abstractmethod
- def get_sync_start_position(self, document, lineno):
- """
- Return the position from where we can start lexing as a (row, column)
- tuple.
-
- :param document: `Document` instance that contains all the lines.
- :param lineno: The line that we want to highlight. (We need to return
- this line, or an earlier position.)
- """
-
-class SyncFromStart(SyntaxSync):
- """
- Always start the syntax highlighting from the beginning.
- """
- def get_sync_start_position(self, document, lineno):
- return 0, 0
-
-
-class RegexSync(SyntaxSync):
- """
- Synchronize by starting at a line that matches the given regex pattern.
- """
- # Never go more than this amount of lines backwards for synchronisation.
- # That would be too CPU intensive.
- MAX_BACKWARDS = 500
-
- # Start lexing at the start, if we are in the first 'n' lines and no
- # synchronisation position was found.
- FROM_START_IF_NO_SYNC_POS_FOUND = 100
-
- def __init__(self, pattern):
- assert isinstance(pattern, six.text_type)
- self._compiled_pattern = re.compile(pattern)
-
- def get_sync_start_position(self, document, lineno):
- " Scan backwards, and find a possible position to start. "
- pattern = self._compiled_pattern
- lines = document.lines
-
- # Scan upwards, until we find a point where we can start the syntax
- # synchronisation.
- for i in range(lineno, max(-1, lineno - self.MAX_BACKWARDS), -1):
- match = pattern.match(lines[i])
- if match:
- return i, match.start()
-
- # No synchronisation point found. If we aren't that far from the
- # beginning, start at the very beginning, otherwise, just try to start
- # at the current line.
- if lineno < self.FROM_START_IF_NO_SYNC_POS_FOUND:
- return 0, 0
- else:
- return lineno, 0
-
- @classmethod
- def from_pygments_lexer_cls(cls, lexer_cls):
- """
- Create a :class:`.RegexSync` instance for this Pygments lexer class.
- """
- patterns = {
- # For Python, start highlighting at any class/def block.
- 'Python': r'^\s*(class|def)\s+',
- 'Python 3': r'^\s*(class|def)\s+',
-
- # For HTML, start at any open/close tag definition.
- 'HTML': r'<[/a-zA-Z]',
-
- # For javascript, start at a function.
- 'JavaScript': r'\bfunction\b'
-
- # TODO: Add definitions for other languages.
- # By default, we start at every possible line.
- }
- p = patterns.get(lexer_cls.name, '^')
- return cls(p)
-
-
+ # Never go more than this amount of lines backwards for synchronisation.
+ # That would be too CPU intensive.
+ MAX_BACKWARDS = 500
+
+ # Start lexing at the start, if we are in the first 'n' lines and no
+ # synchronisation position was found.
+ FROM_START_IF_NO_SYNC_POS_FOUND = 100
+
+ def __init__(self, pattern):
+ assert isinstance(pattern, six.text_type)
+ self._compiled_pattern = re.compile(pattern)
+
+ def get_sync_start_position(self, document, lineno):
+ " Scan backwards, and find a possible position to start. "
+ pattern = self._compiled_pattern
+ lines = document.lines
+
+ # Scan upwards, until we find a point where we can start the syntax
+ # synchronisation.
+ for i in range(lineno, max(-1, lineno - self.MAX_BACKWARDS), -1):
+ match = pattern.match(lines[i])
+ if match:
+ return i, match.start()
+
+ # No synchronisation point found. If we aren't that far from the
+ # beginning, start at the very beginning, otherwise, just try to start
+ # at the current line.
+ if lineno < self.FROM_START_IF_NO_SYNC_POS_FOUND:
+ return 0, 0
+ else:
+ return lineno, 0
+
+ @classmethod
+ def from_pygments_lexer_cls(cls, lexer_cls):
+ """
+ Create a :class:`.RegexSync` instance for this Pygments lexer class.
+ """
+ patterns = {
+ # For Python, start highlighting at any class/def block.
+ 'Python': r'^\s*(class|def)\s+',
+ 'Python 3': r'^\s*(class|def)\s+',
+
+ # For HTML, start at any open/close tag definition.
+ 'HTML': r'<[/a-zA-Z]',
+
+ # For javascript, start at a function.
+ 'JavaScript': r'\bfunction\b'
+
+ # TODO: Add definitions for other languages.
+ # By default, we start at every possible line.
+ }
+ p = patterns.get(lexer_cls.name, '^')
+ return cls(p)
+
+
class PygmentsLexer(Lexer):
"""
Lexer that calls a pygments lexer.
-
+
Example::
from pygments.lexers import HtmlLexer
@@ -161,32 +161,32 @@ class PygmentsLexer(Lexer):
from pygments.styles import get_style_by_name
style = style_from_pygments(get_style_by_name('monokai'))
- :param pygments_lexer_cls: A `Lexer` from Pygments.
- :param sync_from_start: Start lexing at the start of the document. This
- will always give the best results, but it will be slow for bigger
- documents. (When the last part of the document is display, then the
- whole document will be lexed by Pygments on every key stroke.) It is
- recommended to disable this for inputs that are expected to be more
- than 1,000 lines.
- :param syntax_sync: `SyntaxSync` object.
+ :param pygments_lexer_cls: A `Lexer` from Pygments.
+ :param sync_from_start: Start lexing at the start of the document. This
+ will always give the best results, but it will be slow for bigger
+ documents. (When the last part of the document is display, then the
+ whole document will be lexed by Pygments on every key stroke.) It is
+ recommended to disable this for inputs that are expected to be more
+ than 1,000 lines.
+ :param syntax_sync: `SyntaxSync` object.
"""
- # Minimum amount of lines to go backwards when starting the parser.
- # This is important when the lines are retrieved in reverse order, or when
- # scrolling upwards. (Due to the complexity of calculating the vertical
- # scroll offset in the `Window` class, lines are not always retrieved in
- # order.)
- MIN_LINES_BACKWARDS = 50
-
- # When a parser was started this amount of lines back, read the parser
- # until we get the current line. Otherwise, start a new parser.
- # (This should probably be bigger than MIN_LINES_BACKWARDS.)
- REUSE_GENERATOR_MAX_DISTANCE = 100
-
- def __init__(self, pygments_lexer_cls, sync_from_start=True, syntax_sync=None):
- assert syntax_sync is None or isinstance(syntax_sync, SyntaxSync)
-
+ # Minimum amount of lines to go backwards when starting the parser.
+ # This is important when the lines are retrieved in reverse order, or when
+ # scrolling upwards. (Due to the complexity of calculating the vertical
+ # scroll offset in the `Window` class, lines are not always retrieved in
+ # order.)
+ MIN_LINES_BACKWARDS = 50
+
+ # When a parser was started this amount of lines back, read the parser
+ # until we get the current line. Otherwise, start a new parser.
+ # (This should probably be bigger than MIN_LINES_BACKWARDS.)
+ REUSE_GENERATOR_MAX_DISTANCE = 100
+
+ def __init__(self, pygments_lexer_cls, sync_from_start=True, syntax_sync=None):
+ assert syntax_sync is None or isinstance(syntax_sync, SyntaxSync)
+
self.pygments_lexer_cls = pygments_lexer_cls
- self.sync_from_start = to_cli_filter(sync_from_start)
+ self.sync_from_start = to_cli_filter(sync_from_start)
# Instantiate the Pygments lexer.
self.pygments_lexer = pygments_lexer_cls(
@@ -194,127 +194,127 @@ class PygmentsLexer(Lexer):
stripall=False,
ensurenl=False)
- # Create syntax sync instance.
- self.syntax_sync = syntax_sync or RegexSync.from_pygments_lexer_cls(pygments_lexer_cls)
-
- @classmethod
- def from_filename(cls, filename, sync_from_start=True):
- """
- Create a `Lexer` from a filename.
- """
- # Inline imports: the Pygments dependency is optional!
- from pygments.util import ClassNotFound
- from pygments.lexers import get_lexer_for_filename
-
- try:
- pygments_lexer = get_lexer_for_filename(filename)
- except ClassNotFound:
- return SimpleLexer()
- else:
- return cls(pygments_lexer.__class__, sync_from_start=sync_from_start)
-
- def lex_document(self, cli, document):
- """
- Create a lexer function that takes a line number and returns the list
- of (Token, text) tuples as the Pygments lexer returns for that line.
- """
- # Cache of already lexed lines.
- cache = {}
-
- # Pygments generators that are currently lexing.
- line_generators = {} # Map lexer generator to the line number.
-
- def get_syntax_sync():
- " The Syntax synchronisation objcet that we currently use. "
- if self.sync_from_start(cli):
- return SyncFromStart()
- else:
- return self.syntax_sync
-
- def find_closest_generator(i):
- " Return a generator close to line 'i', or None if none was fonud. "
- for generator, lineno in line_generators.items():
- if lineno < i and i - lineno < self.REUSE_GENERATOR_MAX_DISTANCE:
- return generator
-
- def create_line_generator(start_lineno, column=0):
- """
- Create a generator that yields the lexed lines.
- Each iteration it yields a (line_number, [(token, text), ...]) tuple.
- """
- def get_tokens():
- text = '\n'.join(document.lines[start_lineno:])[column:]
-
- # We call `get_tokens_unprocessed`, because `get_tokens` will
- # still replace \r\n and \r by \n. (We don't want that,
- # Pygments should return exactly the same amount of text, as we
- # have given as input.)
- for _, t, v in self.pygments_lexer.get_tokens_unprocessed(text):
- yield t, v
-
- return enumerate(split_lines(get_tokens()), start_lineno)
-
- def get_generator(i):
- """
- Find an already started generator that is close, or create a new one.
- """
- # Find closest line generator.
- generator = find_closest_generator(i)
- if generator:
- return generator
-
- # No generator found. Determine starting point for the syntax
- # synchronisation first.
-
- # Go at least x lines back. (Make scrolling upwards more
- # efficient.)
- i = max(0, i - self.MIN_LINES_BACKWARDS)
-
- if i == 0:
- row = 0
- column = 0
- else:
- row, column = get_syntax_sync().get_sync_start_position(document, i)
-
- # Find generator close to this point, or otherwise create a new one.
- generator = find_closest_generator(i)
- if generator:
- return generator
- else:
- generator = create_line_generator(row, column)
-
- # If the column is not 0, ignore the first line. (Which is
- # incomplete. This happens when the synchronisation algorithm tells
- # us to start parsing in the middle of a line.)
- if column:
- next(generator)
- row += 1
-
- line_generators[generator] = row
- return generator
-
- def get_line(i):
- " Return the tokens for a given line number. "
- try:
- return cache[i]
- except KeyError:
- generator = get_generator(i)
-
- # Exhaust the generator, until we find the requested line.
- for num, line in generator:
- cache[num] = line
- if num == i:
- line_generators[generator] = i
-
- # Remove the next item from the cache.
- # (It could happen that it's already there, because of
- # another generator that started filling these lines,
- # but we want to synchronise these lines with the
- # current lexer's state.)
- if num + 1 in cache:
- del cache[num + 1]
-
- return cache[num]
- return []
-
- return get_line
+ # Create syntax sync instance.
+ self.syntax_sync = syntax_sync or RegexSync.from_pygments_lexer_cls(pygments_lexer_cls)
+
+ @classmethod
+ def from_filename(cls, filename, sync_from_start=True):
+ """
+ Create a `Lexer` from a filename.
+ """
+ # Inline imports: the Pygments dependency is optional!
+ from pygments.util import ClassNotFound
+ from pygments.lexers import get_lexer_for_filename
+
+ try:
+ pygments_lexer = get_lexer_for_filename(filename)
+ except ClassNotFound:
+ return SimpleLexer()
+ else:
+ return cls(pygments_lexer.__class__, sync_from_start=sync_from_start)
+
+ def lex_document(self, cli, document):
+ """
+ Create a lexer function that takes a line number and returns the list
+ of (Token, text) tuples as the Pygments lexer returns for that line.
+ """
+ # Cache of already lexed lines.
+ cache = {}
+
+ # Pygments generators that are currently lexing.
+ line_generators = {} # Map lexer generator to the line number.
+
+ def get_syntax_sync():
+ " The Syntax synchronisation objcet that we currently use. "
+ if self.sync_from_start(cli):
+ return SyncFromStart()
+ else:
+ return self.syntax_sync
+
+ def find_closest_generator(i):
+ " Return a generator close to line 'i', or None if none was fonud. "
+ for generator, lineno in line_generators.items():
+ if lineno < i and i - lineno < self.REUSE_GENERATOR_MAX_DISTANCE:
+ return generator
+
+ def create_line_generator(start_lineno, column=0):
+ """
+ Create a generator that yields the lexed lines.
+ Each iteration it yields a (line_number, [(token, text), ...]) tuple.
+ """
+ def get_tokens():
+ text = '\n'.join(document.lines[start_lineno:])[column:]
+
+ # We call `get_tokens_unprocessed`, because `get_tokens` will
+ # still replace \r\n and \r by \n. (We don't want that,
+ # Pygments should return exactly the same amount of text, as we
+ # have given as input.)
+ for _, t, v in self.pygments_lexer.get_tokens_unprocessed(text):
+ yield t, v
+
+ return enumerate(split_lines(get_tokens()), start_lineno)
+
+ def get_generator(i):
+ """
+ Find an already started generator that is close, or create a new one.
+ """
+ # Find closest line generator.
+ generator = find_closest_generator(i)
+ if generator:
+ return generator
+
+ # No generator found. Determine starting point for the syntax
+ # synchronisation first.
+
+ # Go at least x lines back. (Make scrolling upwards more
+ # efficient.)
+ i = max(0, i - self.MIN_LINES_BACKWARDS)
+
+ if i == 0:
+ row = 0
+ column = 0
+ else:
+ row, column = get_syntax_sync().get_sync_start_position(document, i)
+
+ # Find generator close to this point, or otherwise create a new one.
+ generator = find_closest_generator(i)
+ if generator:
+ return generator
+ else:
+ generator = create_line_generator(row, column)
+
+ # If the column is not 0, ignore the first line. (Which is
+ # incomplete. This happens when the synchronisation algorithm tells
+ # us to start parsing in the middle of a line.)
+ if column:
+ next(generator)
+ row += 1
+
+ line_generators[generator] = row
+ return generator
+
+ def get_line(i):
+ " Return the tokens for a given line number. "
+ try:
+ return cache[i]
+ except KeyError:
+ generator = get_generator(i)
+
+ # Exhaust the generator, until we find the requested line.
+ for num, line in generator:
+ cache[num] = line
+ if num == i:
+ line_generators[generator] = i
+
+ # Remove the next item from the cache.
+ # (It could happen that it's already there, because of
+ # another generator that started filling these lines,
+ # but we want to synchronise these lines with the
+ # current lexer's state.)
+ if num + 1 in cache:
+ del cache[num + 1]
+
+ return cache[num]
+ return []
+
+ return get_line
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/margins.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/margins.py
index 1c596094d6..2934dfc9a7 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/margins.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/margins.py
@@ -3,21 +3,21 @@ Margin implementations for a :class:`~prompt_toolkit.layout.containers.Window`.
"""
from __future__ import unicode_literals
-from abc import ABCMeta, abstractmethod
+from abc import ABCMeta, abstractmethod
from six import with_metaclass
-from six.moves import range
+from six.moves import range
from prompt_toolkit.filters import to_cli_filter
-from prompt_toolkit.token import Token
-from prompt_toolkit.utils import get_cwidth
-from .utils import token_list_to_text
+from prompt_toolkit.token import Token
+from prompt_toolkit.utils import get_cwidth
+from .utils import token_list_to_text
__all__ = (
'Margin',
'NumberredMargin',
'ScrollbarMargin',
'ConditionalMargin',
- 'PromptMargin',
+ 'PromptMargin',
)
@@ -26,14 +26,14 @@ class Margin(with_metaclass(ABCMeta, object)):
Base interface for a margin.
"""
@abstractmethod
- def get_width(self, cli, get_ui_content):
+ def get_width(self, cli, get_ui_content):
"""
Return the width that this margin is going to consume.
-
- :param cli: :class:`.CommandLineInterface` instance.
- :param get_ui_content: Callable that asks the user control to create
- a :class:`.UIContent` instance. This can be used for instance to
- obtain the number of lines.
+
+ :param cli: :class:`.CommandLineInterface` instance.
+ :param get_ui_content: Callable that asks the user control to create
+ a :class:`.UIContent` instance. This can be used for instance to
+ obtain the number of lines.
"""
return 0
@@ -43,7 +43,7 @@ class Margin(with_metaclass(ABCMeta, object)):
Creates a margin.
This should return a list of (Token, text) tuples.
- :param cli: :class:`.CommandLineInterface` instance.
+ :param cli: :class:`.CommandLineInterface` instance.
:param window_render_info:
:class:`~prompt_toolkit.layout.containers.WindowRenderInfo`
instance, generated after rendering and copying the visible part of
@@ -63,16 +63,16 @@ class NumberredMargin(Margin):
:param relative: Number relative to the cursor position. Similar to the Vi
'relativenumber' option.
- :param display_tildes: Display tildes after the end of the document, just
- like Vi does.
+ :param display_tildes: Display tildes after the end of the document, just
+ like Vi does.
"""
- def __init__(self, relative=False, display_tildes=False):
+ def __init__(self, relative=False, display_tildes=False):
self.relative = to_cli_filter(relative)
- self.display_tildes = to_cli_filter(display_tildes)
+ self.display_tildes = to_cli_filter(display_tildes)
- def get_width(self, cli, get_ui_content):
- line_count = get_ui_content().line_count
- return max(3, len('%s' % line_count) + 1)
+ def get_width(self, cli, get_ui_content):
+ line_count = get_ui_content().line_count
+ return max(3, len('%s' % line_count) + 1)
def create_margin(self, cli, window_render_info, width, height):
relative = self.relative(cli)
@@ -81,40 +81,40 @@ class NumberredMargin(Margin):
token_current = Token.LineNumber.Current
# Get current line number.
- current_lineno = window_render_info.ui_content.cursor_position.y
+ current_lineno = window_render_info.ui_content.cursor_position.y
# Construct margin.
result = []
- last_lineno = None
-
- for y, lineno in enumerate(window_render_info.displayed_lines):
- # Only display line number if this line is not a continuation of the previous line.
- if lineno != last_lineno:
- if lineno is None:
- pass
- elif lineno == current_lineno:
+ last_lineno = None
+
+ for y, lineno in enumerate(window_render_info.displayed_lines):
+ # Only display line number if this line is not a continuation of the previous line.
+ if lineno != last_lineno:
+ if lineno is None:
+ pass
+ elif lineno == current_lineno:
# Current line.
if relative:
# Left align current number in relative mode.
- result.append((token_current, '%i' % (lineno + 1)))
+ result.append((token_current, '%i' % (lineno + 1)))
else:
- result.append((token_current, ('%i ' % (lineno + 1)).rjust(width)))
+ result.append((token_current, ('%i ' % (lineno + 1)).rjust(width)))
else:
# Other lines.
if relative:
- lineno = abs(lineno - current_lineno) - 1
+ lineno = abs(lineno - current_lineno) - 1
- result.append((token, ('%i ' % (lineno + 1)).rjust(width)))
+ result.append((token, ('%i ' % (lineno + 1)).rjust(width)))
- last_lineno = lineno
+ last_lineno = lineno
result.append((Token, '\n'))
- # Fill with tildes.
- if self.display_tildes(cli):
- while y < window_render_info.window_height:
- result.append((Token.Tilde, '~\n'))
- y += 1
-
+ # Fill with tildes.
+ if self.display_tildes(cli):
+ while y < window_render_info.window_height:
+ result.append((Token.Tilde, '~\n'))
+ y += 1
+
return result
@@ -128,9 +128,9 @@ class ConditionalMargin(Margin):
self.margin = margin
self.filter = to_cli_filter(filter)
- def get_width(self, cli, ui_content):
+ def get_width(self, cli, ui_content):
if self.filter(cli):
- return self.margin.get_width(cli, ui_content)
+ return self.margin.get_width(cli, ui_content)
else:
return 0
@@ -144,110 +144,110 @@ class ConditionalMargin(Margin):
class ScrollbarMargin(Margin):
"""
Margin displaying a scrollbar.
-
- :param display_arrows: Display scroll up/down arrows.
+
+ :param display_arrows: Display scroll up/down arrows.
"""
- def __init__(self, display_arrows=False):
- self.display_arrows = to_cli_filter(display_arrows)
-
- def get_width(self, cli, ui_content):
+ def __init__(self, display_arrows=False):
+ self.display_arrows = to_cli_filter(display_arrows)
+
+ def get_width(self, cli, ui_content):
return 1
def create_margin(self, cli, window_render_info, width, height):
total_height = window_render_info.content_height
- display_arrows = self.display_arrows(cli)
-
- window_height = window_render_info.window_height
- if display_arrows:
- window_height -= 2
-
- try:
- items_per_row = float(total_height) / min(total_height, window_height)
- except ZeroDivisionError:
- return []
- else:
- def is_scroll_button(row):
- " True if we should display a button on this row. "
- current_row_middle = int((row + .5) * items_per_row)
- return current_row_middle in window_render_info.displayed_lines
-
- # Up arrow.
- result = []
- if display_arrows:
- result.extend([
- (Token.Scrollbar.Arrow, '^'),
- (Token.Scrollbar, '\n')
- ])
-
- # Scrollbar body.
- for i in range(window_height):
- if is_scroll_button(i):
- result.append((Token.Scrollbar.Button, ' '))
- else:
- result.append((Token.Scrollbar, ' '))
- result.append((Token, '\n'))
-
- # Down arrow
- if display_arrows:
- result.append((Token.Scrollbar.Arrow, 'v'))
-
- return result
-
-
-class PromptMargin(Margin):
- """
- Create margin that displays a prompt.
- This can display one prompt at the first line, and a continuation prompt
- (e.g, just dots) on all the following lines.
-
- :param get_prompt_tokens: Callable that takes a CommandLineInterface as
- input and returns a list of (Token, type) tuples to be shown as the
- prompt at the first line.
- :param get_continuation_tokens: Callable that takes a CommandLineInterface
- and a width as input and returns a list of (Token, type) tuples for the
- next lines of the input.
- :param show_numbers: (bool or :class:`~prompt_toolkit.filters.CLIFilter`)
- Display line numbers instead of the continuation prompt.
- """
- def __init__(self, get_prompt_tokens, get_continuation_tokens=None,
- show_numbers=False):
- assert callable(get_prompt_tokens)
- assert get_continuation_tokens is None or callable(get_continuation_tokens)
- show_numbers = to_cli_filter(show_numbers)
-
- self.get_prompt_tokens = get_prompt_tokens
- self.get_continuation_tokens = get_continuation_tokens
- self.show_numbers = show_numbers
-
- def get_width(self, cli, ui_content):
- " Width to report to the `Window`. "
- # Take the width from the first line.
- text = token_list_to_text(self.get_prompt_tokens(cli))
- return get_cwidth(text)
-
- def create_margin(self, cli, window_render_info, width, height):
- # First line.
- tokens = self.get_prompt_tokens(cli)[:]
-
- # Next lines. (Show line numbering when numbering is enabled.)
- if self.get_continuation_tokens:
+ display_arrows = self.display_arrows(cli)
+
+ window_height = window_render_info.window_height
+ if display_arrows:
+ window_height -= 2
+
+ try:
+ items_per_row = float(total_height) / min(total_height, window_height)
+ except ZeroDivisionError:
+ return []
+ else:
+ def is_scroll_button(row):
+ " True if we should display a button on this row. "
+ current_row_middle = int((row + .5) * items_per_row)
+ return current_row_middle in window_render_info.displayed_lines
+
+ # Up arrow.
+ result = []
+ if display_arrows:
+ result.extend([
+ (Token.Scrollbar.Arrow, '^'),
+ (Token.Scrollbar, '\n')
+ ])
+
+ # Scrollbar body.
+ for i in range(window_height):
+ if is_scroll_button(i):
+ result.append((Token.Scrollbar.Button, ' '))
+ else:
+ result.append((Token.Scrollbar, ' '))
+ result.append((Token, '\n'))
+
+ # Down arrow
+ if display_arrows:
+ result.append((Token.Scrollbar.Arrow, 'v'))
+
+ return result
+
+
+class PromptMargin(Margin):
+ """
+ Create margin that displays a prompt.
+ This can display one prompt at the first line, and a continuation prompt
+ (e.g, just dots) on all the following lines.
+
+ :param get_prompt_tokens: Callable that takes a CommandLineInterface as
+ input and returns a list of (Token, type) tuples to be shown as the
+ prompt at the first line.
+ :param get_continuation_tokens: Callable that takes a CommandLineInterface
+ and a width as input and returns a list of (Token, type) tuples for the
+ next lines of the input.
+ :param show_numbers: (bool or :class:`~prompt_toolkit.filters.CLIFilter`)
+ Display line numbers instead of the continuation prompt.
+ """
+ def __init__(self, get_prompt_tokens, get_continuation_tokens=None,
+ show_numbers=False):
+ assert callable(get_prompt_tokens)
+ assert get_continuation_tokens is None or callable(get_continuation_tokens)
+ show_numbers = to_cli_filter(show_numbers)
+
+ self.get_prompt_tokens = get_prompt_tokens
+ self.get_continuation_tokens = get_continuation_tokens
+ self.show_numbers = show_numbers
+
+ def get_width(self, cli, ui_content):
+ " Width to report to the `Window`. "
+ # Take the width from the first line.
+ text = token_list_to_text(self.get_prompt_tokens(cli))
+ return get_cwidth(text)
+
+ def create_margin(self, cli, window_render_info, width, height):
+ # First line.
+ tokens = self.get_prompt_tokens(cli)[:]
+
+ # Next lines. (Show line numbering when numbering is enabled.)
+ if self.get_continuation_tokens:
# Note: we turn this into a list, to make sure that we fail early
# in case `get_continuation_tokens` returns something else,
# like `None`.
tokens2 = list(self.get_continuation_tokens(cli, width))
- else:
- tokens2 = []
-
- show_numbers = self.show_numbers(cli)
- last_y = None
-
- for y in window_render_info.displayed_lines[1:]:
- tokens.append((Token, '\n'))
- if show_numbers:
- if y != last_y:
- tokens.append((Token.LineNumber, ('%i ' % (y + 1)).rjust(width)))
+ else:
+ tokens2 = []
+
+ show_numbers = self.show_numbers(cli)
+ last_y = None
+
+ for y in window_render_info.displayed_lines[1:]:
+ tokens.append((Token, '\n'))
+ if show_numbers:
+ if y != last_y:
+ tokens.append((Token.LineNumber, ('%i ' % (y + 1)).rjust(width)))
else:
- tokens.extend(tokens2)
- last_y = y
+ tokens.extend(tokens2)
+ last_y = y
- return tokens
+ return tokens
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/menus.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/menus.py
index 8883d0594e..a916846e45 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/menus.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/menus.py
@@ -1,16 +1,16 @@
from __future__ import unicode_literals
-from six.moves import zip_longest, range
-from prompt_toolkit.filters import HasCompletions, IsDone, Condition, to_cli_filter
-from prompt_toolkit.mouse_events import MouseEventType
-from prompt_toolkit.token import Token
+from six.moves import zip_longest, range
+from prompt_toolkit.filters import HasCompletions, IsDone, Condition, to_cli_filter
+from prompt_toolkit.mouse_events import MouseEventType
+from prompt_toolkit.token import Token
from prompt_toolkit.utils import get_cwidth
-from .containers import Window, HSplit, ConditionalContainer, ScrollOffsets
-from .controls import UIControl, UIContent
+from .containers import Window, HSplit, ConditionalContainer, ScrollOffsets
+from .controls import UIControl, UIContent
from .dimension import LayoutDimension
-from .margins import ScrollbarMargin
-from .screen import Point, Char
+from .margins import ScrollbarMargin
+from .screen import Point, Char
import math
@@ -29,12 +29,12 @@ class CompletionsMenuControl(UIControl):
is a very high number, the current completion will be shown in the
middle most of the time.
"""
- # Preferred minimum size of the menu control.
- # The CompletionsMenu class defines a width of 8, and there is a scrollbar
- # of 1.)
- MIN_WIDTH = 7
+ # Preferred minimum size of the menu control.
+ # The CompletionsMenu class defines a width of 8, and there is a scrollbar
+ # of 1.)
+ MIN_WIDTH = 7
- def __init__(self):
+ def __init__(self):
self.token = Token.Menu.Completions
def has_focus(self, cli):
@@ -46,20 +46,20 @@ class CompletionsMenuControl(UIControl):
menu_width = self._get_menu_width(500, complete_state)
menu_meta_width = self._get_menu_meta_width(500, complete_state)
- return menu_width + menu_meta_width
+ return menu_width + menu_meta_width
else:
return 0
- def preferred_height(self, cli, width, max_available_height, wrap_lines):
+ def preferred_height(self, cli, width, max_available_height, wrap_lines):
complete_state = cli.current_buffer.complete_state
if complete_state:
return len(complete_state.current_completions)
else:
return 0
- def create_content(self, cli, width, height):
+ def create_content(self, cli, width, height):
"""
- Create a UIContent object for this control.
+ Create a UIContent object for this control.
"""
complete_state = cli.current_buffer.complete_state
if complete_state:
@@ -67,25 +67,25 @@ class CompletionsMenuControl(UIControl):
index = complete_state.complete_index # Can be None!
# Calculate width of completions menu.
- menu_width = self._get_menu_width(width, complete_state)
- menu_meta_width = self._get_menu_meta_width(width - menu_width, complete_state)
+ menu_width = self._get_menu_width(width, complete_state)
+ menu_meta_width = self._get_menu_meta_width(width - menu_width, complete_state)
show_meta = self._show_meta(complete_state)
- def get_line(i):
- c = completions[i]
- is_current_completion = (i == index)
- result = self._get_menu_item_tokens(c, is_current_completion, menu_width)
+ def get_line(i):
+ c = completions[i]
+ is_current_completion = (i == index)
+ result = self._get_menu_item_tokens(c, is_current_completion, menu_width)
- if show_meta:
- result += self._get_menu_item_meta_tokens(c, is_current_completion, menu_meta_width)
- return result
+ if show_meta:
+ result += self._get_menu_item_meta_tokens(c, is_current_completion, menu_meta_width)
+ return result
- return UIContent(get_line=get_line,
- cursor_position=Point(x=0, y=index or 0),
- line_count=len(completions),
- default_char=Char(' ', self.token))
+ return UIContent(get_line=get_line,
+ cursor_position=Point(x=0, y=index or 0),
+ line_count=len(completions),
+ default_char=Char(' ', self.token))
- return UIContent()
+ return UIContent()
def _show_meta(self, complete_state):
"""
@@ -97,8 +97,8 @@ class CompletionsMenuControl(UIControl):
"""
Return the width of the main column.
"""
- return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display)
- for c in complete_state.current_completions) + 2))
+ return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display)
+ for c in complete_state.current_completions) + 2))
def _get_menu_meta_width(self, max_width, complete_state):
"""
@@ -136,16 +136,16 @@ class CompletionsMenuControl(UIControl):
"""
b = cli.current_buffer
- if mouse_event.event_type == MouseEventType.MOUSE_UP:
+ if mouse_event.event_type == MouseEventType.MOUSE_UP:
# Select completion.
- b.go_to_completion(mouse_event.position.y)
+ b.go_to_completion(mouse_event.position.y)
b.complete_state = None
- elif mouse_event.event_type == MouseEventType.SCROLL_DOWN:
+ elif mouse_event.event_type == MouseEventType.SCROLL_DOWN:
# Scroll up.
b.complete_next(count=3, disable_wrap_around=True)
- elif mouse_event.event_type == MouseEventType.SCROLL_UP:
+ elif mouse_event.event_type == MouseEventType.SCROLL_UP:
# Scroll down.
b.complete_previous(count=3, disable_wrap_around=True)
@@ -179,19 +179,19 @@ def _trim_text(text, max_width):
class CompletionsMenu(ConditionalContainer):
- def __init__(self, max_height=None, scroll_offset=0, extra_filter=True, display_arrows=False):
- extra_filter = to_cli_filter(extra_filter)
- display_arrows = to_cli_filter(display_arrows)
-
+ def __init__(self, max_height=None, scroll_offset=0, extra_filter=True, display_arrows=False):
+ extra_filter = to_cli_filter(extra_filter)
+ display_arrows = to_cli_filter(display_arrows)
+
super(CompletionsMenu, self).__init__(
content=Window(
- content=CompletionsMenuControl(),
+ content=CompletionsMenuControl(),
width=LayoutDimension(min=8),
- height=LayoutDimension(min=1, max=max_height),
- scroll_offsets=ScrollOffsets(top=scroll_offset, bottom=scroll_offset),
- right_margins=[ScrollbarMargin(display_arrows=display_arrows)],
- dont_extend_width=True,
- ),
+ height=LayoutDimension(min=1, max=max_height),
+ scroll_offsets=ScrollOffsets(top=scroll_offset, bottom=scroll_offset),
+ right_margins=[ScrollbarMargin(display_arrows=display_arrows)],
+ dont_extend_width=True,
+ ),
# Show when there are completions but not at the point we are
# returning the input.
filter=HasCompletions() & ~IsDone() & extra_filter)
@@ -260,7 +260,7 @@ class MultiColumnCompletionMenuControl(UIControl):
result -= column_width
return result + self._required_margin
- def preferred_height(self, cli, width, max_available_height, wrap_lines):
+ def preferred_height(self, cli, width, max_available_height, wrap_lines):
"""
Preferred height: as much as needed in order to display all the completions.
"""
@@ -270,9 +270,9 @@ class MultiColumnCompletionMenuControl(UIControl):
return int(math.ceil(len(complete_state.current_completions) / float(column_count)))
- def create_content(self, cli, width, height):
+ def create_content(self, cli, width, height):
"""
- Create a UIContent object for this menu.
+ Create a UIContent object for this menu.
"""
complete_state = cli.current_buffer.complete_state
column_width = self._get_column_width(complete_state)
@@ -316,15 +316,15 @@ class MultiColumnCompletionMenuControl(UIControl):
render_right_arrow = self.scroll < len(rows_[0]) - visible_columns
# Write completions to screen.
- tokens_for_line = []
+ tokens_for_line = []
for row_index, row in enumerate(rows_):
- tokens = []
+ tokens = []
middle_row = row_index == len(rows_) // 2
# Draw left arrow if we have hidden completions on the left.
if render_left_arrow:
- tokens += [(Token.Scrollbar, '<' if middle_row else ' ')]
+ tokens += [(Token.Scrollbar, '<' if middle_row else ' ')]
# Draw row content.
for column_index, c in enumerate(row[self.scroll:][:visible_columns]):
@@ -342,13 +342,13 @@ class MultiColumnCompletionMenuControl(UIControl):
# Draw right arrow if we have hidden completions on the right.
if render_right_arrow:
- tokens += [(Token.Scrollbar, '>' if middle_row else ' ')]
+ tokens += [(Token.Scrollbar, '>' if middle_row else ' ')]
# Newline.
- tokens_for_line.append(tokens)
+ tokens_for_line.append(tokens)
- else:
- tokens = []
+ else:
+ tokens = []
self._rendered_rows = height
self._rendered_columns = visible_columns
@@ -357,11 +357,11 @@ class MultiColumnCompletionMenuControl(UIControl):
self._render_right_arrow = render_right_arrow
self._render_width = column_width * visible_columns + render_left_arrow + render_right_arrow + 1
- def get_line(i):
- return tokens_for_line[i]
+ def get_line(i):
+ return tokens_for_line[i]
+
+ return UIContent(get_line=get_line, line_count=len(rows_))
- return UIContent(get_line=get_line, line_count=len(rows_))
-
def _get_column_width(self, complete_state):
"""
Return the width of each column.
@@ -393,13 +393,13 @@ class MultiColumnCompletionMenuControl(UIControl):
b.complete_next(count=self._rendered_rows, disable_wrap_around=True)
self.scroll = min(self._total_columns - self._rendered_columns, self.scroll + 1)
- if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
+ if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
scroll_right()
- elif mouse_event.event_type == MouseEventType.SCROLL_UP:
+ elif mouse_event.event_type == MouseEventType.SCROLL_UP:
scroll_left()
- elif mouse_event.event_type == MouseEventType.MOUSE_UP:
+ elif mouse_event.event_type == MouseEventType.MOUSE_UP:
x = mouse_event.position.x
y = mouse_event.position.y
@@ -475,17 +475,17 @@ class _SelectedCompletionMetaControl(UIControl):
else:
return 0
- def preferred_height(self, cli, width, max_available_height, wrap_lines):
+ def preferred_height(self, cli, width, max_available_height, wrap_lines):
return 1
- def create_content(self, cli, width, height):
- tokens = self._get_tokens(cli)
+ def create_content(self, cli, width, height):
+ tokens = self._get_tokens(cli)
+
+ def get_line(i):
+ return tokens
+
+ return UIContent(get_line=get_line, line_count=1 if tokens else 0)
- def get_line(i):
- return tokens
-
- return UIContent(get_line=get_line, line_count=1 if tokens else 0)
-
def _get_tokens(self, cli):
token = Token.Menu.Completions.MultiColumnMeta
state = cli.current_buffer.complete_state
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py
index fc3e29a089..0b8bc9c223 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py
@@ -8,20 +8,20 @@ token types.
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from six import with_metaclass
-from six.moves import range
+from six.moves import range
-from prompt_toolkit.cache import SimpleCache
+from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.document import Document
from prompt_toolkit.enums import SEARCH_BUFFER
-from prompt_toolkit.filters import to_cli_filter, ViInsertMultipleMode
+from prompt_toolkit.filters import to_cli_filter, ViInsertMultipleMode
from prompt_toolkit.layout.utils import token_list_to_text
-from prompt_toolkit.reactive import Integer
-from prompt_toolkit.token import Token
+from prompt_toolkit.reactive import Integer
+from prompt_toolkit.token import Token
-from .utils import token_list_len, explode_tokens
+from .utils import token_list_len, explode_tokens
+
+import re
-import re
-
__all__ = (
'Processor',
'Transformation',
@@ -29,37 +29,37 @@ __all__ = (
'HighlightSearchProcessor',
'HighlightSelectionProcessor',
'PasswordProcessor',
- 'HighlightMatchingBracketProcessor',
- 'DisplayMultipleCursors',
+ 'HighlightMatchingBracketProcessor',
+ 'DisplayMultipleCursors',
'BeforeInput',
'AfterInput',
'AppendAutoSuggestion',
'ConditionalProcessor',
'ShowLeadingWhiteSpaceProcessor',
'ShowTrailingWhiteSpaceProcessor',
- 'TabsProcessor',
+ 'TabsProcessor',
)
class Processor(with_metaclass(ABCMeta, object)):
"""
- Manipulate the tokens for a given line in a
+ Manipulate the tokens for a given line in a
:class:`~prompt_toolkit.layout.controls.BufferControl`.
"""
@abstractmethod
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
"""
Apply transformation. Returns a :class:`.Transformation` instance.
-
- :param cli: :class:`.CommandLineInterface` instance.
- :param lineno: The number of the line to which we apply the processor.
- :param source_to_display: A function that returns the position in the
- `tokens` for any position in the source string. (This takes
- previous processors into account.)
- :param tokens: List of tokens that we can transform. (Received from the
- previous processor.)
+
+ :param cli: :class:`.CommandLineInterface` instance.
+ :param lineno: The number of the line to which we apply the processor.
+ :param source_to_display: A function that returns the position in the
+ `tokens` for any position in the source string. (This takes
+ previous processors into account.)
+ :param tokens: List of tokens that we can transform. (Received from the
+ previous processor.)
"""
- return Transformation(tokens)
+ return Transformation(tokens)
def has_focus(self, cli):
"""
@@ -83,26 +83,26 @@ class Transformation(object):
:param display_to_source: Cursor position transformed from source string to
original string.
"""
- def __init__(self, tokens, source_to_display=None, display_to_source=None):
+ def __init__(self, tokens, source_to_display=None, display_to_source=None):
self.tokens = tokens
self.source_to_display = source_to_display or (lambda i: i)
self.display_to_source = display_to_source or (lambda i: i)
-class HighlightSearchProcessor(Processor):
+class HighlightSearchProcessor(Processor):
"""
Processor that highlights search matches in the document.
- Note that this doesn't support multiline search matches yet.
+ Note that this doesn't support multiline search matches yet.
:param preview_search: A Filter; when active it indicates that we take
the search text in real time while the user is typing, instead of the
last active search state.
"""
- def __init__(self, preview_search=False, search_buffer_name=SEARCH_BUFFER,
- get_search_state=None):
+ def __init__(self, preview_search=False, search_buffer_name=SEARCH_BUFFER,
+ get_search_state=None):
self.preview_search = to_cli_filter(preview_search)
self.search_buffer_name = search_buffer_name
- self.get_search_state = get_search_state or (lambda cli: cli.search_state)
+ self.get_search_state = get_search_state or (lambda cli: cli.search_state)
def _get_search_text(self, cli):
"""
@@ -113,70 +113,70 @@ class HighlightSearchProcessor(Processor):
return cli.buffers[self.search_buffer_name].text
# Otherwise, take the text of the last active search.
else:
- return self.get_search_state(cli).text
+ return self.get_search_state(cli).text
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
search_text = self._get_search_text(cli)
- searchmatch_current_token = (':', ) + Token.SearchMatch.Current
- searchmatch_token = (':', ) + Token.SearchMatch
+ searchmatch_current_token = (':', ) + Token.SearchMatch.Current
+ searchmatch_token = (':', ) + Token.SearchMatch
if search_text and not cli.is_returning:
# For each search match, replace the Token.
- line_text = token_list_to_text(tokens)
- tokens = explode_tokens(tokens)
+ line_text = token_list_to_text(tokens)
+ tokens = explode_tokens(tokens)
- flags = re.IGNORECASE if cli.is_ignoring_case else 0
+ flags = re.IGNORECASE if cli.is_ignoring_case else 0
- # Get cursor column.
- if document.cursor_position_row == lineno:
- cursor_column = source_to_display(document.cursor_position_col)
- else:
- cursor_column = None
+ # Get cursor column.
+ if document.cursor_position_row == lineno:
+ cursor_column = source_to_display(document.cursor_position_col)
+ else:
+ cursor_column = None
- for match in re.finditer(re.escape(search_text), line_text, flags=flags):
- if cursor_column is not None:
- on_cursor = match.start() <= cursor_column < match.end()
- else:
- on_cursor = False
+ for match in re.finditer(re.escape(search_text), line_text, flags=flags):
+ if cursor_column is not None:
+ on_cursor = match.start() <= cursor_column < match.end()
+ else:
+ on_cursor = False
- for i in range(match.start(), match.end()):
- old_token, text = tokens[i]
- if on_cursor:
- tokens[i] = (old_token + searchmatch_current_token, tokens[i][1])
- else:
- tokens[i] = (old_token + searchmatch_token, tokens[i][1])
+ for i in range(match.start(), match.end()):
+ old_token, text = tokens[i]
+ if on_cursor:
+ tokens[i] = (old_token + searchmatch_current_token, tokens[i][1])
+ else:
+ tokens[i] = (old_token + searchmatch_token, tokens[i][1])
- return Transformation(tokens)
+ return Transformation(tokens)
-class HighlightSelectionProcessor(Processor):
+class HighlightSelectionProcessor(Processor):
"""
Processor that highlights the selection in the document.
"""
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- selected_token = (':', ) + Token.SelectedText
-
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ selected_token = (':', ) + Token.SelectedText
+
# In case of selection, highlight all matches.
- selection_at_line = document.selection_range_at_line(lineno)
+ selection_at_line = document.selection_range_at_line(lineno)
- if selection_at_line:
- from_, to = selection_at_line
- from_ = source_to_display(from_)
- to = source_to_display(to)
+ if selection_at_line:
+ from_, to = selection_at_line
+ from_ = source_to_display(from_)
+ to = source_to_display(to)
- tokens = explode_tokens(tokens)
+ tokens = explode_tokens(tokens)
- if from_ == 0 and to == 0 and len(tokens) == 0:
- # When this is an empty line, insert a space in order to
- # visualiase the selection.
- return Transformation([(Token.SelectedText, ' ')])
- else:
- for i in range(from_, to + 1):
- if i < len(tokens):
- old_token, old_text = tokens[i]
- tokens[i] = (old_token + selected_token, old_text)
+ if from_ == 0 and to == 0 and len(tokens) == 0:
+ # When this is an empty line, insert a space in order to
+ # visualiase the selection.
+ return Transformation([(Token.SelectedText, ' ')])
+ else:
+ for i in range(from_, to + 1):
+ if i < len(tokens):
+ old_token, old_text = tokens[i]
+ tokens[i] = (old_token + selected_token, old_text)
- return Transformation(tokens)
+ return Transformation(tokens)
class PasswordProcessor(Processor):
@@ -188,121 +188,121 @@ class PasswordProcessor(Processor):
def __init__(self, char='*'):
self.char = char
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- tokens = [(token, self.char * len(text)) for token, text in tokens]
- return Transformation(tokens)
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ tokens = [(token, self.char * len(text)) for token, text in tokens]
+ return Transformation(tokens)
-class HighlightMatchingBracketProcessor(Processor):
+class HighlightMatchingBracketProcessor(Processor):
"""
When the cursor is on or right after a bracket, it highlights the matching
bracket.
-
- :param max_cursor_distance: Only highlight matching brackets when the
- cursor is within this distance. (From inside a `Processor`, we can't
- know which lines will be visible on the screen. But we also don't want
- to scan the whole document for matching brackets on each key press, so
- we limit to this value.)
+
+ :param max_cursor_distance: Only highlight matching brackets when the
+ cursor is within this distance. (From inside a `Processor`, we can't
+ know which lines will be visible on the screen. But we also don't want
+ to scan the whole document for matching brackets on each key press, so
+ we limit to this value.)
"""
_closing_braces = '])}>'
- def __init__(self, chars='[](){}<>', max_cursor_distance=1000):
+ def __init__(self, chars='[](){}<>', max_cursor_distance=1000):
self.chars = chars
- self.max_cursor_distance = max_cursor_distance
-
- self._positions_cache = SimpleCache(maxsize=8)
-
- def _get_positions_to_highlight(self, document):
- """
- Return a list of (row, col) tuples that need to be highlighted.
- """
- # Try for the character under the cursor.
- if document.current_char and document.current_char in self.chars:
- pos = document.find_matching_bracket_position(
- start_pos=document.cursor_position - self.max_cursor_distance,
- end_pos=document.cursor_position + self.max_cursor_distance)
-
- # Try for the character before the cursor.
- elif (document.char_before_cursor and document.char_before_cursor in
- self._closing_braces and document.char_before_cursor in self.chars):
- document = Document(document.text, document.cursor_position - 1)
-
- pos = document.find_matching_bracket_position(
- start_pos=document.cursor_position - self.max_cursor_distance,
- end_pos=document.cursor_position + self.max_cursor_distance)
- else:
- pos = None
-
- # Return a list of (row, col) tuples that need to be highlighted.
- if pos:
- pos += document.cursor_position # pos is relative.
- row, col = document.translate_index_to_position(pos)
- return [(row, col), (document.cursor_position_row, document.cursor_position_col)]
- else:
- return []
-
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- # Get the highlight positions.
- key = (cli.render_counter, document.text, document.cursor_position)
- positions = self._positions_cache.get(
- key, lambda: self._get_positions_to_highlight(document))
-
- # Apply if positions were found at this line.
- if positions:
- for row, col in positions:
- if row == lineno:
- col = source_to_display(col)
- tokens = explode_tokens(tokens)
- token, text = tokens[col]
-
- if col == document.cursor_position_col:
- token += (':', ) + Token.MatchingBracket.Cursor
- else:
- token += (':', ) + Token.MatchingBracket.Other
-
- tokens[col] = (token, text)
-
- return Transformation(tokens)
-
-
-class DisplayMultipleCursors(Processor):
+ self.max_cursor_distance = max_cursor_distance
+
+ self._positions_cache = SimpleCache(maxsize=8)
+
+ def _get_positions_to_highlight(self, document):
+ """
+ Return a list of (row, col) tuples that need to be highlighted.
+ """
+ # Try for the character under the cursor.
+ if document.current_char and document.current_char in self.chars:
+ pos = document.find_matching_bracket_position(
+ start_pos=document.cursor_position - self.max_cursor_distance,
+ end_pos=document.cursor_position + self.max_cursor_distance)
+
+ # Try for the character before the cursor.
+ elif (document.char_before_cursor and document.char_before_cursor in
+ self._closing_braces and document.char_before_cursor in self.chars):
+ document = Document(document.text, document.cursor_position - 1)
+
+ pos = document.find_matching_bracket_position(
+ start_pos=document.cursor_position - self.max_cursor_distance,
+ end_pos=document.cursor_position + self.max_cursor_distance)
+ else:
+ pos = None
+
+ # Return a list of (row, col) tuples that need to be highlighted.
+ if pos:
+ pos += document.cursor_position # pos is relative.
+ row, col = document.translate_index_to_position(pos)
+ return [(row, col), (document.cursor_position_row, document.cursor_position_col)]
+ else:
+ return []
+
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ # Get the highlight positions.
+ key = (cli.render_counter, document.text, document.cursor_position)
+ positions = self._positions_cache.get(
+ key, lambda: self._get_positions_to_highlight(document))
+
+ # Apply if positions were found at this line.
+ if positions:
+ for row, col in positions:
+ if row == lineno:
+ col = source_to_display(col)
+ tokens = explode_tokens(tokens)
+ token, text = tokens[col]
+
+ if col == document.cursor_position_col:
+ token += (':', ) + Token.MatchingBracket.Cursor
+ else:
+ token += (':', ) + Token.MatchingBracket.Other
+
+ tokens[col] = (token, text)
+
+ return Transformation(tokens)
+
+
+class DisplayMultipleCursors(Processor):
"""
- When we're in Vi block insert mode, display all the cursors.
+ When we're in Vi block insert mode, display all the cursors.
"""
- _insert_multiple = ViInsertMultipleMode()
+ _insert_multiple = ViInsertMultipleMode()
- def __init__(self, buffer_name):
- self.buffer_name = buffer_name
+ def __init__(self, buffer_name):
+ self.buffer_name = buffer_name
+
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ buff = cli.buffers[self.buffer_name]
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- buff = cli.buffers[self.buffer_name]
+ if self._insert_multiple(cli):
+ positions = buff.multiple_cursor_positions
+ tokens = explode_tokens(tokens)
- if self._insert_multiple(cli):
- positions = buff.multiple_cursor_positions
- tokens = explode_tokens(tokens)
+ # If any cursor appears on the current line, highlight that.
+ start_pos = document.translate_row_col_to_index(lineno, 0)
+ end_pos = start_pos + len(document.lines[lineno])
- # If any cursor appears on the current line, highlight that.
- start_pos = document.translate_row_col_to_index(lineno, 0)
- end_pos = start_pos + len(document.lines[lineno])
+ token_suffix = (':', ) + Token.MultipleCursors.Cursor
- token_suffix = (':', ) + Token.MultipleCursors.Cursor
+ for p in positions:
+ if start_pos <= p < end_pos:
+ column = source_to_display(p - start_pos)
- for p in positions:
- if start_pos <= p < end_pos:
- column = source_to_display(p - start_pos)
+ # Replace token.
+ token, text = tokens[column]
+ token += token_suffix
+ tokens[column] = (token, text)
+ elif p == end_pos:
+ tokens.append((token_suffix, ' '))
+
+ return Transformation(tokens)
+ else:
+ return Transformation(tokens)
- # Replace token.
- token, text = tokens[column]
- token += token_suffix
- tokens[column] = (token, text)
- elif p == end_pos:
- tokens.append((token_suffix, ' '))
- return Transformation(tokens)
- else:
- return Transformation(tokens)
-
-
class BeforeInput(Processor):
"""
Insert tokens before the input.
@@ -315,21 +315,21 @@ class BeforeInput(Processor):
assert callable(get_tokens)
self.get_tokens = get_tokens
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- if lineno == 0:
- tokens_before = self.get_tokens(cli)
- tokens = tokens_before + tokens
-
- shift_position = token_list_len(tokens_before)
- source_to_display = lambda i: i + shift_position
- display_to_source = lambda i: i - shift_position
- else:
- source_to_display = None
- display_to_source = None
-
- return Transformation(tokens, source_to_display=source_to_display,
- display_to_source=display_to_source)
-
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ if lineno == 0:
+ tokens_before = self.get_tokens(cli)
+ tokens = tokens_before + tokens
+
+ shift_position = token_list_len(tokens_before)
+ source_to_display = lambda i: i + shift_position
+ display_to_source = lambda i: i - shift_position
+ else:
+ source_to_display = None
+ display_to_source = None
+
+ return Transformation(tokens, source_to_display=source_to_display,
+ display_to_source=display_to_source)
+
@classmethod
def static(cls, text, token=Token):
"""
@@ -357,12 +357,12 @@ class AfterInput(Processor):
assert callable(get_tokens)
self.get_tokens = get_tokens
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- # Insert tokens after the last line.
- if lineno == document.line_count - 1:
- return Transformation(tokens=tokens + self.get_tokens(cli))
- else:
- return Transformation(tokens=tokens)
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ # Insert tokens after the last line.
+ if lineno == document.line_count - 1:
+ return Transformation(tokens=tokens + self.get_tokens(cli))
+ else:
+ return Transformation(tokens=tokens)
@classmethod
def static(cls, text, token=Token):
@@ -397,171 +397,171 @@ class AppendAutoSuggestion(Processor):
else:
return cli.current_buffer
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- # Insert tokens after the last line.
- if lineno == document.line_count - 1:
- buffer = self._get_buffer(cli)
-
- if buffer.suggestion and buffer.document.is_cursor_at_the_end:
- suggestion = buffer.suggestion.text
- else:
- suggestion = ''
-
- return Transformation(tokens=tokens + [(self.token, suggestion)])
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ # Insert tokens after the last line.
+ if lineno == document.line_count - 1:
+ buffer = self._get_buffer(cli)
+
+ if buffer.suggestion and buffer.document.is_cursor_at_the_end:
+ suggestion = buffer.suggestion.text
+ else:
+ suggestion = ''
+
+ return Transformation(tokens=tokens + [(self.token, suggestion)])
else:
- return Transformation(tokens=tokens)
+ return Transformation(tokens=tokens)
class ShowLeadingWhiteSpaceProcessor(Processor):
"""
Make leading whitespace visible.
-
- :param get_char: Callable that takes a :class:`CommandLineInterface`
- instance and returns one character.
- :param token: Token to be used.
+
+ :param get_char: Callable that takes a :class:`CommandLineInterface`
+ instance and returns one character.
+ :param token: Token to be used.
"""
- def __init__(self, get_char=None, token=Token.LeadingWhiteSpace):
- assert get_char is None or callable(get_char)
-
- if get_char is None:
- def get_char(cli):
- if '\xb7'.encode(cli.output.encoding(), 'replace') == b'?':
- return '.'
- else:
- return '\xb7'
-
+ def __init__(self, get_char=None, token=Token.LeadingWhiteSpace):
+ assert get_char is None or callable(get_char)
+
+ if get_char is None:
+ def get_char(cli):
+ if '\xb7'.encode(cli.output.encoding(), 'replace') == b'?':
+ return '.'
+ else:
+ return '\xb7'
+
self.token = token
- self.get_char = get_char
+ self.get_char = get_char
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
# Walk through all te tokens.
- if tokens and token_list_to_text(tokens).startswith(' '):
- t = (self.token, self.get_char(cli))
- tokens = explode_tokens(tokens)
+ if tokens and token_list_to_text(tokens).startswith(' '):
+ t = (self.token, self.get_char(cli))
+ tokens = explode_tokens(tokens)
- for i in range(len(tokens)):
- if tokens[i][1] == ' ':
- tokens[i] = t
- else:
- break
+ for i in range(len(tokens)):
+ if tokens[i][1] == ' ':
+ tokens[i] = t
+ else:
+ break
- return Transformation(tokens)
+ return Transformation(tokens)
class ShowTrailingWhiteSpaceProcessor(Processor):
"""
Make trailing whitespace visible.
-
- :param get_char: Callable that takes a :class:`CommandLineInterface`
- instance and returns one character.
- :param token: Token to be used.
+
+ :param get_char: Callable that takes a :class:`CommandLineInterface`
+ instance and returns one character.
+ :param token: Token to be used.
+ """
+ def __init__(self, get_char=None, token=Token.TrailingWhiteSpace):
+ assert get_char is None or callable(get_char)
+
+ if get_char is None:
+ def get_char(cli):
+ if '\xb7'.encode(cli.output.encoding(), 'replace') == b'?':
+ return '.'
+ else:
+ return '\xb7'
+
+ self.token = token
+ self.get_char = get_char
+
+
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ if tokens and tokens[-1][1].endswith(' '):
+ t = (self.token, self.get_char(cli))
+ tokens = explode_tokens(tokens)
+
+ # Walk backwards through all te tokens and replace whitespace.
+ for i in range(len(tokens) - 1, -1, -1):
+ char = tokens[i][1]
+ if char == ' ':
+ tokens[i] = t
+ else:
+ break
+
+ return Transformation(tokens)
+
+
+class TabsProcessor(Processor):
"""
- def __init__(self, get_char=None, token=Token.TrailingWhiteSpace):
- assert get_char is None or callable(get_char)
-
- if get_char is None:
- def get_char(cli):
- if '\xb7'.encode(cli.output.encoding(), 'replace') == b'?':
- return '.'
- else:
- return '\xb7'
-
+ Render tabs as spaces (instead of ^I) or make them visible (for instance,
+ by replacing them with dots.)
+
+ :param tabstop: (Integer) Horizontal space taken by a tab.
+ :param get_char1: Callable that takes a `CommandLineInterface` and return a
+ character (text of length one). This one is used for the first space
+ taken by the tab.
+ :param get_char2: Like `get_char1`, but for the rest of the space.
+ """
+ def __init__(self, tabstop=4, get_char1=None, get_char2=None, token=Token.Tab):
+ assert isinstance(tabstop, Integer)
+ assert get_char1 is None or callable(get_char1)
+ assert get_char2 is None or callable(get_char2)
+
+ self.get_char1 = get_char1 or get_char2 or (lambda cli: '|')
+ self.get_char2 = get_char2 or get_char1 or (lambda cli: '\u2508')
+ self.tabstop = tabstop
self.token = token
- self.get_char = get_char
-
-
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- if tokens and tokens[-1][1].endswith(' '):
- t = (self.token, self.get_char(cli))
- tokens = explode_tokens(tokens)
-
- # Walk backwards through all te tokens and replace whitespace.
- for i in range(len(tokens) - 1, -1, -1):
- char = tokens[i][1]
- if char == ' ':
- tokens[i] = t
- else:
- break
-
- return Transformation(tokens)
-
-
-class TabsProcessor(Processor):
- """
- Render tabs as spaces (instead of ^I) or make them visible (for instance,
- by replacing them with dots.)
-
- :param tabstop: (Integer) Horizontal space taken by a tab.
- :param get_char1: Callable that takes a `CommandLineInterface` and return a
- character (text of length one). This one is used for the first space
- taken by the tab.
- :param get_char2: Like `get_char1`, but for the rest of the space.
- """
- def __init__(self, tabstop=4, get_char1=None, get_char2=None, token=Token.Tab):
- assert isinstance(tabstop, Integer)
- assert get_char1 is None or callable(get_char1)
- assert get_char2 is None or callable(get_char2)
-
- self.get_char1 = get_char1 or get_char2 or (lambda cli: '|')
- self.get_char2 = get_char2 or get_char1 or (lambda cli: '\u2508')
- self.tabstop = tabstop
- self.token = token
-
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
- tabstop = int(self.tabstop)
- token = self.token
-
- # Create separator for tabs.
- separator1 = self.get_char1(cli)
- separator2 = self.get_char2(cli)
-
- # Transform tokens.
- tokens = explode_tokens(tokens)
-
- position_mappings = {}
- result_tokens = []
- pos = 0
-
- for i, token_and_text in enumerate(tokens):
- position_mappings[i] = pos
-
- if token_and_text[1] == '\t':
- # Calculate how many characters we have to insert.
- count = tabstop - (pos % tabstop)
- if count == 0:
- count = tabstop
-
- # Insert tab.
- result_tokens.append((token, separator1))
- result_tokens.append((token, separator2 * (count - 1)))
- pos += count
+
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ tabstop = int(self.tabstop)
+ token = self.token
+
+ # Create separator for tabs.
+ separator1 = self.get_char1(cli)
+ separator2 = self.get_char2(cli)
+
+ # Transform tokens.
+ tokens = explode_tokens(tokens)
+
+ position_mappings = {}
+ result_tokens = []
+ pos = 0
+
+ for i, token_and_text in enumerate(tokens):
+ position_mappings[i] = pos
+
+ if token_and_text[1] == '\t':
+ # Calculate how many characters we have to insert.
+ count = tabstop - (pos % tabstop)
+ if count == 0:
+ count = tabstop
+
+ # Insert tab.
+ result_tokens.append((token, separator1))
+ result_tokens.append((token, separator2 * (count - 1)))
+ pos += count
else:
- result_tokens.append(token_and_text)
- pos += 1
-
- position_mappings[len(tokens)] = pos
-
- def source_to_display(from_position):
- " Maps original cursor position to the new one. "
- return position_mappings[from_position]
-
- def display_to_source(display_pos):
- " Maps display cursor position to the original one. "
- position_mappings_reversed = dict((v, k) for k, v in position_mappings.items())
-
- while display_pos >= 0:
- try:
- return position_mappings_reversed[display_pos]
- except KeyError:
- display_pos -= 1
- return 0
-
- return Transformation(
- result_tokens,
- source_to_display=source_to_display,
- display_to_source=display_to_source)
-
-
+ result_tokens.append(token_and_text)
+ pos += 1
+
+ position_mappings[len(tokens)] = pos
+
+ def source_to_display(from_position):
+ " Maps original cursor position to the new one. "
+ return position_mappings[from_position]
+
+ def display_to_source(display_pos):
+ " Maps display cursor position to the original one. "
+ position_mappings_reversed = dict((v, k) for k, v in position_mappings.items())
+
+ while display_pos >= 0:
+ try:
+ return position_mappings_reversed[display_pos]
+ except KeyError:
+ display_pos -= 1
+ return 0
+
+ return Transformation(
+ result_tokens,
+ source_to_display=source_to_display,
+ display_to_source=display_to_source)
+
+
class ConditionalProcessor(Processor):
"""
Processor that applies another processor, according to a certain condition.
@@ -586,13 +586,13 @@ class ConditionalProcessor(Processor):
self.processor = processor
self.filter = to_cli_filter(filter)
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
# Run processor when enabled.
if self.filter(cli):
- return self.processor.apply_transformation(
- cli, document, lineno, source_to_display, tokens)
+ return self.processor.apply_transformation(
+ cli, document, lineno, source_to_display, tokens)
else:
- return Transformation(tokens)
+ return Transformation(tokens)
def has_focus(self, cli):
if self.filter(cli):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/prompt.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/prompt.py
index 2a1373efbb..7d00ec513e 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/prompt.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/prompt.py
@@ -3,7 +3,7 @@ from __future__ import unicode_literals
from six import text_type
from prompt_toolkit.enums import IncrementalSearchDirection, SEARCH_BUFFER
-from prompt_toolkit.token import Token
+from prompt_toolkit.token import Token
from .utils import token_list_len
from .processors import Processor, Transformation
@@ -45,7 +45,7 @@ class DefaultPrompt(Processor):
return [(Token.Prompt, message)]
return cls(get_message_tokens)
- def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
+ def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
# Get text before cursor.
if cli.is_searching:
before = _get_isearch_tokens(cli)
@@ -59,11 +59,11 @@ class DefaultPrompt(Processor):
# Insert before buffer text.
shift_position = token_list_len(before)
- # Only show the prompt before the first line. For the following lines,
- # only indent using spaces.
- if lineno != 0:
- before = [(Token.Prompt, ' ' * shift_position)]
-
+ # Only show the prompt before the first line. For the following lines,
+ # only indent using spaces.
+ if lineno != 0:
+ before = [(Token.Prompt, ' ' * shift_position)]
+
return Transformation(
tokens=before + tokens,
source_to_display=lambda i: i + shift_position,
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/screen.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/screen.py
index 3e66f26500..95561f5de7 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/screen.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/screen.py
@@ -1,9 +1,9 @@
from __future__ import unicode_literals
-from prompt_toolkit.cache import FastDictCache
-from prompt_toolkit.token import Token
+from prompt_toolkit.cache import FastDictCache
+from prompt_toolkit.token import Token
from prompt_toolkit.utils import get_cwidth
-
+
from collections import defaultdict, namedtuple
__all__ = (
@@ -61,7 +61,7 @@ class Char(object):
'\x1c': '^\\',
'\x1d': '^]',
'\x1f': '^_',
- '\x7f': '^?', # Backspace
+ '\x7f': '^?', # Backspace
}
def __init__(self, char=' ', token=Token):
@@ -87,7 +87,7 @@ class Char(object):
return '%s(%r, %r)' % (self.__class__.__name__, self.char, self.token)
-_CHAR_CACHE = FastDictCache(Char, size=1000 * 1000)
+_CHAR_CACHE = FastDictCache(Char, size=1000 * 1000)
Transparent = Token.Transparent
@@ -97,13 +97,13 @@ class Screen(object):
"""
def __init__(self, default_char=None, initial_width=0, initial_height=0):
if default_char is None:
- default_char = _CHAR_CACHE[' ', Transparent]
+ default_char = _CHAR_CACHE[' ', Transparent]
self.data_buffer = defaultdict(lambda: defaultdict(lambda: default_char))
- #: Escape sequences to be injected.
- self.zero_width_escapes = defaultdict(lambda: defaultdict(lambda: ''))
-
+ #: Escape sequences to be injected.
+ self.zero_width_escapes = defaultdict(lambda: defaultdict(lambda: ''))
+
#: Position of the cursor.
self.cursor_position = Point(y=0, x=0)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/toolbars.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/toolbars.py
index 573e7db666..2e77c2fa16 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/toolbars.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/toolbars.py
@@ -4,15 +4,15 @@ from ..enums import IncrementalSearchDirection
from .processors import BeforeInput
-from .lexers import SimpleLexer
+from .lexers import SimpleLexer
from .dimension import LayoutDimension
-from .controls import BufferControl, TokenListControl, UIControl, UIContent
+from .controls import BufferControl, TokenListControl, UIControl, UIContent
from .containers import Window, ConditionalContainer
-from .screen import Char
+from .screen import Char
from .utils import token_list_len
-from prompt_toolkit.enums import SEARCH_BUFFER, SYSTEM_BUFFER
+from prompt_toolkit.enums import SEARCH_BUFFER, SYSTEM_BUFFER
from prompt_toolkit.filters import HasFocus, HasArg, HasCompletions, HasValidationError, HasSearch, Always, IsDone
-from prompt_toolkit.token import Token
+from prompt_toolkit.token import Token
__all__ = (
'TokenListToolbar',
@@ -35,13 +35,13 @@ class TokenListToolbar(ConditionalContainer):
class SystemToolbarControl(BufferControl):
def __init__(self):
- token = Token.Toolbar.System
-
+ token = Token.Toolbar.System
+
super(SystemToolbarControl, self).__init__(
buffer_name=SYSTEM_BUFFER,
- default_char=Char(token=token),
- lexer=SimpleLexer(token=token.Text),
- input_processors=[BeforeInput.static('Shell command: ', token)],)
+ default_char=Char(token=token),
+ lexer=SimpleLexer(token=token.Text),
+ input_processors=[BeforeInput.static('Shell command: ', token)],)
class SystemToolbar(ConditionalContainer):
@@ -56,13 +56,13 @@ class SystemToolbar(ConditionalContainer):
class ArgToolbarControl(TokenListControl):
def __init__(self):
def get_tokens(cli):
- arg = cli.input_processor.arg
- if arg == '-':
- arg = '-1'
-
+ arg = cli.input_processor.arg
+ if arg == '-':
+ arg = '-1'
+
return [
(Token.Toolbar.Arg, 'Repeat: '),
- (Token.Toolbar.Arg.Text, arg),
+ (Token.Toolbar.Arg.Text, arg),
]
super(ArgToolbarControl, self).__init__(get_tokens)
@@ -97,8 +97,8 @@ class SearchToolbarControl(BufferControl):
super(SearchToolbarControl, self).__init__(
buffer_name=SEARCH_BUFFER,
input_processors=[BeforeInput(get_before_input)],
- default_char=Char(token=token),
- lexer=SimpleLexer(token=token.Text))
+ default_char=Char(token=token),
+ lexer=SimpleLexer(token=token.Text))
class SearchToolbar(ConditionalContainer):
@@ -113,7 +113,7 @@ class SearchToolbar(ConditionalContainer):
class CompletionsToolbarControl(UIControl):
token = Token.Toolbar.Completions
- def create_content(self, cli, width, height):
+ def create_content(self, cli, width, height):
complete_state = cli.current_buffer.complete_state
if complete_state:
completions = complete_state.current_completions
@@ -161,12 +161,12 @@ class CompletionsToolbarControl(UIControl):
else:
all_tokens = []
- def get_line(i):
- return all_tokens
+ def get_line(i):
+ return all_tokens
+
+ return UIContent(get_line=get_line, line_count=1)
- return UIContent(get_line=get_line, line_count=1)
-
class CompletionsToolbar(ConditionalContainer):
def __init__(self, extra_filter=Always()):
super(CompletionsToolbar, self).__init__(
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py
index 3fa16de535..a4fb7ed0f5 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py
@@ -1,14 +1,14 @@
from __future__ import unicode_literals
from prompt_toolkit.utils import get_cwidth
-from prompt_toolkit.token import Token
+from prompt_toolkit.token import Token
__all__ = (
'token_list_len',
'token_list_width',
'token_list_to_text',
'explode_tokens',
- 'split_lines',
+ 'split_lines',
'find_window_for_buffer_name',
)
@@ -20,8 +20,8 @@ def token_list_len(tokenlist):
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples.
"""
- ZeroWidthEscape = Token.ZeroWidthEscape
- return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)
+ ZeroWidthEscape = Token.ZeroWidthEscape
+ return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)
def token_list_width(tokenlist):
@@ -32,16 +32,16 @@ def token_list_width(tokenlist):
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples.
"""
- ZeroWidthEscape = Token.ZeroWidthEscape
- return sum(get_cwidth(c) for item in tokenlist for c in item[1] if item[0] != ZeroWidthEscape)
+ ZeroWidthEscape = Token.ZeroWidthEscape
+ return sum(get_cwidth(c) for item in tokenlist for c in item[1] if item[0] != ZeroWidthEscape)
def token_list_to_text(tokenlist):
"""
Concatenate all the text parts again.
"""
- ZeroWidthEscape = Token.ZeroWidthEscape
- return ''.join(item[1] for item in tokenlist if item[0] != ZeroWidthEscape)
+ ZeroWidthEscape = Token.ZeroWidthEscape
+ return ''.join(item[1] for item in tokenlist if item[0] != ZeroWidthEscape)
def iter_token_lines(tokenlist):
@@ -62,7 +62,7 @@ def iter_token_lines(tokenlist):
def split_lines(tokenlist):
"""
Take a single list of (Token, text) tuples and yield one such list for each
- line. Just like str.split, this will yield at least one item.
+ line. Just like str.split, this will yield at least one item.
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples.
@@ -82,8 +82,8 @@ def split_lines(tokenlist):
line = []
line.append((token, parts[-1]))
- # Note that parts[-1] can be empty, and that's fine. It happens
- # in the case of [(Token.SetCursorPosition, '')].
+ # Note that parts[-1] can be empty, and that's fine. It happens
+ # in the case of [(Token.SetCursorPosition, '')].
# For (token, text, mouse_handler) tuples.
# I know, partly copy/paste, but understandable and more efficient
@@ -100,67 +100,67 @@ def split_lines(tokenlist):
line.append((token, parts[-1], mouse_handler))
- # Always yield the last line, even when this is an empty line. This ensures
- # that when `tokenlist` ends with a newline character, an additional empty
- # line is yielded. (Otherwise, there's no way to differentiate between the
- # cases where `tokenlist` does and doesn't end with a newline.)
- yield line
-
-
-class _ExplodedList(list):
- """
- Wrapper around a list, that marks it as 'exploded'.
-
- As soon as items are added or the list is extended, the new items are
- automatically exploded as well.
- """
- def __init__(self, *a, **kw):
- super(_ExplodedList, self).__init__(*a, **kw)
- self.exploded = True
-
- def append(self, item):
- self.extend([item])
-
- def extend(self, lst):
- super(_ExplodedList, self).extend(explode_tokens(lst))
-
- def insert(self, index, item):
- raise NotImplementedError # TODO
-
- # TODO: When creating a copy() or [:], return also an _ExplodedList.
-
- def __setitem__(self, index, value):
- """
- Ensure that when `(Token, 'long string')` is set, the string will be
- exploded.
- """
- if not isinstance(index, slice):
- index = slice(index, index + 1)
- value = explode_tokens([value])
- super(_ExplodedList, self).__setitem__(index, value)
-
-
+ # Always yield the last line, even when this is an empty line. This ensures
+ # that when `tokenlist` ends with a newline character, an additional empty
+ # line is yielded. (Otherwise, there's no way to differentiate between the
+ # cases where `tokenlist` does and doesn't end with a newline.)
+ yield line
+
+
+class _ExplodedList(list):
+ """
+ Wrapper around a list, that marks it as 'exploded'.
+
+ As soon as items are added or the list is extended, the new items are
+ automatically exploded as well.
+ """
+ def __init__(self, *a, **kw):
+ super(_ExplodedList, self).__init__(*a, **kw)
+ self.exploded = True
+
+ def append(self, item):
+ self.extend([item])
+
+ def extend(self, lst):
+ super(_ExplodedList, self).extend(explode_tokens(lst))
+
+ def insert(self, index, item):
+ raise NotImplementedError # TODO
+
+ # TODO: When creating a copy() or [:], return also an _ExplodedList.
+
+ def __setitem__(self, index, value):
+ """
+ Ensure that when `(Token, 'long string')` is set, the string will be
+ exploded.
+ """
+ if not isinstance(index, slice):
+ index = slice(index, index + 1)
+ value = explode_tokens([value])
+ super(_ExplodedList, self).__setitem__(index, value)
+
+
def explode_tokens(tokenlist):
"""
Turn a list of (token, text) tuples into another list where each string is
exactly one character.
- It should be fine to call this function several times. Calling this on a
- list that is already exploded, is a null operation.
-
+ It should be fine to call this function several times. Calling this on a
+ list that is already exploded, is a null operation.
+
:param tokenlist: List of (token, text) tuples.
"""
- # When the tokenlist is already exploded, don't explode again.
- if getattr(tokenlist, 'exploded', False):
- return tokenlist
-
+ # When the tokenlist is already exploded, don't explode again.
+ if getattr(tokenlist, 'exploded', False):
+ return tokenlist
+
result = []
for token, string in tokenlist:
for c in string:
result.append((token, c))
- return _ExplodedList(result)
+ return _ExplodedList(result)
def find_window_for_buffer_name(cli, buffer_name):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/mouse_events.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/mouse_events.py
index 4537ba8035..f42276ce9f 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/mouse_events.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/mouse_events.py
@@ -18,21 +18,21 @@ coordinates to coordinates relative to the user control, and there
from __future__ import unicode_literals
__all__ = (
- 'MouseEventType',
+ 'MouseEventType',
'MouseEvent'
)
-class MouseEventType:
+class MouseEventType:
MOUSE_UP = 'MOUSE_UP'
MOUSE_DOWN = 'MOUSE_DOWN'
SCROLL_UP = 'SCROLL_UP'
SCROLL_DOWN = 'SCROLL_DOWN'
-MouseEventTypes = MouseEventType # Deprecated: plural for backwards compatibility.
-
-
+MouseEventTypes = MouseEventType # Deprecated: plural for backwards compatibility.
+
+
class MouseEvent(object):
"""
Mouse event, sent to `UIControl.mouse_handler`.
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py
index b863abc908..072fb0677f 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py
@@ -4,7 +4,7 @@ Interface for an output.
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from six import with_metaclass
-from prompt_toolkit.layout.screen import Size
+from prompt_toolkit.layout.screen import Size
__all__ = (
'Output',
@@ -21,19 +21,19 @@ class Output(with_metaclass(ABCMeta, object)):
:class:`~prompt_toolkit.terminal.win32_output.Win32Output`.
"""
@abstractmethod
- def fileno(self):
- " Return the file descriptor to which we can write for the output. "
-
- @abstractmethod
- def encoding(self):
- """
- Return the encoding for this output, e.g. 'utf-8'.
- (This is used mainly to know which characters are supported by the
- output the data, so that the UI can provide alternatives, when
- required.)
- """
-
- @abstractmethod
+ def fileno(self):
+ " Return the file descriptor to which we can write for the output. "
+
+ @abstractmethod
+ def encoding(self):
+ """
+ Return the encoding for this output, e.g. 'utf-8'.
+ (This is used mainly to know which characters are supported by the
+ output the data, so that the UI can provide alternatives, when
+ required.)
+ """
+
+ @abstractmethod
def write(self, data):
" Write text (Terminal escape sequences will be removed/escaped.) "
@@ -147,46 +147,46 @@ class Output(with_metaclass(ABCMeta, object)):
def disable_bracketed_paste(self):
" For vt100 only. "
-
-
-class DummyOutput(Output):
- """
- For testing. An output class that doesn't render anything.
- """
- def fileno(self):
- " There is no sensible default for fileno(). "
- raise NotImplementedError
-
- def encoding(self):
- return 'utf-8'
-
- def write(self, data): pass
- def write_raw(self, data): pass
- def set_title(self, title): pass
- def clear_title(self): pass
- def flush(self): pass
- def erase_screen(self): pass
- def enter_alternate_screen(self): pass
- def quit_alternate_screen(self): pass
- def enable_mouse_support(self): pass
- def disable_mouse_support(self): pass
- def erase_end_of_line(self): pass
- def erase_down(self): pass
- def reset_attributes(self): pass
- def set_attributes(self, attrs): pass
- def disable_autowrap(self): pass
- def enable_autowrap(self): pass
- def cursor_goto(self, row=0, column=0): pass
- def cursor_up(self, amount): pass
- def cursor_down(self, amount): pass
- def cursor_forward(self, amount): pass
- def cursor_backward(self, amount): pass
- def hide_cursor(self): pass
- def show_cursor(self): pass
- def ask_for_cpr(self): pass
- def bell(self): pass
- def enable_bracketed_paste(self): pass
- def disable_bracketed_paste(self): pass
-
- def get_size(self):
- return Size(rows=40, columns=80)
+
+
+class DummyOutput(Output):
+ """
+ For testing. An output class that doesn't render anything.
+ """
+ def fileno(self):
+ " There is no sensible default for fileno(). "
+ raise NotImplementedError
+
+ def encoding(self):
+ return 'utf-8'
+
+ def write(self, data): pass
+ def write_raw(self, data): pass
+ def set_title(self, title): pass
+ def clear_title(self): pass
+ def flush(self): pass
+ def erase_screen(self): pass
+ def enter_alternate_screen(self): pass
+ def quit_alternate_screen(self): pass
+ def enable_mouse_support(self): pass
+ def disable_mouse_support(self): pass
+ def erase_end_of_line(self): pass
+ def erase_down(self): pass
+ def reset_attributes(self): pass
+ def set_attributes(self, attrs): pass
+ def disable_autowrap(self): pass
+ def enable_autowrap(self): pass
+ def cursor_goto(self, row=0, column=0): pass
+ def cursor_up(self, amount): pass
+ def cursor_down(self, amount): pass
+ def cursor_forward(self, amount): pass
+ def cursor_backward(self, amount): pass
+ def hide_cursor(self): pass
+ def show_cursor(self): pass
+ def ask_for_cpr(self): pass
+ def bell(self): pass
+ def enable_bracketed_paste(self): pass
+ def disable_bracketed_paste(self): pass
+
+ def get_size(self):
+ return Size(rows=40, columns=80)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/renderer.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/renderer.py
index c0fee22e10..7a8fde55b3 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/renderer.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/renderer.py
@@ -4,23 +4,23 @@ Renders the command line on the console.
"""
from __future__ import unicode_literals
-from prompt_toolkit.filters import to_cli_filter
-from prompt_toolkit.layout.mouse_handlers import MouseHandlers
+from prompt_toolkit.filters import to_cli_filter
+from prompt_toolkit.layout.mouse_handlers import MouseHandlers
from prompt_toolkit.layout.screen import Point, Screen, WritePosition
from prompt_toolkit.output import Output
-from prompt_toolkit.styles import Style
-from prompt_toolkit.token import Token
+from prompt_toolkit.styles import Style
+from prompt_toolkit.token import Token
from prompt_toolkit.utils import is_windows
-from six.moves import range
-
+from six.moves import range
+
__all__ = (
'Renderer',
'print_tokens',
)
-def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_token=None,
+def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_token=None,
is_done=False, use_alternate_screen=False, attrs_for_token=None, size=None,
previous_width=0): # XXX: drop is_done
"""
@@ -36,7 +36,7 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
Don't change things without profiling first.
:param current_pos: Current cursor position.
- :param last_token: `Token` instance that represents the output attributes of
+ :param last_token: `Token` instance that represents the output attributes of
the last drawn character. (Color/attributes.)
:param attrs_for_token: :class:`._TokenToAttrsCache` instance.
:param width: The width of the terminal.
@@ -45,11 +45,11 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
width, height = size.columns, size.rows
#: Remember the last printed character.
- last_token = [last_token] # nonlocal
+ last_token = [last_token] # nonlocal
#: Variable for capturing the output.
write = output.write
- write_raw = output.write_raw
+ write_raw = output.write_raw
# Create locals for the most used output methods.
# (Save expensive attribute lookups.)
@@ -65,7 +65,7 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
def reset_attributes():
" Wrapper around Output.reset_attributes. "
_output_reset_attributes()
- last_token[0] = None # Forget last char after resetting attributes.
+ last_token[0] = None # Forget last char after resetting attributes.
def move_cursor(new):
" Move cursor to this `new` point. Returns the given Point. "
@@ -100,14 +100,14 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
"""
# If the last printed character has the same token, it also has the
# same style, so we don't output it.
- the_last_token = last_token[0]
-
- if the_last_token and the_last_token == char.token:
+ the_last_token = last_token[0]
+
+ if the_last_token and the_last_token == char.token:
write(char.char)
else:
- _output_set_attributes(attrs_for_token[char.token])
+ _output_set_attributes(attrs_for_token[char.token])
write(char.char)
- last_token[0] = char.token
+ last_token[0] = char.token
# Render for the first time: reset styling.
if not previous_screen:
@@ -138,10 +138,10 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
row_count = min(max(screen.height, previous_screen.height), height)
c = 0 # Column counter.
- for y in range(row_count):
- new_row = screen.data_buffer[y]
- previous_row = previous_screen.data_buffer[y]
- zero_width_escapes_row = screen.zero_width_escapes[y]
+ for y in range(row_count):
+ new_row = screen.data_buffer[y]
+ previous_row = previous_screen.data_buffer[y]
+ zero_width_escapes_row = screen.zero_width_escapes[y]
new_max_line_len = min(width - 1, max(new_row.keys()) if new_row else 0)
previous_max_line_len = min(width - 1, max(previous_row.keys()) if previous_row else 0)
@@ -158,11 +158,11 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
# `Char.__ne__`, but inline the same expression.)
if new_char.char != old_char.char or new_char.token != old_char.token:
current_pos = move_cursor(Point(y=y, x=c))
-
- # Send injected escape sequences to output.
- if c in zero_width_escapes_row:
- write_raw(zero_width_escapes_row[c])
-
+
+ # Send injected escape sequences to output.
+ if c in zero_width_escapes_row:
+ write_raw(zero_width_escapes_row[c])
+
output_char(new_char)
current_pos = current_pos._replace(x=current_pos.x + char_width)
@@ -197,16 +197,16 @@ def _output_screen_diff(output, screen, current_pos, previous_screen=None, last_
if is_done or not use_alternate_screen:
output.enable_autowrap()
- # Always reset the color attributes. This is important because a background
- # thread could print data to stdout and we want that to be displayed in the
- # default colors. (Also, if a background color has been set, many terminals
- # give weird artifacs on resize events.)
- reset_attributes()
+ # Always reset the color attributes. This is important because a background
+ # thread could print data to stdout and we want that to be displayed in the
+ # default colors. (Also, if a background color has been set, many terminals
+ # give weird artifacs on resize events.)
+ reset_attributes()
if screen.show_cursor or is_done:
output.show_cursor()
- return current_pos, last_token[0]
+ return current_pos, last_token[0]
class HeightIsUnknownError(Exception):
@@ -254,13 +254,13 @@ class Renderer(object):
self._mouse_support_enabled = False
self._bracketed_paste_enabled = False
- # Waiting for CPR flag. True when we send the request, but didn't got a
- # response.
- self.waiting_for_cpr = False
-
+ # Waiting for CPR flag. True when we send the request, but didn't got a
+ # response.
+ self.waiting_for_cpr = False
+
self.reset(_scroll=True)
- def reset(self, _scroll=False, leave_alternate_screen=True):
+ def reset(self, _scroll=False, leave_alternate_screen=True):
# Reset position
self._cursor_pos = Point(x=0, y=0)
@@ -270,7 +270,7 @@ class Renderer(object):
# instance a toolbar at the bottom position.)
self._last_screen = None
self._last_size = None
- self._last_token = None
+ self._last_token = None
# When the style hash changes, we have to do a full redraw as well as
# clear the `_attrs_for_token` dictionary.
@@ -293,7 +293,7 @@ class Renderer(object):
self.output.scroll_buffer_to_prompt()
# Quit alternate screen.
- if self._in_alternate_screen and leave_alternate_screen:
+ if self._in_alternate_screen and leave_alternate_screen:
self.output.quit_alternate_screen()
self._in_alternate_screen = False
@@ -353,7 +353,7 @@ class Renderer(object):
self._min_available_height = self.output.get_size().rows
else:
# Asks for a cursor position report (CPR).
- self.waiting_for_cpr = True
+ self.waiting_for_cpr = True
self.output.ask_for_cpr()
def report_absolute_cursor_row(self, row):
@@ -369,8 +369,8 @@ class Renderer(object):
# Set the
self._min_available_height = rows_below_cursor
- self.waiting_for_cpr = False
-
+ self.waiting_for_cpr = False
+
def render(self, cli, layout, is_done=False):
"""
Render the current interface to the output.
@@ -441,9 +441,9 @@ class Renderer(object):
screen.replace_all_tokens(Token.Aborted)
# Process diff and write to output.
- self._cursor_pos, self._last_token = _output_screen_diff(
+ self._cursor_pos, self._last_token = _output_screen_diff(
output, screen, self._cursor_pos,
- self._last_screen, self._last_token, is_done,
+ self._last_screen, self._last_token, is_done,
use_alternate_screen=self.use_alternate_screen,
attrs_for_token=self._attrs_for_token,
size=size,
@@ -464,15 +464,15 @@ class Renderer(object):
output.flush()
- def erase(self, leave_alternate_screen=True, erase_title=True):
+ def erase(self, leave_alternate_screen=True, erase_title=True):
"""
Hide all output and put the cursor back at the first line. This is for
instance used for running a system command (while hiding the CLI) and
later resuming the same CLI.)
-
- :param leave_alternate_screen: When True, and when inside an alternate
- screen buffer, quit the alternate screen.
- :param erase_title: When True, clear the title from the title bar.
+
+ :param leave_alternate_screen: When True, and when inside an alternate
+ screen buffer, quit the alternate screen.
+ :param erase_title: When True, clear the title from the title bar.
"""
output = self.output
@@ -484,10 +484,10 @@ class Renderer(object):
output.flush()
# Erase title.
- if self._last_title and erase_title:
+ if self._last_title and erase_title:
output.clear_title()
- self.reset(leave_alternate_screen=leave_alternate_screen)
+ self.reset(leave_alternate_screen=leave_alternate_screen)
def clear(self):
"""
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/selection.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/selection.py
index 4490f15c0d..6582921222 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/selection.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/selection.py
@@ -15,13 +15,13 @@ class SelectionType(object):
Type of selection.
"""
#: Characters. (Visual in Vi.)
- CHARACTERS = 'CHARACTERS'
+ CHARACTERS = 'CHARACTERS'
#: Whole lines. (Visual-Line in Vi.)
- LINES = 'LINES'
+ LINES = 'LINES'
#: A block selection. (Visual-Block in Vi.)
- BLOCK = 'BLOCK'
+ BLOCK = 'BLOCK'
class PasteMode(object):
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py
index 2bb34177de..9893624c6e 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py
@@ -23,45 +23,45 @@ from __future__ import unicode_literals
from .buffer import Buffer, AcceptAction
from .document import Document
-from .enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
+from .enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
from .filters import IsDone, HasFocus, RendererHeightIsKnown, to_simple_filter, to_cli_filter, Condition
from .history import InMemoryHistory
from .interface import CommandLineInterface, Application, AbortAction
from .key_binding.defaults import load_key_bindings_for_prompt
-from .key_binding.registry import Registry
-from .keys import Keys
-from .layout import Window, HSplit, FloatContainer, Float
+from .key_binding.registry import Registry
+from .keys import Keys
+from .layout import Window, HSplit, FloatContainer, Float
from .layout.containers import ConditionalContainer
from .layout.controls import BufferControl, TokenListControl
from .layout.dimension import LayoutDimension
from .layout.lexers import PygmentsLexer
-from .layout.margins import PromptMargin, ConditionalMargin
+from .layout.margins import PromptMargin, ConditionalMargin
from .layout.menus import CompletionsMenu, MultiColumnCompletionsMenu
-from .layout.processors import PasswordProcessor, ConditionalProcessor, AppendAutoSuggestion, HighlightSearchProcessor, HighlightSelectionProcessor, DisplayMultipleCursors
+from .layout.processors import PasswordProcessor, ConditionalProcessor, AppendAutoSuggestion, HighlightSearchProcessor, HighlightSelectionProcessor, DisplayMultipleCursors
from .layout.prompt import DefaultPrompt
from .layout.screen import Char
from .layout.toolbars import ValidationToolbar, SystemToolbar, ArgToolbar, SearchToolbar
from .layout.utils import explode_tokens
-from .renderer import print_tokens as renderer_print_tokens
-from .styles import DEFAULT_STYLE, Style, style_from_dict
-from .token import Token
+from .renderer import print_tokens as renderer_print_tokens
+from .styles import DEFAULT_STYLE, Style, style_from_dict
+from .token import Token
from .utils import is_conemu_ansi, is_windows, DummyContext
-from six import text_type, exec_, PY2
+from six import text_type, exec_, PY2
-import os
+import os
import sys
import textwrap
-import threading
-import time
-
-try:
- from pygments.lexer import Lexer as pygments_Lexer
- from pygments.style import Style as pygments_Style
-except ImportError:
- pygments_Lexer = None
- pygments_Style = None
-
+import threading
+import time
+
+try:
+ from pygments.lexer import Lexer as pygments_Lexer
+ from pygments.style import Style as pygments_Style
+except ImportError:
+ pygments_Lexer = None
+ pygments_Style = None
+
if is_windows():
from .terminal.win32_output import Win32Output
from .terminal.conemu_output import ConEmuOutput
@@ -76,15 +76,15 @@ __all__ = (
'create_prompt_application',
'prompt',
'prompt_async',
- 'create_confirm_application',
+ 'create_confirm_application',
'run_application',
- 'confirm',
- 'print_tokens',
+ 'confirm',
+ 'print_tokens',
'clear',
)
-def create_eventloop(inputhook=None, recognize_win32_paste=True):
+def create_eventloop(inputhook=None, recognize_win32_paste=True):
"""
Create and return an
:class:`~prompt_toolkit.eventloop.base.EventLoop` instance for a
@@ -92,21 +92,21 @@ def create_eventloop(inputhook=None, recognize_win32_paste=True):
"""
if is_windows():
from prompt_toolkit.eventloop.win32 import Win32EventLoop as Loop
- return Loop(inputhook=inputhook, recognize_paste=recognize_win32_paste)
+ return Loop(inputhook=inputhook, recognize_paste=recognize_win32_paste)
else:
from prompt_toolkit.eventloop.posix import PosixEventLoop as Loop
- return Loop(inputhook=inputhook)
+ return Loop(inputhook=inputhook)
-def create_output(stdout=None, true_color=False, ansi_colors_only=None):
+def create_output(stdout=None, true_color=False, ansi_colors_only=None):
"""
Return an :class:`~prompt_toolkit.output.Output` instance for the command
line.
:param true_color: When True, use 24bit colors instead of 256 colors.
(`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.)
- :param ansi_colors_only: When True, restrict to 16 ANSI colors only.
- (`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.)
+ :param ansi_colors_only: When True, restrict to 16 ANSI colors only.
+ (`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.)
"""
stdout = stdout or sys.__stdout__
true_color = to_simple_filter(true_color)
@@ -117,15 +117,15 @@ def create_output(stdout=None, true_color=False, ansi_colors_only=None):
else:
return Win32Output(stdout)
else:
- term = os.environ.get('TERM', '')
- if PY2:
- term = term.decode('utf-8')
+ term = os.environ.get('TERM', '')
+ if PY2:
+ term = term.decode('utf-8')
+
+ return Vt100_Output.from_pty(
+ stdout, true_color=true_color,
+ ansi_colors_only=ansi_colors_only, term=term)
- return Vt100_Output.from_pty(
- stdout, true_color=true_color,
- ansi_colors_only=ansi_colors_only, term=term)
-
def create_asyncio_eventloop(loop=None):
"""
Returns an asyncio :class:`~prompt_toolkit.eventloop.EventLoop` instance
@@ -147,24 +147,24 @@ def create_asyncio_eventloop(loop=None):
def _split_multiline_prompt(get_prompt_tokens):
"""
- Take a `get_prompt_tokens` function and return three new functions instead.
- One that tells whether this prompt consists of multiple lines; one that
- returns the tokens to be shown on the lines above the input; and another
- one with the tokens to be shown at the first line of the input.
+ Take a `get_prompt_tokens` function and return three new functions instead.
+ One that tells whether this prompt consists of multiple lines; one that
+ returns the tokens to be shown on the lines above the input; and another
+ one with the tokens to be shown at the first line of the input.
"""
- def has_before_tokens(cli):
- for token, char in get_prompt_tokens(cli):
- if '\n' in char:
- return True
- return False
-
+ def has_before_tokens(cli):
+ for token, char in get_prompt_tokens(cli):
+ if '\n' in char:
+ return True
+ return False
+
def before(cli):
result = []
found_nl = False
for token, char in reversed(explode_tokens(get_prompt_tokens(cli))):
- if found_nl:
- result.insert(0, (token, char))
- elif char == '\n':
+ if found_nl:
+ result.insert(0, (token, char))
+ elif char == '\n':
found_nl = True
return result
@@ -177,23 +177,23 @@ def _split_multiline_prompt(get_prompt_tokens):
result.insert(0, (token, char))
return result
- return has_before_tokens, before, first_input_line
+ return has_before_tokens, before, first_input_line
+
+
+class _RPrompt(Window):
+ " The prompt that is displayed on the right side of the Window. "
+ def __init__(self, get_tokens=None):
+ get_tokens = get_tokens or (lambda cli: [])
+
+ super(_RPrompt, self).__init__(
+ TokenListControl(get_tokens, align_right=True))
-class _RPrompt(Window):
- " The prompt that is displayed on the right side of the Window. "
- def __init__(self, get_tokens=None):
- get_tokens = get_tokens or (lambda cli: [])
-
- super(_RPrompt, self).__init__(
- TokenListControl(get_tokens, align_right=True))
-
-
def create_prompt_layout(message='', lexer=None, is_password=False,
reserve_space_for_menu=8,
- get_prompt_tokens=None, get_continuation_tokens=None,
- get_rprompt_tokens=None,
- get_bottom_toolbar_tokens=None,
+ get_prompt_tokens=None, get_continuation_tokens=None,
+ get_rprompt_tokens=None,
+ get_bottom_toolbar_tokens=None,
display_completions_in_columns=False,
extra_input_processors=None, multiline=False,
wrap_lines=True):
@@ -210,9 +210,9 @@ def create_prompt_layout(message='', lexer=None, is_password=False,
to display the completion menu.
:param get_prompt_tokens: An optional callable that returns the tokens to be
shown in the menu. (To be used instead of a `message`.)
- :param get_continuation_tokens: An optional callable that takes a
- CommandLineInterface and width as input and returns a list of (Token,
- text) tuples to be used for the continuation.
+ :param get_continuation_tokens: An optional callable that takes a
+ CommandLineInterface and width as input and returns a list of (Token,
+ text) tuples to be used for the continuation.
:param get_bottom_toolbar_tokens: An optional callable that returns the
tokens for a toolbar at the bottom.
:param display_completions_in_columns: `bool` or
@@ -226,10 +226,10 @@ def create_prompt_layout(message='', lexer=None, is_password=False,
When True (the default), automatically wrap long lines instead of
scrolling horizontally.
"""
- assert isinstance(message, text_type), 'Please provide a unicode string.'
+ assert isinstance(message, text_type), 'Please provide a unicode string.'
assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens)
assert get_prompt_tokens is None or callable(get_prompt_tokens)
- assert get_rprompt_tokens is None or callable(get_rprompt_tokens)
+ assert get_rprompt_tokens is None or callable(get_rprompt_tokens)
assert not (message and get_prompt_tokens)
display_completions_in_columns = to_cli_filter(display_completions_in_columns)
@@ -238,33 +238,33 @@ def create_prompt_layout(message='', lexer=None, is_password=False,
if get_prompt_tokens is None:
get_prompt_tokens = lambda _: [(Token.Prompt, message)]
- has_before_tokens, get_prompt_tokens_1, get_prompt_tokens_2 = \
- _split_multiline_prompt(get_prompt_tokens)
+ has_before_tokens, get_prompt_tokens_1, get_prompt_tokens_2 = \
+ _split_multiline_prompt(get_prompt_tokens)
# `lexer` is supposed to be a `Lexer` instance. But if a Pygments lexer
# class is given, turn it into a PygmentsLexer. (Important for
# backwards-compatibility.)
try:
- if pygments_Lexer and issubclass(lexer, pygments_Lexer):
- lexer = PygmentsLexer(lexer, sync_from_start=True)
+ if pygments_Lexer and issubclass(lexer, pygments_Lexer):
+ lexer = PygmentsLexer(lexer, sync_from_start=True)
except TypeError: # Happens when lexer is `None` or an instance of something else.
pass
- # Create processors list.
- input_processors = [
- ConditionalProcessor(
+ # Create processors list.
+ input_processors = [
+ ConditionalProcessor(
# By default, only highlight search when the search
# input has the focus. (Note that this doesn't mean
# there is no search: the Vi 'n' binding for instance
# still allows to jump to the next match in
# navigation mode.)
- HighlightSearchProcessor(preview_search=True),
- HasFocus(SEARCH_BUFFER)),
- HighlightSelectionProcessor(),
+ HighlightSearchProcessor(preview_search=True),
+ HasFocus(SEARCH_BUFFER)),
+ HighlightSelectionProcessor(),
ConditionalProcessor(AppendAutoSuggestion(), HasFocus(DEFAULT_BUFFER) & ~IsDone()),
- ConditionalProcessor(PasswordProcessor(), is_password),
- DisplayMultipleCursors(DEFAULT_BUFFER),
- ]
+ ConditionalProcessor(PasswordProcessor(), is_password),
+ DisplayMultipleCursors(DEFAULT_BUFFER),
+ ]
if extra_input_processors:
input_processors.extend(extra_input_processors)
@@ -274,7 +274,7 @@ def create_prompt_layout(message='', lexer=None, is_password=False,
# (Only for single line mode.)
# (DefaultPrompt should always be at the end of the processors.)
input_processors.append(ConditionalProcessor(
- DefaultPrompt(get_prompt_tokens_2), ~multiline))
+ DefaultPrompt(get_prompt_tokens_2), ~multiline))
# Create bottom toolbar.
if get_bottom_toolbar_tokens:
@@ -290,26 +290,26 @@ def create_prompt_layout(message='', lexer=None, is_password=False,
# If there is an autocompletion menu to be shown, make sure that our
# layout has at least a minimal height in order to display it.
if reserve_space_for_menu and not cli.is_done:
- buff = cli.current_buffer
-
- # Reserve the space, either when there are completions, or when
- # `complete_while_typing` is true and we expect completions very
- # soon.
- if buff.complete_while_typing() or buff.complete_state is not None:
- return LayoutDimension(min=reserve_space_for_menu)
-
- return LayoutDimension()
-
+ buff = cli.current_buffer
+
+ # Reserve the space, either when there are completions, or when
+ # `complete_while_typing` is true and we expect completions very
+ # soon.
+ if buff.complete_while_typing() or buff.complete_state is not None:
+ return LayoutDimension(min=reserve_space_for_menu)
+
+ return LayoutDimension()
+
# Create and return Container instance.
return HSplit([
- # The main input, with completion menus floating on top of it.
- FloatContainer(
- HSplit([
- ConditionalContainer(
- Window(
- TokenListControl(get_prompt_tokens_1),
- dont_extend_height=True),
- Condition(has_before_tokens)
+ # The main input, with completion menus floating on top of it.
+ FloatContainer(
+ HSplit([
+ ConditionalContainer(
+ Window(
+ TokenListControl(get_prompt_tokens_1),
+ dont_extend_height=True),
+ Condition(has_before_tokens)
),
Window(
BufferControl(
@@ -319,38 +319,38 @@ def create_prompt_layout(message='', lexer=None, is_password=False,
# in reverse-i-search mode.
preview_search=True),
get_height=get_height,
- left_margins=[
- # In multiline mode, use the window margin to display
- # the prompt and continuation tokens.
- ConditionalMargin(
- PromptMargin(get_prompt_tokens_2, get_continuation_tokens),
- filter=multiline
- )
- ],
- wrap_lines=wrap_lines,
+ left_margins=[
+ # In multiline mode, use the window margin to display
+ # the prompt and continuation tokens.
+ ConditionalMargin(
+ PromptMargin(get_prompt_tokens_2, get_continuation_tokens),
+ filter=multiline
+ )
+ ],
+ wrap_lines=wrap_lines,
),
- ]),
- [
- # Completion menus.
- Float(xcursor=True,
- ycursor=True,
- content=CompletionsMenu(
- max_height=16,
- scroll_offset=1,
- extra_filter=HasFocus(DEFAULT_BUFFER) &
- ~display_completions_in_columns)),
- Float(xcursor=True,
- ycursor=True,
- content=MultiColumnCompletionsMenu(
- extra_filter=HasFocus(DEFAULT_BUFFER) &
- display_completions_in_columns,
- show_meta=True)),
-
- # The right prompt.
- Float(right=0, top=0, hide_when_covering_content=True,
- content=_RPrompt(get_rprompt_tokens)),
- ]
- ),
+ ]),
+ [
+ # Completion menus.
+ Float(xcursor=True,
+ ycursor=True,
+ content=CompletionsMenu(
+ max_height=16,
+ scroll_offset=1,
+ extra_filter=HasFocus(DEFAULT_BUFFER) &
+ ~display_completions_in_columns)),
+ Float(xcursor=True,
+ ycursor=True,
+ content=MultiColumnCompletionsMenu(
+ extra_filter=HasFocus(DEFAULT_BUFFER) &
+ display_completions_in_columns,
+ show_meta=True)),
+
+ # The right prompt.
+ Float(right=0, top=0, hide_when_covering_content=True,
+ content=_RPrompt(get_rprompt_tokens)),
+ ]
+ ),
ValidationToolbar(),
SystemToolbar(),
@@ -366,7 +366,7 @@ def create_prompt_application(
wrap_lines=True,
is_password=False,
vi_mode=False,
- editing_mode=EditingMode.EMACS,
+ editing_mode=EditingMode.EMACS,
complete_while_typing=True,
enable_history_search=False,
lexer=None,
@@ -380,8 +380,8 @@ def create_prompt_application(
history=None,
clipboard=None,
get_prompt_tokens=None,
- get_continuation_tokens=None,
- get_rprompt_tokens=None,
+ get_continuation_tokens=None,
+ get_rprompt_tokens=None,
get_bottom_toolbar_tokens=None,
display_completions_in_columns=False,
get_title=None,
@@ -391,7 +391,7 @@ def create_prompt_application(
on_abort=AbortAction.RAISE_EXCEPTION,
on_exit=AbortAction.RAISE_EXCEPTION,
accept_action=AcceptAction.RETURN_DOCUMENT,
- erase_when_done=False,
+ erase_when_done=False,
default=''):
"""
Create an :class:`~Application` instance for a prompt.
@@ -407,13 +407,13 @@ def create_prompt_application(
When True (the default), automatically wrap long lines instead of
scrolling horizontally.
:param is_password: Show asterisks instead of the actual typed characters.
- :param editing_mode: ``EditingMode.VI`` or ``EditingMode.EMACS``.
- :param vi_mode: `bool`, if True, Identical to ``editing_mode=EditingMode.VI``.
+ :param editing_mode: ``EditingMode.VI`` or ``EditingMode.EMACS``.
+ :param vi_mode: `bool`, if True, Identical to ``editing_mode=EditingMode.VI``.
:param complete_while_typing: `bool` or
- :class:`~prompt_toolkit.filters.SimpleFilter`. Enable autocompletion
- while typing.
+ :class:`~prompt_toolkit.filters.SimpleFilter`. Enable autocompletion
+ while typing.
:param enable_history_search: `bool` or
- :class:`~prompt_toolkit.filters.SimpleFilter`. Enable up-arrow parting
+ :class:`~prompt_toolkit.filters.SimpleFilter`. Enable up-arrow parting
string matching.
:param lexer: :class:`~prompt_toolkit.layout.lexers.Lexer` to be used for
the syntax highlighting.
@@ -425,7 +425,7 @@ def create_prompt_application(
(0 means that no space needs to be reserved.)
:param auto_suggest: :class:`~prompt_toolkit.auto_suggest.AutoSuggest`
instance for input suggestions.
- :param style: :class:`.Style` instance for the color scheme.
+ :param style: :class:`.Style` instance for the color scheme.
:param enable_system_bindings: `bool` or
:class:`~prompt_toolkit.filters.CLIFilter`. Pressing Meta+'!' will show
a system prompt.
@@ -453,10 +453,10 @@ def create_prompt_application(
enable_system_bindings=enable_system_bindings,
enable_open_in_editor=enable_open_in_editor)
- # Ensure backwards-compatibility, when `vi_mode` is passed.
- if vi_mode:
- editing_mode = EditingMode.VI
-
+ # Ensure backwards-compatibility, when `vi_mode` is passed.
+ if vi_mode:
+ editing_mode = EditingMode.VI
+
# Make sure that complete_while_typing is disabled when enable_history_search
# is enabled. (First convert to SimpleFilter, to avoid doing bitwise operations
# on bool objects.)
@@ -468,9 +468,9 @@ def create_prompt_application(
# Accept Pygments styles as well for backwards compatibility.
try:
- if pygments_Style and issubclass(style, pygments_Style):
- style = style_from_dict(style.styles)
- except TypeError: # Happens when style is `None` or an instance of something else.
+ if pygments_Style and issubclass(style, pygments_Style):
+ style = style_from_dict(style.styles)
+ except TypeError: # Happens when style is `None` or an instance of something else.
pass
# Create application
@@ -482,8 +482,8 @@ def create_prompt_application(
reserve_space_for_menu=(reserve_space_for_menu if completer is not None else 0),
multiline=Condition(lambda cli: multiline()),
get_prompt_tokens=get_prompt_tokens,
- get_continuation_tokens=get_continuation_tokens,
- get_rprompt_tokens=get_rprompt_tokens,
+ get_continuation_tokens=get_continuation_tokens,
+ get_rprompt_tokens=get_rprompt_tokens,
get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
display_completions_in_columns=display_completions_in_columns,
extra_input_processors=extra_input_processors,
@@ -504,8 +504,8 @@ def create_prompt_application(
key_bindings_registry=key_bindings_registry,
get_title=get_title,
mouse_support=mouse_support,
- editing_mode=editing_mode,
- erase_when_done=erase_when_done,
+ editing_mode=editing_mode,
+ erase_when_done=erase_when_done,
reverse_vi_search_direction=True,
on_abort=on_abort,
on_exit=on_exit)
@@ -529,93 +529,93 @@ def prompt(message='', **kwargs):
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
- :param refresh_interval: (number; in seconds) When given, refresh the UI
- every so many seconds.
+ :param refresh_interval: (number; in seconds) When given, refresh the UI
+ every so many seconds.
"""
patch_stdout = kwargs.pop('patch_stdout', False)
return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
true_color = kwargs.pop('true_color', False)
- refresh_interval = kwargs.pop('refresh_interval', 0)
- eventloop = kwargs.pop('eventloop', None)
-
- application = create_prompt_application(message, **kwargs)
-
- return run_application(application,
- patch_stdout=patch_stdout,
- return_asyncio_coroutine=return_asyncio_coroutine,
- true_color=true_color,
- refresh_interval=refresh_interval,
- eventloop=eventloop)
-
-
-def run_application(
- application, patch_stdout=False, return_asyncio_coroutine=False,
- true_color=False, refresh_interval=0, eventloop=None):
- """
- Run a prompt toolkit application.
-
- :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
- print statements from other threads won't destroy the prompt. (They
- will be printed above the prompt instead.)
- :param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
- :param true_color: When True, use 24bit colors instead of 256 colors.
- :param refresh_interval: (number; in seconds) When given, refresh the UI
- every so many seconds.
- """
- assert isinstance(application, Application)
-
+ refresh_interval = kwargs.pop('refresh_interval', 0)
+ eventloop = kwargs.pop('eventloop', None)
+
+ application = create_prompt_application(message, **kwargs)
+
+ return run_application(application,
+ patch_stdout=patch_stdout,
+ return_asyncio_coroutine=return_asyncio_coroutine,
+ true_color=true_color,
+ refresh_interval=refresh_interval,
+ eventloop=eventloop)
+
+
+def run_application(
+ application, patch_stdout=False, return_asyncio_coroutine=False,
+ true_color=False, refresh_interval=0, eventloop=None):
+ """
+ Run a prompt toolkit application.
+
+ :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
+ print statements from other threads won't destroy the prompt. (They
+ will be printed above the prompt instead.)
+ :param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
+ :param true_color: When True, use 24bit colors instead of 256 colors.
+ :param refresh_interval: (number; in seconds) When given, refresh the UI
+ every so many seconds.
+ """
+ assert isinstance(application, Application)
+
if return_asyncio_coroutine:
eventloop = create_asyncio_eventloop()
else:
- eventloop = eventloop or create_eventloop()
+ eventloop = eventloop or create_eventloop()
# Create CommandLineInterface.
cli = CommandLineInterface(
- application=application,
+ application=application,
eventloop=eventloop,
output=create_output(true_color=true_color))
- # Set up refresh interval.
- if refresh_interval:
- done = [False]
- def start_refresh_loop(cli):
- def run():
- while not done[0]:
- time.sleep(refresh_interval)
- cli.request_redraw()
- t = threading.Thread(target=run)
- t.daemon = True
- t.start()
-
- def stop_refresh_loop(cli):
- done[0] = True
-
- cli.on_start += start_refresh_loop
- cli.on_stop += stop_refresh_loop
-
+ # Set up refresh interval.
+ if refresh_interval:
+ done = [False]
+ def start_refresh_loop(cli):
+ def run():
+ while not done[0]:
+ time.sleep(refresh_interval)
+ cli.request_redraw()
+ t = threading.Thread(target=run)
+ t.daemon = True
+ t.start()
+
+ def stop_refresh_loop(cli):
+ done[0] = True
+
+ cli.on_start += start_refresh_loop
+ cli.on_stop += stop_refresh_loop
+
# Replace stdout.
patch_context = cli.patch_stdout_context(raw=True) if patch_stdout else DummyContext()
# Read input and return it.
if return_asyncio_coroutine:
# Create an asyncio coroutine and call it.
- exec_context = {'patch_context': patch_context, 'cli': cli,
- 'Document': Document}
+ exec_context = {'patch_context': patch_context, 'cli': cli,
+ 'Document': Document}
exec_(textwrap.dedent('''
def prompt_coro():
- # Inline import, because it slows down startup when asyncio is not
- # needed.
- import asyncio
+ # Inline import, because it slows down startup when asyncio is not
+ # needed.
+ import asyncio
- @asyncio.coroutine
- def run():
- with patch_context:
+ @asyncio.coroutine
+ def run():
+ with patch_context:
result = yield from cli.run_async()
-
- if isinstance(result, Document): # Backwards-compatibility.
- return result.text
- return result
- return run()
+
+ if isinstance(result, Document): # Backwards-compatibility.
+ return result.text
+ return result
+ return run()
'''), exec_context)
return exec_context['prompt_coro']()
@@ -624,9 +624,9 @@ def run_application(
with patch_context:
result = cli.run()
- if isinstance(result, Document): # Backwards-compatibility.
- return result.text
- return result
+ if isinstance(result, Document): # Backwards-compatibility.
+ return result.text
+ return result
finally:
eventloop.close()
@@ -639,79 +639,79 @@ def prompt_async(message='', **kwargs):
return prompt(message, **kwargs)
-def create_confirm_application(message):
- """
- Create a confirmation `Application` that returns True/False.
- """
- registry = Registry()
-
- @registry.add_binding('y')
- @registry.add_binding('Y')
- def _(event):
- event.cli.buffers[DEFAULT_BUFFER].text = 'y'
- event.cli.set_return_value(True)
-
- @registry.add_binding('n')
- @registry.add_binding('N')
- @registry.add_binding(Keys.ControlC)
- def _(event):
- event.cli.buffers[DEFAULT_BUFFER].text = 'n'
- event.cli.set_return_value(False)
-
- return create_prompt_application(message, key_bindings_registry=registry)
-
-
-def confirm(message='Confirm (y or n) '):
- """
- Display a confirmation prompt.
- """
- assert isinstance(message, text_type)
-
- app = create_confirm_application(message)
- return run_application(app)
-
-
+def create_confirm_application(message):
+ """
+ Create a confirmation `Application` that returns True/False.
+ """
+ registry = Registry()
+
+ @registry.add_binding('y')
+ @registry.add_binding('Y')
+ def _(event):
+ event.cli.buffers[DEFAULT_BUFFER].text = 'y'
+ event.cli.set_return_value(True)
+
+ @registry.add_binding('n')
+ @registry.add_binding('N')
+ @registry.add_binding(Keys.ControlC)
+ def _(event):
+ event.cli.buffers[DEFAULT_BUFFER].text = 'n'
+ event.cli.set_return_value(False)
+
+ return create_prompt_application(message, key_bindings_registry=registry)
+
+
+def confirm(message='Confirm (y or n) '):
+ """
+ Display a confirmation prompt.
+ """
+ assert isinstance(message, text_type)
+
+ app = create_confirm_application(message)
+ return run_application(app)
+
+
def print_tokens(tokens, style=None, true_color=False, file=None):
- """
- Print a list of (Token, text) tuples in the given style to the output.
- E.g.::
-
- style = style_from_dict({
- Token.Hello: '#ff0066',
- Token.World: '#884444 italic',
- })
- tokens = [
- (Token.Hello, 'Hello'),
- (Token.World, 'World'),
- ]
- print_tokens(tokens, style=style)
-
- :param tokens: List of ``(Token, text)`` tuples.
- :param style: :class:`.Style` instance for the color scheme.
- :param true_color: When True, use 24bit colors instead of 256 colors.
+ """
+ Print a list of (Token, text) tuples in the given style to the output.
+ E.g.::
+
+ style = style_from_dict({
+ Token.Hello: '#ff0066',
+ Token.World: '#884444 italic',
+ })
+ tokens = [
+ (Token.Hello, 'Hello'),
+ (Token.World, 'World'),
+ ]
+ print_tokens(tokens, style=style)
+
+ :param tokens: List of ``(Token, text)`` tuples.
+ :param style: :class:`.Style` instance for the color scheme.
+ :param true_color: When True, use 24bit colors instead of 256 colors.
:param file: The output file. This can be `sys.stdout` or `sys.stderr`.
- """
+ """
if style is None:
style = DEFAULT_STYLE
- assert isinstance(style, Style)
-
+ assert isinstance(style, Style)
+
output = create_output(true_color=true_color, stdout=file)
- renderer_print_tokens(output, tokens, style)
-
-
-def clear():
- """
- Clear the screen.
- """
- out = create_output()
- out.erase_screen()
- out.cursor_goto(0, 0)
- out.flush()
-
-
+ renderer_print_tokens(output, tokens, style)
+
+
+def clear():
+ """
+ Clear the screen.
+ """
+ out = create_output()
+ out.erase_screen()
+ out.cursor_goto(0, 0)
+ out.flush()
+
+
# Deprecated alias for `prompt`.
get_input = prompt
-# Deprecated alias for create_prompt_layout
-create_default_layout = create_prompt_layout
-# Deprecated alias for create_prompt_application
-create_default_application = create_prompt_application
+# Deprecated alias for create_prompt_layout
+create_default_layout = create_prompt_layout
+# Deprecated alias for create_prompt_application
+create_default_application = create_prompt_application
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/__init__.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/__init__.py
index 4735ab2155..9d641f0447 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/__init__.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/__init__.py
@@ -1,21 +1,21 @@
-"""
-Styling for prompt_toolkit applications.
-"""
-from __future__ import unicode_literals
-
-from .base import *
-from .defaults import *
-from .from_dict import *
-from .from_pygments import *
-from .utils import *
-
-
-#: The default built-in style.
-#: (For backwards compatibility, when Pygments is installed, this includes the
-#: default Pygments style.)
-try:
- import pygments
-except ImportError:
- DEFAULT_STYLE = style_from_dict(DEFAULT_STYLE_EXTENSIONS)
-else:
- DEFAULT_STYLE = style_from_pygments()
+"""
+Styling for prompt_toolkit applications.
+"""
+from __future__ import unicode_literals
+
+from .base import *
+from .defaults import *
+from .from_dict import *
+from .from_pygments import *
+from .utils import *
+
+
+#: The default built-in style.
+#: (For backwards compatibility, when Pygments is installed, this includes the
+#: default Pygments style.)
+try:
+ import pygments
+except ImportError:
+ DEFAULT_STYLE = style_from_dict(DEFAULT_STYLE_EXTENSIONS)
+else:
+ DEFAULT_STYLE = style_from_pygments()
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/base.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/base.py
index d1009ba3b2..e9ddaa524d 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/base.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/base.py
@@ -1,86 +1,86 @@
-"""
-The base classes for the styling.
-"""
-from __future__ import unicode_literals
-from abc import ABCMeta, abstractmethod
-from collections import namedtuple
-from six import with_metaclass
-
-__all__ = (
- 'Attrs',
- 'DEFAULT_ATTRS',
- 'ANSI_COLOR_NAMES',
- 'Style',
- 'DynamicStyle',
-)
-
-
-#: Style attributes.
-Attrs = namedtuple('Attrs', 'color bgcolor bold underline italic blink reverse')
-"""
-:param color: Hexadecimal string. E.g. '000000' or Ansi color name: e.g. 'ansiblue'
-:param bgcolor: Hexadecimal string. E.g. 'ffffff' or Ansi color name: e.g. 'ansired'
-:param bold: Boolean
-:param underline: Boolean
-:param italic: Boolean
-:param blink: Boolean
-:param reverse: Boolean
-"""
-
-#: The default `Attrs`.
-DEFAULT_ATTRS = Attrs(color=None, bgcolor=None, bold=False, underline=False,
- italic=False, blink=False, reverse=False)
-
-
-#: ``Attrs.bgcolor/fgcolor`` can be in either 'ffffff' format, or can be any of
-#: the following in case we want to take colors from the 8/16 color palette.
-#: Usually, in that case, the terminal application allows to configure the RGB
-#: values for these names.
-ANSI_COLOR_NAMES = [
- 'ansiblack', 'ansiwhite', 'ansidefault',
-
- # Low intensity.
- 'ansired', 'ansigreen', 'ansiyellow', 'ansiblue', 'ansifuchsia', 'ansiturquoise', 'ansilightgray',
-
- # High intensity. (Not supported everywhere.)
- 'ansidarkgray', 'ansidarkred', 'ansidarkgreen', 'ansibrown', 'ansidarkblue',
- 'ansipurple', 'ansiteal',
-]
-
-
-class Style(with_metaclass(ABCMeta, object)):
- """
- Abstract base class for prompt_toolkit styles.
- """
- @abstractmethod
- def get_attrs_for_token(self, token):
- """
- Return :class:`.Attrs` for the given token.
- """
-
- @abstractmethod
- def invalidation_hash(self):
- """
- Invalidation hash for the style. When this changes over time, the
- renderer knows that something in the style changed, and that everything
- has to be redrawn.
- """
-
-
-class DynamicStyle(Style):
- """
- Style class that can dynamically returns an other Style.
-
- :param get_style: Callable that returns a :class:`.Style` instance.
- """
- def __init__(self, get_style):
- self.get_style = get_style
-
- def get_attrs_for_token(self, token):
- style = self.get_style()
- assert isinstance(style, Style)
-
- return style.get_attrs_for_token(token)
-
- def invalidation_hash(self):
- return self.get_style().invalidation_hash()
+"""
+The base classes for the styling.
+"""
+from __future__ import unicode_literals
+from abc import ABCMeta, abstractmethod
+from collections import namedtuple
+from six import with_metaclass
+
+__all__ = (
+ 'Attrs',
+ 'DEFAULT_ATTRS',
+ 'ANSI_COLOR_NAMES',
+ 'Style',
+ 'DynamicStyle',
+)
+
+
+#: Style attributes.
+Attrs = namedtuple('Attrs', 'color bgcolor bold underline italic blink reverse')
+"""
+:param color: Hexadecimal string. E.g. '000000' or Ansi color name: e.g. 'ansiblue'
+:param bgcolor: Hexadecimal string. E.g. 'ffffff' or Ansi color name: e.g. 'ansired'
+:param bold: Boolean
+:param underline: Boolean
+:param italic: Boolean
+:param blink: Boolean
+:param reverse: Boolean
+"""
+
+#: The default `Attrs`.
+DEFAULT_ATTRS = Attrs(color=None, bgcolor=None, bold=False, underline=False,
+ italic=False, blink=False, reverse=False)
+
+
+#: ``Attrs.bgcolor/fgcolor`` can be in either 'ffffff' format, or can be any of
+#: the following in case we want to take colors from the 8/16 color palette.
+#: Usually, in that case, the terminal application allows to configure the RGB
+#: values for these names.
+ANSI_COLOR_NAMES = [
+ 'ansiblack', 'ansiwhite', 'ansidefault',
+
+ # Low intensity.
+ 'ansired', 'ansigreen', 'ansiyellow', 'ansiblue', 'ansifuchsia', 'ansiturquoise', 'ansilightgray',
+
+ # High intensity. (Not supported everywhere.)
+ 'ansidarkgray', 'ansidarkred', 'ansidarkgreen', 'ansibrown', 'ansidarkblue',
+ 'ansipurple', 'ansiteal',
+]
+
+
+class Style(with_metaclass(ABCMeta, object)):
+ """
+ Abstract base class for prompt_toolkit styles.
+ """
+ @abstractmethod
+ def get_attrs_for_token(self, token):
+ """
+ Return :class:`.Attrs` for the given token.
+ """
+
+ @abstractmethod
+ def invalidation_hash(self):
+ """
+ Invalidation hash for the style. When this changes over time, the
+ renderer knows that something in the style changed, and that everything
+ has to be redrawn.
+ """
+
+
+class DynamicStyle(Style):
+ """
+ Style class that can dynamically returns an other Style.
+
+ :param get_style: Callable that returns a :class:`.Style` instance.
+ """
+ def __init__(self, get_style):
+ self.get_style = get_style
+
+ def get_attrs_for_token(self, token):
+ style = self.get_style()
+ assert isinstance(style, Style)
+
+ return style.get_attrs_for_token(token)
+
+ def invalidation_hash(self):
+ return self.get_style().invalidation_hash()
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/defaults.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/defaults.py
index f280dd4646..5357eaa111 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/defaults.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/defaults.py
@@ -1,95 +1,95 @@
-"""
-The default styling.
-"""
-from __future__ import unicode_literals
-
-from prompt_toolkit.token import Token
-
-__all__ = (
- 'DEFAULT_STYLE_EXTENSIONS',
- 'default_style_extensions',
-)
-
-
-#: Styling of prompt-toolkit specific tokens, that are not know by the default
-#: Pygments style.
-DEFAULT_STYLE_EXTENSIONS = {
- # Highlighting of search matches in document.
- Token.SearchMatch: 'noinherit reverse',
- Token.SearchMatch.Current: 'noinherit #ffffff bg:#448844 underline',
-
- # Highlighting of select text in document.
- Token.SelectedText: 'reverse',
-
- Token.CursorColumn: 'bg:#dddddd',
- Token.CursorLine: 'underline',
- Token.ColorColumn: 'bg:#ccaacc',
-
- # Highlighting of matching brackets.
- Token.MatchingBracket: '',
- Token.MatchingBracket.Other: '#000000 bg:#aacccc',
- Token.MatchingBracket.Cursor: '#ff8888 bg:#880000',
-
- Token.MultipleCursors.Cursor: '#000000 bg:#ccccaa',
-
- # Line numbers.
- Token.LineNumber: '#888888',
- Token.LineNumber.Current: 'bold',
- Token.Tilde: '#8888ff',
-
- # Default prompt.
- Token.Prompt: '',
- Token.Prompt.Arg: 'noinherit',
- Token.Prompt.Search: 'noinherit',
- Token.Prompt.Search.Text: '',
-
- # Search toolbar.
- Token.Toolbar.Search: 'bold',
- Token.Toolbar.Search.Text: 'nobold',
-
- # System toolbar
- Token.Toolbar.System: 'bold',
- Token.Toolbar.System.Text: 'nobold',
-
- # "arg" toolbar.
- Token.Toolbar.Arg: 'bold',
- Token.Toolbar.Arg.Text: 'nobold',
-
- # Validation toolbar.
- Token.Toolbar.Validation: 'bg:#550000 #ffffff',
- Token.WindowTooSmall: 'bg:#550000 #ffffff',
-
- # Completions toolbar.
- Token.Toolbar.Completions: 'bg:#bbbbbb #000000',
- Token.Toolbar.Completions.Arrow: 'bg:#bbbbbb #000000 bold',
- Token.Toolbar.Completions.Completion: 'bg:#bbbbbb #000000',
- Token.Toolbar.Completions.Completion.Current: 'bg:#444444 #ffffff',
-
- # Completions menu.
- Token.Menu.Completions: 'bg:#bbbbbb #000000',
- Token.Menu.Completions.Completion: '',
- Token.Menu.Completions.Completion.Current: 'bg:#888888 #ffffff',
- Token.Menu.Completions.Meta: 'bg:#999999 #000000',
- Token.Menu.Completions.Meta.Current: 'bg:#aaaaaa #000000',
- Token.Menu.Completions.MultiColumnMeta: 'bg:#aaaaaa #000000',
-
- # Scrollbars.
- Token.Scrollbar: 'bg:#888888',
- Token.Scrollbar.Button: 'bg:#444444',
- Token.Scrollbar.Arrow: 'bg:#222222 #888888 bold',
-
- # Auto suggestion text.
- Token.AutoSuggestion: '#666666',
-
- # Trailing whitespace and tabs.
- Token.TrailingWhiteSpace: '#999999',
- Token.Tab: '#999999',
-
- # When Control-C has been pressed. Grayed.
- Token.Aborted: '#888888',
-
- # Entering a Vi digraph.
- Token.Digraph: '#4444ff',
-}
-
-default_style_extensions = DEFAULT_STYLE_EXTENSIONS # Old name.
+"""
+The default styling.
+"""
+from __future__ import unicode_literals
+
+from prompt_toolkit.token import Token
+
+__all__ = (
+ 'DEFAULT_STYLE_EXTENSIONS',
+ 'default_style_extensions',
+)
+
+
+#: Styling of prompt-toolkit specific tokens, that are not know by the default
+#: Pygments style.
+DEFAULT_STYLE_EXTENSIONS = {
+ # Highlighting of search matches in document.
+ Token.SearchMatch: 'noinherit reverse',
+ Token.SearchMatch.Current: 'noinherit #ffffff bg:#448844 underline',
+
+ # Highlighting of select text in document.
+ Token.SelectedText: 'reverse',
+
+ Token.CursorColumn: 'bg:#dddddd',
+ Token.CursorLine: 'underline',
+ Token.ColorColumn: 'bg:#ccaacc',
+
+ # Highlighting of matching brackets.
+ Token.MatchingBracket: '',
+ Token.MatchingBracket.Other: '#000000 bg:#aacccc',
+ Token.MatchingBracket.Cursor: '#ff8888 bg:#880000',
+
+ Token.MultipleCursors.Cursor: '#000000 bg:#ccccaa',
+
+ # Line numbers.
+ Token.LineNumber: '#888888',
+ Token.LineNumber.Current: 'bold',
+ Token.Tilde: '#8888ff',
+
+ # Default prompt.
+ Token.Prompt: '',
+ Token.Prompt.Arg: 'noinherit',
+ Token.Prompt.Search: 'noinherit',
+ Token.Prompt.Search.Text: '',
+
+ # Search toolbar.
+ Token.Toolbar.Search: 'bold',
+ Token.Toolbar.Search.Text: 'nobold',
+
+ # System toolbar
+ Token.Toolbar.System: 'bold',
+ Token.Toolbar.System.Text: 'nobold',
+
+ # "arg" toolbar.
+ Token.Toolbar.Arg: 'bold',
+ Token.Toolbar.Arg.Text: 'nobold',
+
+ # Validation toolbar.
+ Token.Toolbar.Validation: 'bg:#550000 #ffffff',
+ Token.WindowTooSmall: 'bg:#550000 #ffffff',
+
+ # Completions toolbar.
+ Token.Toolbar.Completions: 'bg:#bbbbbb #000000',
+ Token.Toolbar.Completions.Arrow: 'bg:#bbbbbb #000000 bold',
+ Token.Toolbar.Completions.Completion: 'bg:#bbbbbb #000000',
+ Token.Toolbar.Completions.Completion.Current: 'bg:#444444 #ffffff',
+
+ # Completions menu.
+ Token.Menu.Completions: 'bg:#bbbbbb #000000',
+ Token.Menu.Completions.Completion: '',
+ Token.Menu.Completions.Completion.Current: 'bg:#888888 #ffffff',
+ Token.Menu.Completions.Meta: 'bg:#999999 #000000',
+ Token.Menu.Completions.Meta.Current: 'bg:#aaaaaa #000000',
+ Token.Menu.Completions.MultiColumnMeta: 'bg:#aaaaaa #000000',
+
+ # Scrollbars.
+ Token.Scrollbar: 'bg:#888888',
+ Token.Scrollbar.Button: 'bg:#444444',
+ Token.Scrollbar.Arrow: 'bg:#222222 #888888 bold',
+
+ # Auto suggestion text.
+ Token.AutoSuggestion: '#666666',
+
+ # Trailing whitespace and tabs.
+ Token.TrailingWhiteSpace: '#999999',
+ Token.Tab: '#999999',
+
+ # When Control-C has been pressed. Grayed.
+ Token.Aborted: '#888888',
+
+ # Entering a Vi digraph.
+ Token.Digraph: '#4444ff',
+}
+
+default_style_extensions = DEFAULT_STYLE_EXTENSIONS # Old name.
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_dict.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_dict.py
index e000aceb93..b50325710f 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_dict.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_dict.py
@@ -1,151 +1,151 @@
-"""
-Tool for creating styles from a dictionary.
-
-This is very similar to the Pygments style dictionary, with some additions:
-- Support for reverse and blink.
-- Support for ANSI color names. (These will map directly to the 16 terminal
- colors.)
-"""
+"""
+Tool for creating styles from a dictionary.
+
+This is very similar to the Pygments style dictionary, with some additions:
+- Support for reverse and blink.
+- Support for ANSI color names. (These will map directly to the 16 terminal
+ colors.)
+"""
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
-
-from .base import Style, DEFAULT_ATTRS, ANSI_COLOR_NAMES
-from .defaults import DEFAULT_STYLE_EXTENSIONS
-from .utils import merge_attrs, split_token_in_parts
-from six.moves import range
-
-__all__ = (
- 'style_from_dict',
-)
-
-
-def _colorformat(text):
- """
- Parse/validate color format.
-
- Like in Pygments, but also support the ANSI color names.
- (These will map to the colors of the 16 color palette.)
- """
- if text[0:1] == '#':
- col = text[1:]
- if col in ANSI_COLOR_NAMES:
- return col
- elif len(col) == 6:
- return col
- elif len(col) == 3:
- return col[0]*2 + col[1]*2 + col[2]*2
- elif text == '':
- return text
-
- raise ValueError('Wrong color format %r' % text)
-
-
-def style_from_dict(style_dict, include_defaults=True):
- """
- Create a ``Style`` instance from a dictionary or other mapping.
-
- The dictionary is equivalent to the ``Style.styles`` dictionary from
- pygments, with a few additions: it supports 'reverse' and 'blink'.
-
- Usage::
-
- style_from_dict({
- Token: '#ff0000 bold underline',
- Token.Title: 'blink',
- Token.SomethingElse: 'reverse',
- })
-
- :param include_defaults: Include the defaults (built-in) styling for
- selected text, etc...)
- """
- assert isinstance(style_dict, Mapping)
-
- if include_defaults:
- s2 = {}
- s2.update(DEFAULT_STYLE_EXTENSIONS)
- s2.update(style_dict)
- style_dict = s2
-
- # Expand token inheritance and turn style description into Attrs.
- token_to_attrs = {}
-
- # (Loop through the tokens in order. Sorting makes sure that
- # we process the parent first.)
- for ttype, styledef in sorted(style_dict.items()):
- # Start from parent Attrs or default Attrs.
- attrs = DEFAULT_ATTRS
-
- if 'noinherit' not in styledef:
- for i in range(1, len(ttype) + 1):
- try:
- attrs = token_to_attrs[ttype[:-i]]
- except KeyError:
- pass
- else:
- break
-
- # Now update with the given attributes.
- for part in styledef.split():
- if part == 'noinherit':
- pass
- elif part == 'bold':
- attrs = attrs._replace(bold=True)
- elif part == 'nobold':
- attrs = attrs._replace(bold=False)
- elif part == 'italic':
- attrs = attrs._replace(italic=True)
- elif part == 'noitalic':
- attrs = attrs._replace(italic=False)
- elif part == 'underline':
- attrs = attrs._replace(underline=True)
- elif part == 'nounderline':
- attrs = attrs._replace(underline=False)
-
- # prompt_toolkit extensions. Not in Pygments.
- elif part == 'blink':
- attrs = attrs._replace(blink=True)
- elif part == 'noblink':
- attrs = attrs._replace(blink=False)
- elif part == 'reverse':
- attrs = attrs._replace(reverse=True)
- elif part == 'noreverse':
- attrs = attrs._replace(reverse=False)
-
- # Pygments properties that we ignore.
- elif part in ('roman', 'sans', 'mono'):
- pass
- elif part.startswith('border:'):
- pass
-
- # Colors.
-
- elif part.startswith('bg:'):
- attrs = attrs._replace(bgcolor=_colorformat(part[3:]))
- else:
- attrs = attrs._replace(color=_colorformat(part))
-
- token_to_attrs[ttype] = attrs
-
- return _StyleFromDict(token_to_attrs)
-
-
-class _StyleFromDict(Style):
- """
- Turn a dictionary that maps `Token` to `Attrs` into a style class.
-
- :param token_to_attrs: Dictionary that maps `Token` to `Attrs`.
- """
- def __init__(self, token_to_attrs):
- self.token_to_attrs = token_to_attrs
-
- def get_attrs_for_token(self, token):
- # Split Token.
- list_of_attrs = []
- for token in split_token_in_parts(token):
- list_of_attrs.append(self.token_to_attrs.get(token, DEFAULT_ATTRS))
- return merge_attrs(list_of_attrs)
-
- def invalidation_hash(self):
- return id(self.token_to_attrs)
+
+from .base import Style, DEFAULT_ATTRS, ANSI_COLOR_NAMES
+from .defaults import DEFAULT_STYLE_EXTENSIONS
+from .utils import merge_attrs, split_token_in_parts
+from six.moves import range
+
+__all__ = (
+ 'style_from_dict',
+)
+
+
+def _colorformat(text):
+ """
+ Parse/validate color format.
+
+ Like in Pygments, but also support the ANSI color names.
+ (These will map to the colors of the 16 color palette.)
+ """
+ if text[0:1] == '#':
+ col = text[1:]
+ if col in ANSI_COLOR_NAMES:
+ return col
+ elif len(col) == 6:
+ return col
+ elif len(col) == 3:
+ return col[0]*2 + col[1]*2 + col[2]*2
+ elif text == '':
+ return text
+
+ raise ValueError('Wrong color format %r' % text)
+
+
+def style_from_dict(style_dict, include_defaults=True):
+ """
+ Create a ``Style`` instance from a dictionary or other mapping.
+
+ The dictionary is equivalent to the ``Style.styles`` dictionary from
+ pygments, with a few additions: it supports 'reverse' and 'blink'.
+
+ Usage::
+
+ style_from_dict({
+ Token: '#ff0000 bold underline',
+ Token.Title: 'blink',
+ Token.SomethingElse: 'reverse',
+ })
+
+ :param include_defaults: Include the defaults (built-in) styling for
+ selected text, etc...)
+ """
+ assert isinstance(style_dict, Mapping)
+
+ if include_defaults:
+ s2 = {}
+ s2.update(DEFAULT_STYLE_EXTENSIONS)
+ s2.update(style_dict)
+ style_dict = s2
+
+ # Expand token inheritance and turn style description into Attrs.
+ token_to_attrs = {}
+
+ # (Loop through the tokens in order. Sorting makes sure that
+ # we process the parent first.)
+ for ttype, styledef in sorted(style_dict.items()):
+ # Start from parent Attrs or default Attrs.
+ attrs = DEFAULT_ATTRS
+
+ if 'noinherit' not in styledef:
+ for i in range(1, len(ttype) + 1):
+ try:
+ attrs = token_to_attrs[ttype[:-i]]
+ except KeyError:
+ pass
+ else:
+ break
+
+ # Now update with the given attributes.
+ for part in styledef.split():
+ if part == 'noinherit':
+ pass
+ elif part == 'bold':
+ attrs = attrs._replace(bold=True)
+ elif part == 'nobold':
+ attrs = attrs._replace(bold=False)
+ elif part == 'italic':
+ attrs = attrs._replace(italic=True)
+ elif part == 'noitalic':
+ attrs = attrs._replace(italic=False)
+ elif part == 'underline':
+ attrs = attrs._replace(underline=True)
+ elif part == 'nounderline':
+ attrs = attrs._replace(underline=False)
+
+ # prompt_toolkit extensions. Not in Pygments.
+ elif part == 'blink':
+ attrs = attrs._replace(blink=True)
+ elif part == 'noblink':
+ attrs = attrs._replace(blink=False)
+ elif part == 'reverse':
+ attrs = attrs._replace(reverse=True)
+ elif part == 'noreverse':
+ attrs = attrs._replace(reverse=False)
+
+ # Pygments properties that we ignore.
+ elif part in ('roman', 'sans', 'mono'):
+ pass
+ elif part.startswith('border:'):
+ pass
+
+ # Colors.
+
+ elif part.startswith('bg:'):
+ attrs = attrs._replace(bgcolor=_colorformat(part[3:]))
+ else:
+ attrs = attrs._replace(color=_colorformat(part))
+
+ token_to_attrs[ttype] = attrs
+
+ return _StyleFromDict(token_to_attrs)
+
+
+class _StyleFromDict(Style):
+ """
+ Turn a dictionary that maps `Token` to `Attrs` into a style class.
+
+ :param token_to_attrs: Dictionary that maps `Token` to `Attrs`.
+ """
+ def __init__(self, token_to_attrs):
+ self.token_to_attrs = token_to_attrs
+
+ def get_attrs_for_token(self, token):
+ # Split Token.
+ list_of_attrs = []
+ for token in split_token_in_parts(token):
+ list_of_attrs.append(self.token_to_attrs.get(token, DEFAULT_ATTRS))
+ return merge_attrs(list_of_attrs)
+
+ def invalidation_hash(self):
+ return id(self.token_to_attrs)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_pygments.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_pygments.py
index 9be932f2e0..0af8c53cf2 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_pygments.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/from_pygments.py
@@ -1,77 +1,77 @@
-"""
-Adaptor for building prompt_toolkit styles, starting from a Pygments style.
-
-Usage::
-
- from pygments.styles.tango import TangoStyle
- style = style_from_pygments(pygments_style_cls=TangoStyle)
-"""
-from __future__ import unicode_literals
-
-from .base import Style
-from .from_dict import style_from_dict
-
-__all__ = (
- 'PygmentsStyle',
- 'style_from_pygments',
-)
-
-
-# Following imports are only needed when a ``PygmentsStyle`` class is used.
-try:
- from pygments.style import Style as pygments_Style
- from pygments.styles.default import DefaultStyle as pygments_DefaultStyle
-except ImportError:
- pygments_Style = None
- pygments_DefaultStyle = None
-
-
-def style_from_pygments(style_cls=pygments_DefaultStyle,
- style_dict=None,
- include_defaults=True):
- """
- Shortcut to create a :class:`.Style` instance from a Pygments style class
- and a style dictionary.
-
+"""
+Adaptor for building prompt_toolkit styles, starting from a Pygments style.
+
+Usage::
+
+ from pygments.styles.tango import TangoStyle
+ style = style_from_pygments(pygments_style_cls=TangoStyle)
+"""
+from __future__ import unicode_literals
+
+from .base import Style
+from .from_dict import style_from_dict
+
+__all__ = (
+ 'PygmentsStyle',
+ 'style_from_pygments',
+)
+
+
+# Following imports are only needed when a ``PygmentsStyle`` class is used.
+try:
+ from pygments.style import Style as pygments_Style
+ from pygments.styles.default import DefaultStyle as pygments_DefaultStyle
+except ImportError:
+ pygments_Style = None
+ pygments_DefaultStyle = None
+
+
+def style_from_pygments(style_cls=pygments_DefaultStyle,
+ style_dict=None,
+ include_defaults=True):
+ """
+ Shortcut to create a :class:`.Style` instance from a Pygments style class
+ and a style dictionary.
+
Example::
from prompt_toolkit.styles.from_pygments import style_from_pygments
from pygments.styles import get_style_by_name
style = style_from_pygments(get_style_by_name('monokai'))
- :param style_cls: Pygments style class to start from.
- :param style_dict: Dictionary for this style. `{Token: style}`.
- :param include_defaults: (`bool`) Include prompt_toolkit extensions.
- """
- assert style_dict is None or isinstance(style_dict, dict)
- assert style_cls is None or issubclass(style_cls, pygments_Style)
-
- styles_dict = {}
-
- if style_cls is not None:
- styles_dict.update(style_cls.styles)
-
- if style_dict is not None:
- styles_dict.update(style_dict)
-
- return style_from_dict(styles_dict, include_defaults=include_defaults)
-
-
-class PygmentsStyle(Style):
- " Deprecated. "
- def __new__(cls, pygments_style_cls):
- assert issubclass(pygments_style_cls, pygments_Style)
- return style_from_dict(pygments_style_cls.styles)
-
- def invalidation_hash(self):
- pass
-
- @classmethod
- def from_defaults(cls, style_dict=None,
- pygments_style_cls=pygments_DefaultStyle,
- include_extensions=True):
- " Deprecated. "
- return style_from_pygments(
- style_cls=pygments_style_cls,
- style_dict=style_dict,
- include_defaults=include_extensions)
+ :param style_cls: Pygments style class to start from.
+ :param style_dict: Dictionary for this style. `{Token: style}`.
+ :param include_defaults: (`bool`) Include prompt_toolkit extensions.
+ """
+ assert style_dict is None or isinstance(style_dict, dict)
+ assert style_cls is None or issubclass(style_cls, pygments_Style)
+
+ styles_dict = {}
+
+ if style_cls is not None:
+ styles_dict.update(style_cls.styles)
+
+ if style_dict is not None:
+ styles_dict.update(style_dict)
+
+ return style_from_dict(styles_dict, include_defaults=include_defaults)
+
+
+class PygmentsStyle(Style):
+ " Deprecated. "
+ def __new__(cls, pygments_style_cls):
+ assert issubclass(pygments_style_cls, pygments_Style)
+ return style_from_dict(pygments_style_cls.styles)
+
+ def invalidation_hash(self):
+ pass
+
+ @classmethod
+ def from_defaults(cls, style_dict=None,
+ pygments_style_cls=pygments_DefaultStyle,
+ include_extensions=True):
+ " Deprecated. "
+ return style_from_pygments(
+ style_cls=pygments_style_cls,
+ style_dict=style_dict,
+ include_defaults=include_extensions)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/utils.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/utils.py
index 75982af3ab..6087e76abe 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/utils.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/styles/utils.py
@@ -1,45 +1,45 @@
-from __future__ import unicode_literals
-from .base import DEFAULT_ATTRS, Attrs
-
-__all__ = (
- 'split_token_in_parts',
- 'merge_attrs',
-)
-
-
-def split_token_in_parts(token):
- """
- Take a Token, and turn it in a list of tokens, by splitting
- it on ':' (taking that as a separator.)
- """
- result = []
- current = []
- for part in token + (':', ):
- if part == ':':
- if current:
- result.append(tuple(current))
- current = []
- else:
- current.append(part)
-
- return result
-
-
-def merge_attrs(list_of_attrs):
- """
- Take a list of :class:`.Attrs` instances and merge them into one.
- Every `Attr` in the list can override the styling of the previous one.
- """
- result = DEFAULT_ATTRS
-
- for attr in list_of_attrs:
- result = Attrs(
- color=attr.color or result.color,
- bgcolor=attr.bgcolor or result.bgcolor,
- bold=attr.bold or result.bold,
- underline=attr.underline or result.underline,
- italic=attr.italic or result.italic,
- blink=attr.blink or result.blink,
- reverse=attr.reverse or result.reverse)
-
- return result
+from __future__ import unicode_literals
+from .base import DEFAULT_ATTRS, Attrs
+
+__all__ = (
+ 'split_token_in_parts',
+ 'merge_attrs',
+)
+
+
+def split_token_in_parts(token):
+ """
+ Take a Token, and turn it in a list of tokens, by splitting
+ it on ':' (taking that as a separator.)
+ """
+ result = []
+ current = []
+ for part in token + (':', ):
+ if part == ':':
+ if current:
+ result.append(tuple(current))
+ current = []
+ else:
+ current.append(part)
+
+ return result
+
+
+def merge_attrs(list_of_attrs):
+ """
+ Take a list of :class:`.Attrs` instances and merge them into one.
+ Every `Attr` in the list can override the styling of the previous one.
+ """
+ result = DEFAULT_ATTRS
+
+ for attr in list_of_attrs:
+ result = Attrs(
+ color=attr.color or result.color,
+ bgcolor=attr.bgcolor or result.bgcolor,
+ bold=attr.bold or result.bold,
+ underline=attr.underline or result.underline,
+ italic=attr.italic or result.italic,
+ blink=attr.blink or result.blink,
+ reverse=attr.reverse or result.reverse)
+
+ return result
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/conemu_output.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/conemu_output.py
index 1b7e69fbd4..16b7bde8f3 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/conemu_output.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/conemu_output.py
@@ -32,8 +32,8 @@ class ConEmuOutput(object):
def __getattr__(self, name):
if name in ('get_size', 'get_rows_below_cursor_position',
'enable_mouse_support', 'disable_mouse_support',
- 'scroll_buffer_to_prompt', 'get_win32_screen_buffer_info',
- 'enable_bracketed_paste', 'disable_bracketed_paste'):
+ 'scroll_buffer_to_prompt', 'get_win32_screen_buffer_info',
+ 'enable_bracketed_paste', 'disable_bracketed_paste'):
return getattr(self.win32_output, name)
else:
return getattr(self.vt100_output, name)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_input.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_input.py
index a66afc28c6..74841312fa 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_input.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_input.py
@@ -9,8 +9,8 @@ import six
import termios
import tty
-from six.moves import range
-
+from six.moves import range
+
from ..keys import Keys
from ..key_binding.input_processor import KeyPress
@@ -93,7 +93,7 @@ ANSI_SEQUENCES = {
'\x1bOF': Keys.End,
'\x1b[3~': Keys.Delete,
'\x1b[3;2~': Keys.ShiftDelete, # xterm, gnome-terminal.
- '\x1b[3;5~': Keys.ControlDelete, # xterm, gnome-terminal.
+ '\x1b[3;5~': Keys.ControlDelete, # xterm, gnome-terminal.
'\x1b[1~': Keys.Home, # tmux
'\x1b[4~': Keys.End, # tmux
'\x1b[5~': Keys.PageUp,
@@ -107,11 +107,11 @@ ANSI_SEQUENCES = {
'\x1bOQ': Keys.F2,
'\x1bOR': Keys.F3,
'\x1bOS': Keys.F4,
- '\x1b[[A': Keys.F1, # Linux console.
- '\x1b[[B': Keys.F2, # Linux console.
- '\x1b[[C': Keys.F3, # Linux console.
- '\x1b[[D': Keys.F4, # Linux console.
- '\x1b[[E': Keys.F5, # Linux console.
+ '\x1b[[A': Keys.F1, # Linux console.
+ '\x1b[[B': Keys.F2, # Linux console.
+ '\x1b[[C': Keys.F3, # Linux console.
+ '\x1b[[D': Keys.F4, # Linux console.
+ '\x1b[[E': Keys.F5, # Linux console.
'\x1b[11~': Keys.F1, # rxvt-unicode
'\x1b[12~': Keys.F2, # rxvt-unicode
'\x1b[13~': Keys.F3, # rxvt-unicode
@@ -132,39 +132,39 @@ ANSI_SEQUENCES = {
'\x1b[32~': Keys.F18,
'\x1b[33~': Keys.F19,
'\x1b[34~': Keys.F20,
-
- # Xterm
- '\x1b[1;2P': Keys.F13,
- '\x1b[1;2Q': Keys.F14,
- # '\x1b[1;2R': Keys.F15, # Conflicts with CPR response.
- '\x1b[1;2S': Keys.F16,
- '\x1b[15;2~': Keys.F17,
- '\x1b[17;2~': Keys.F18,
- '\x1b[18;2~': Keys.F19,
- '\x1b[19;2~': Keys.F20,
- '\x1b[20;2~': Keys.F21,
- '\x1b[21;2~': Keys.F22,
- '\x1b[23;2~': Keys.F23,
- '\x1b[24;2~': Keys.F24,
-
+
+ # Xterm
+ '\x1b[1;2P': Keys.F13,
+ '\x1b[1;2Q': Keys.F14,
+ # '\x1b[1;2R': Keys.F15, # Conflicts with CPR response.
+ '\x1b[1;2S': Keys.F16,
+ '\x1b[15;2~': Keys.F17,
+ '\x1b[17;2~': Keys.F18,
+ '\x1b[18;2~': Keys.F19,
+ '\x1b[19;2~': Keys.F20,
+ '\x1b[20;2~': Keys.F21,
+ '\x1b[21;2~': Keys.F22,
+ '\x1b[23;2~': Keys.F23,
+ '\x1b[24;2~': Keys.F24,
+
'\x1b[1;5A': Keys.ControlUp, # Cursor Mode
'\x1b[1;5B': Keys.ControlDown, # Cursor Mode
'\x1b[1;5C': Keys.ControlRight, # Cursor Mode
'\x1b[1;5D': Keys.ControlLeft, # Cursor Mode
- '\x1b[1;2A': Keys.ShiftUp,
- '\x1b[1;2B': Keys.ShiftDown,
- '\x1b[1;2C': Keys.ShiftRight,
- '\x1b[1;2D': Keys.ShiftLeft,
-
- # Tmux sends following keystrokes when control+arrow is pressed, but for
- # Emacs ansi-term sends the same sequences for normal arrow keys. Consider
- # it a normal arrow press, because that's more important.
- '\x1bOA': Keys.Up,
- '\x1bOB': Keys.Down,
- '\x1bOC': Keys.Right,
- '\x1bOD': Keys.Left,
-
+ '\x1b[1;2A': Keys.ShiftUp,
+ '\x1b[1;2B': Keys.ShiftDown,
+ '\x1b[1;2C': Keys.ShiftRight,
+ '\x1b[1;2D': Keys.ShiftLeft,
+
+ # Tmux sends following keystrokes when control+arrow is pressed, but for
+ # Emacs ansi-term sends the same sequences for normal arrow keys. Consider
+ # it a normal arrow press, because that's more important.
+ '\x1bOA': Keys.Up,
+ '\x1bOB': Keys.Down,
+ '\x1bOC': Keys.Right,
+ '\x1bOD': Keys.Left,
+
'\x1b[5A': Keys.ControlUp,
'\x1b[5B': Keys.ControlDown,
'\x1b[5C': Keys.ControlRight,
@@ -188,11 +188,11 @@ ANSI_SEQUENCES = {
'\x1b[1;3C': (Keys.Escape, Keys.Right),
'\x1b[1;3A': (Keys.Escape, Keys.Up),
'\x1b[1;3B': (Keys.Escape, Keys.Down),
-
- # Sequences generated by numpad 5. Not sure what it means. (It doesn't
- # appear in 'infocmp'. Just ignore.
- '\x1b[E': Keys.Ignore, # Xterm.
- '\x1b[G': Keys.Ignore, # Linux console.
+
+ # Sequences generated by numpad 5. Not sure what it means. (It doesn't
+ # appear in 'infocmp'. Just ignore.
+ '\x1b[E': Keys.Ignore, # Xterm.
+ '\x1b[G': Keys.Ignore, # Linux console.
}
@@ -367,11 +367,11 @@ class InputStream(object):
# Quit bracketed paste mode and handle remaining input.
self._in_bracketed_paste = False
- remaining = self._paste_buffer[end_index + len(end_mark):]
+ remaining = self._paste_buffer[end_index + len(end_mark):]
self._paste_buffer = ''
- self.feed(remaining)
-
+ self.feed(remaining)
+
# Handle normal input character by character.
else:
for i, c in enumerate(data):
@@ -383,16 +383,16 @@ class InputStream(object):
else:
# Replace \r by \n. (Some clients send \r instead of \n
# when enter is pressed. E.g. telnet and some other
- # terminals.)
-
- # XXX: We should remove this in a future version. It *is*
- # now possible to recognise the difference.
- # (We remove ICRNL/INLCR/IGNCR below.)
- # However, this breaks IPython and maybe other applications,
- # because they bind ControlJ (\n) for handling the Enter key.
-
- # When this is removed, replace Enter=ControlJ by
- # Enter=ControlM in keys.py.
+ # terminals.)
+
+ # XXX: We should remove this in a future version. It *is*
+ # now possible to recognise the difference.
+ # (We remove ICRNL/INLCR/IGNCR below.)
+ # However, this breaks IPython and maybe other applications,
+ # because they bind ControlJ (\n) for handling the Enter key.
+
+ # When this is removed, replace Enter=ControlJ by
+ # Enter=ControlM in keys.py.
if c == '\r':
c = '\n'
self._input_parser.send(c)
@@ -425,40 +425,40 @@ class raw_mode(object):
with raw_mode(stdin):
''' the pseudo-terminal stdin is now used in raw mode '''
-
- We ignore errors when executing `tcgetattr` fails.
+
+ We ignore errors when executing `tcgetattr` fails.
"""
- # There are several reasons for ignoring errors:
- # 1. To avoid the "Inappropriate ioctl for device" crash if somebody would
- # execute this code (In a Python REPL, for instance):
- #
- # import os; f = open(os.devnull); os.dup2(f.fileno(), 0)
- #
- # The result is that the eventloop will stop correctly, because it has
- # to logic to quit when stdin is closed. However, we should not fail at
- # this point. See:
- # https://github.com/jonathanslenders/python-prompt-toolkit/pull/393
- # https://github.com/jonathanslenders/python-prompt-toolkit/issues/392
-
- # 2. Related, when stdin is an SSH pipe, and no full terminal was allocated.
- # See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/165
+ # There are several reasons for ignoring errors:
+ # 1. To avoid the "Inappropriate ioctl for device" crash if somebody would
+ # execute this code (In a Python REPL, for instance):
+ #
+ # import os; f = open(os.devnull); os.dup2(f.fileno(), 0)
+ #
+ # The result is that the eventloop will stop correctly, because it has
+ # to logic to quit when stdin is closed. However, we should not fail at
+ # this point. See:
+ # https://github.com/jonathanslenders/python-prompt-toolkit/pull/393
+ # https://github.com/jonathanslenders/python-prompt-toolkit/issues/392
+
+ # 2. Related, when stdin is an SSH pipe, and no full terminal was allocated.
+ # See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/165
def __init__(self, fileno):
self.fileno = fileno
- try:
- self.attrs_before = termios.tcgetattr(fileno)
- except termios.error:
- # Ignore attribute errors.
- self.attrs_before = None
+ try:
+ self.attrs_before = termios.tcgetattr(fileno)
+ except termios.error:
+ # Ignore attribute errors.
+ self.attrs_before = None
def __enter__(self):
# NOTE: On os X systems, using pty.setraw() fails. Therefor we are using this:
- try:
- newattr = termios.tcgetattr(self.fileno)
- except termios.error:
- pass
- else:
- newattr[tty.LFLAG] = self._patch_lflag(newattr[tty.LFLAG])
- newattr[tty.IFLAG] = self._patch_iflag(newattr[tty.IFLAG])
+ try:
+ newattr = termios.tcgetattr(self.fileno)
+ except termios.error:
+ pass
+ else:
+ newattr[tty.LFLAG] = self._patch_lflag(newattr[tty.LFLAG])
+ newattr[tty.IFLAG] = self._patch_iflag(newattr[tty.IFLAG])
# VMIN defines the number of characters read at a time in
# non-canonical mode. It seems to default to 1 on Linux, but on
@@ -467,54 +467,54 @@ class raw_mode(object):
# defaults to ASCII EOT = Ctrl-D = 4.)
newattr[tty.CC][termios.VMIN] = 1
- termios.tcsetattr(self.fileno, termios.TCSANOW, newattr)
+ termios.tcsetattr(self.fileno, termios.TCSANOW, newattr)
- # Put the terminal in cursor mode. (Instead of application mode.)
- os.write(self.fileno, b'\x1b[?1l')
+ # Put the terminal in cursor mode. (Instead of application mode.)
+ os.write(self.fileno, b'\x1b[?1l')
- @classmethod
- def _patch_lflag(cls, attrs):
+ @classmethod
+ def _patch_lflag(cls, attrs):
return attrs & ~(termios.ECHO | termios.ICANON | termios.IEXTEN | termios.ISIG)
- @classmethod
- def _patch_iflag(cls, attrs):
- return attrs & ~(
- # Disable XON/XOFF flow control on output and input.
- # (Don't capture Ctrl-S and Ctrl-Q.)
- # Like executing: "stty -ixon."
- termios.IXON | termios.IXOFF |
-
- # Don't translate carriage return into newline on input.
- termios.ICRNL | termios.INLCR | termios.IGNCR
- )
-
+ @classmethod
+ def _patch_iflag(cls, attrs):
+ return attrs & ~(
+ # Disable XON/XOFF flow control on output and input.
+ # (Don't capture Ctrl-S and Ctrl-Q.)
+ # Like executing: "stty -ixon."
+ termios.IXON | termios.IXOFF |
+
+ # Don't translate carriage return into newline on input.
+ termios.ICRNL | termios.INLCR | termios.IGNCR
+ )
+
def __exit__(self, *a, **kw):
- if self.attrs_before is not None:
- try:
- termios.tcsetattr(self.fileno, termios.TCSANOW, self.attrs_before)
- except termios.error:
- pass
+ if self.attrs_before is not None:
+ try:
+ termios.tcsetattr(self.fileno, termios.TCSANOW, self.attrs_before)
+ except termios.error:
+ pass
- # # Put the terminal in application mode.
- # self._stdout.write('\x1b[?1h')
+ # # Put the terminal in application mode.
+ # self._stdout.write('\x1b[?1h')
class cooked_mode(raw_mode):
"""
- The opposide of ``raw_mode``, used when we need cooked mode inside a
- `raw_mode` block. Used in `CommandLineInterface.run_in_terminal`.::
+ The opposide of ``raw_mode``, used when we need cooked mode inside a
+ `raw_mode` block. Used in `CommandLineInterface.run_in_terminal`.::
with cooked_mode(stdin):
''' the pseudo-terminal stdin is now used in cooked mode. '''
"""
- @classmethod
- def _patch_lflag(cls, attrs):
+ @classmethod
+ def _patch_lflag(cls, attrs):
return attrs | (termios.ECHO | termios.ICANON | termios.IEXTEN | termios.ISIG)
-
- @classmethod
- def _patch_iflag(cls, attrs):
- # Turn the ICRNL flag back on. (Without this, calling `input()` in
- # run_in_terminal doesn't work and displays ^M instead. Ptpython
- # evaluates commands using `run_in_terminal`, so it's important that
- # they translate ^M back into ^J.)
- return attrs | termios.ICRNL
+
+ @classmethod
+ def _patch_iflag(cls, attrs):
+ # Turn the ICRNL flag back on. (Without this, calling `input()` in
+ # run_in_terminal doesn't work and displays ^M instead. Ptpython
+ # evaluates commands using `run_in_terminal`, so it's important that
+ # they translate ^M back into ^J.)
+ return attrs | termios.ICRNL
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py
index f9ebbcbb24..b800aaacec 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/vt100_output.py
@@ -1,22 +1,22 @@
-"""
-Output for vt100 terminals.
-
-A lot of thanks, regarding outputting of colors, goes to the Pygments project:
-(We don't rely on Pygments anymore, because many things are very custom, and
-everything has been highly optimized.)
-http://pygments.org/
-"""
+"""
+Output for vt100 terminals.
+
+A lot of thanks, regarding outputting of colors, goes to the Pygments project:
+(We don't rely on Pygments anymore, because many things are very custom, and
+everything has been highly optimized.)
+http://pygments.org/
+"""
from __future__ import unicode_literals
-from prompt_toolkit.filters import to_simple_filter, Condition
+from prompt_toolkit.filters import to_simple_filter, Condition
from prompt_toolkit.layout.screen import Size
from prompt_toolkit.renderer import Output
from prompt_toolkit.styles import ANSI_COLOR_NAMES
-from six.moves import range
+from six.moves import range
import array
import errno
-import os
+import os
import six
__all__ = (
@@ -25,219 +25,219 @@ __all__ = (
FG_ANSI_COLORS = {
- 'ansidefault': 39,
+ 'ansidefault': 39,
# Low intensity.
'ansiblack': 30,
- 'ansidarkred': 31,
- 'ansidarkgreen': 32,
- 'ansibrown': 33,
- 'ansidarkblue': 34,
- 'ansipurple': 35,
- 'ansiteal': 36,
+ 'ansidarkred': 31,
+ 'ansidarkgreen': 32,
+ 'ansibrown': 33,
+ 'ansidarkblue': 34,
+ 'ansipurple': 35,
+ 'ansiteal': 36,
'ansilightgray': 37,
# High intensity.
'ansidarkgray': 90,
- 'ansired': 91,
- 'ansigreen': 92,
- 'ansiyellow': 93,
- 'ansiblue': 94,
- 'ansifuchsia': 95,
- 'ansiturquoise': 96,
+ 'ansired': 91,
+ 'ansigreen': 92,
+ 'ansiyellow': 93,
+ 'ansiblue': 94,
+ 'ansifuchsia': 95,
+ 'ansiturquoise': 96,
'ansiwhite': 97,
}
BG_ANSI_COLORS = {
- 'ansidefault': 49,
+ 'ansidefault': 49,
# Low intensity.
'ansiblack': 40,
- 'ansidarkred': 41,
- 'ansidarkgreen': 42,
- 'ansibrown': 43,
- 'ansidarkblue': 44,
- 'ansipurple': 45,
- 'ansiteal': 46,
+ 'ansidarkred': 41,
+ 'ansidarkgreen': 42,
+ 'ansibrown': 43,
+ 'ansidarkblue': 44,
+ 'ansipurple': 45,
+ 'ansiteal': 46,
'ansilightgray': 47,
# High intensity.
'ansidarkgray': 100,
- 'ansired': 101,
- 'ansigreen': 102,
- 'ansiyellow': 103,
- 'ansiblue': 104,
- 'ansifuchsia': 105,
- 'ansiturquoise': 106,
+ 'ansired': 101,
+ 'ansigreen': 102,
+ 'ansiyellow': 103,
+ 'ansiblue': 104,
+ 'ansifuchsia': 105,
+ 'ansiturquoise': 106,
'ansiwhite': 107,
}
-
-ANSI_COLORS_TO_RGB = {
- 'ansidefault': (0x00, 0x00, 0x00), # Don't use, 'default' doesn't really have a value.
- 'ansiblack': (0x00, 0x00, 0x00),
- 'ansidarkgray': (0x7f, 0x7f, 0x7f),
- 'ansiwhite': (0xff, 0xff, 0xff),
- 'ansilightgray': (0xe5, 0xe5, 0xe5),
-
- # Low intensity.
- 'ansidarkred': (0xcd, 0x00, 0x00),
- 'ansidarkgreen': (0x00, 0xcd, 0x00),
- 'ansibrown': (0xcd, 0xcd, 0x00),
- 'ansidarkblue': (0x00, 0x00, 0xcd),
- 'ansipurple': (0xcd, 0x00, 0xcd),
- 'ansiteal': (0x00, 0xcd, 0xcd),
-
- # High intensity.
- 'ansired': (0xff, 0x00, 0x00),
- 'ansigreen': (0x00, 0xff, 0x00),
- 'ansiyellow': (0xff, 0xff, 0x00),
- 'ansiblue': (0x00, 0x00, 0xff),
- 'ansifuchsia': (0xff, 0x00, 0xff),
- 'ansiturquoise': (0x00, 0xff, 0xff),
-}
-
-
+
+ANSI_COLORS_TO_RGB = {
+ 'ansidefault': (0x00, 0x00, 0x00), # Don't use, 'default' doesn't really have a value.
+ 'ansiblack': (0x00, 0x00, 0x00),
+ 'ansidarkgray': (0x7f, 0x7f, 0x7f),
+ 'ansiwhite': (0xff, 0xff, 0xff),
+ 'ansilightgray': (0xe5, 0xe5, 0xe5),
+
+ # Low intensity.
+ 'ansidarkred': (0xcd, 0x00, 0x00),
+ 'ansidarkgreen': (0x00, 0xcd, 0x00),
+ 'ansibrown': (0xcd, 0xcd, 0x00),
+ 'ansidarkblue': (0x00, 0x00, 0xcd),
+ 'ansipurple': (0xcd, 0x00, 0xcd),
+ 'ansiteal': (0x00, 0xcd, 0xcd),
+
+ # High intensity.
+ 'ansired': (0xff, 0x00, 0x00),
+ 'ansigreen': (0x00, 0xff, 0x00),
+ 'ansiyellow': (0xff, 0xff, 0x00),
+ 'ansiblue': (0x00, 0x00, 0xff),
+ 'ansifuchsia': (0xff, 0x00, 0xff),
+ 'ansiturquoise': (0x00, 0xff, 0xff),
+}
+
+
assert set(FG_ANSI_COLORS) == set(ANSI_COLOR_NAMES)
assert set(BG_ANSI_COLORS) == set(ANSI_COLOR_NAMES)
-assert set(ANSI_COLORS_TO_RGB) == set(ANSI_COLOR_NAMES)
-
-
-def _get_closest_ansi_color(r, g, b, exclude=()):
- """
- Find closest ANSI color. Return it by name.
-
- :param r: Red (Between 0 and 255.)
- :param g: Green (Between 0 and 255.)
- :param b: Blue (Between 0 and 255.)
- :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.)
- """
- assert isinstance(exclude, tuple)
-
- # When we have a bit of saturation, avoid the gray-like colors, otherwise,
- # too often the distance to the gray color is less.
- saturation = abs(r - g) + abs(g - b) + abs(b - r) # Between 0..510
-
- if saturation > 30:
- exclude += ('ansilightgray', 'ansidarkgray', 'ansiwhite', 'ansiblack')
-
- # Take the closest color.
- # (Thanks to Pygments for this part.)
- distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
- match = 'ansidefault'
-
- for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items():
- if name != 'ansidefault' and name not in exclude:
- d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2
-
- if d < distance:
- match = name
- distance = d
-
- return match
-
-
-class _16ColorCache(dict):
- """
- Cache which maps (r, g, b) tuples to 16 ansi colors.
-
- :param bg: Cache for background colors, instead of foreground.
- """
- def __init__(self, bg=False):
- assert isinstance(bg, bool)
- self.bg = bg
-
- def get_code(self, value, exclude=()):
- """
- Return a (ansi_code, ansi_name) tuple. (E.g. ``(44, 'ansiblue')``.) for
- a given (r,g,b) value.
- """
- key = (value, exclude)
- if key not in self:
- self[key] = self._get(value, exclude)
- return self[key]
-
- def _get(self, value, exclude=()):
- r, g, b = value
- match = _get_closest_ansi_color(r, g, b, exclude=exclude)
-
- # Turn color name into code.
- if self.bg:
- code = BG_ANSI_COLORS[match]
- else:
- code = FG_ANSI_COLORS[match]
-
- self[value] = code
- return code, match
-
-
-class _256ColorCache(dict):
- """
- Cach which maps (r, g, b) tuples to 256 colors.
- """
- def __init__(self):
- # Build color table.
- colors = []
-
- # colors 0..15: 16 basic colors
- colors.append((0x00, 0x00, 0x00)) # 0
- colors.append((0xcd, 0x00, 0x00)) # 1
- colors.append((0x00, 0xcd, 0x00)) # 2
- colors.append((0xcd, 0xcd, 0x00)) # 3
- colors.append((0x00, 0x00, 0xee)) # 4
- colors.append((0xcd, 0x00, 0xcd)) # 5
- colors.append((0x00, 0xcd, 0xcd)) # 6
- colors.append((0xe5, 0xe5, 0xe5)) # 7
- colors.append((0x7f, 0x7f, 0x7f)) # 8
- colors.append((0xff, 0x00, 0x00)) # 9
- colors.append((0x00, 0xff, 0x00)) # 10
- colors.append((0xff, 0xff, 0x00)) # 11
- colors.append((0x5c, 0x5c, 0xff)) # 12
- colors.append((0xff, 0x00, 0xff)) # 13
- colors.append((0x00, 0xff, 0xff)) # 14
- colors.append((0xff, 0xff, 0xff)) # 15
-
- # colors 16..232: the 6x6x6 color cube
- valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
-
- for i in range(217):
- r = valuerange[(i // 36) % 6]
- g = valuerange[(i // 6) % 6]
- b = valuerange[i % 6]
- colors.append((r, g, b))
-
- # colors 233..253: grayscale
- for i in range(1, 22):
- v = 8 + i * 10
- colors.append((v, v, v))
-
- self.colors = colors
-
- def __missing__(self, value):
- r, g, b = value
-
- # Find closest color.
- # (Thanks to Pygments for this!)
- distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
- match = 0
-
- for i, (r2, g2, b2) in enumerate(self.colors):
- d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2
-
- if d < distance:
- match = i
- distance = d
-
- # Turn color name into code.
- self[value] = match
- return match
-
-
-_16_fg_colors = _16ColorCache(bg=False)
-_16_bg_colors = _16ColorCache(bg=True)
-_256_colors = _256ColorCache()
-
-
+assert set(ANSI_COLORS_TO_RGB) == set(ANSI_COLOR_NAMES)
+
+
+def _get_closest_ansi_color(r, g, b, exclude=()):
+ """
+ Find closest ANSI color. Return it by name.
+
+ :param r: Red (Between 0 and 255.)
+ :param g: Green (Between 0 and 255.)
+ :param b: Blue (Between 0 and 255.)
+ :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.)
+ """
+ assert isinstance(exclude, tuple)
+
+ # When we have a bit of saturation, avoid the gray-like colors, otherwise,
+ # too often the distance to the gray color is less.
+ saturation = abs(r - g) + abs(g - b) + abs(b - r) # Between 0..510
+
+ if saturation > 30:
+ exclude += ('ansilightgray', 'ansidarkgray', 'ansiwhite', 'ansiblack')
+
+ # Take the closest color.
+ # (Thanks to Pygments for this part.)
+ distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
+ match = 'ansidefault'
+
+ for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items():
+ if name != 'ansidefault' and name not in exclude:
+ d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2
+
+ if d < distance:
+ match = name
+ distance = d
+
+ return match
+
+
+class _16ColorCache(dict):
+ """
+ Cache which maps (r, g, b) tuples to 16 ansi colors.
+
+ :param bg: Cache for background colors, instead of foreground.
+ """
+ def __init__(self, bg=False):
+ assert isinstance(bg, bool)
+ self.bg = bg
+
+ def get_code(self, value, exclude=()):
+ """
+ Return a (ansi_code, ansi_name) tuple. (E.g. ``(44, 'ansiblue')``.) for
+ a given (r,g,b) value.
+ """
+ key = (value, exclude)
+ if key not in self:
+ self[key] = self._get(value, exclude)
+ return self[key]
+
+ def _get(self, value, exclude=()):
+ r, g, b = value
+ match = _get_closest_ansi_color(r, g, b, exclude=exclude)
+
+ # Turn color name into code.
+ if self.bg:
+ code = BG_ANSI_COLORS[match]
+ else:
+ code = FG_ANSI_COLORS[match]
+
+ self[value] = code
+ return code, match
+
+
+class _256ColorCache(dict):
+ """
+ Cach which maps (r, g, b) tuples to 256 colors.
+ """
+ def __init__(self):
+ # Build color table.
+ colors = []
+
+ # colors 0..15: 16 basic colors
+ colors.append((0x00, 0x00, 0x00)) # 0
+ colors.append((0xcd, 0x00, 0x00)) # 1
+ colors.append((0x00, 0xcd, 0x00)) # 2
+ colors.append((0xcd, 0xcd, 0x00)) # 3
+ colors.append((0x00, 0x00, 0xee)) # 4
+ colors.append((0xcd, 0x00, 0xcd)) # 5
+ colors.append((0x00, 0xcd, 0xcd)) # 6
+ colors.append((0xe5, 0xe5, 0xe5)) # 7
+ colors.append((0x7f, 0x7f, 0x7f)) # 8
+ colors.append((0xff, 0x00, 0x00)) # 9
+ colors.append((0x00, 0xff, 0x00)) # 10
+ colors.append((0xff, 0xff, 0x00)) # 11
+ colors.append((0x5c, 0x5c, 0xff)) # 12
+ colors.append((0xff, 0x00, 0xff)) # 13
+ colors.append((0x00, 0xff, 0xff)) # 14
+ colors.append((0xff, 0xff, 0xff)) # 15
+
+ # colors 16..232: the 6x6x6 color cube
+ valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
+
+ for i in range(217):
+ r = valuerange[(i // 36) % 6]
+ g = valuerange[(i // 6) % 6]
+ b = valuerange[i % 6]
+ colors.append((r, g, b))
+
+ # colors 233..253: grayscale
+ for i in range(1, 22):
+ v = 8 + i * 10
+ colors.append((v, v, v))
+
+ self.colors = colors
+
+ def __missing__(self, value):
+ r, g, b = value
+
+ # Find closest color.
+ # (Thanks to Pygments for this!)
+ distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
+ match = 0
+
+ for i, (r2, g2, b2) in enumerate(self.colors):
+ d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2
+
+ if d < distance:
+ match = i
+ distance = d
+
+ # Turn color name into code.
+ self[value] = match
+ return match
+
+
+_16_fg_colors = _16ColorCache(bg=False)
+_16_bg_colors = _16ColorCache(bg=True)
+_256_colors = _256ColorCache()
+
+
class _EscapeCodeCache(dict):
"""
Cache for VT100 escape codes. It maps
@@ -245,17 +245,17 @@ class _EscapeCodeCache(dict):
:param true_color: When True, use 24bit colors instead of 256 colors.
"""
- def __init__(self, true_color=False, ansi_colors_only=False):
+ def __init__(self, true_color=False, ansi_colors_only=False):
assert isinstance(true_color, bool)
self.true_color = true_color
- self.ansi_colors_only = to_simple_filter(ansi_colors_only)
+ self.ansi_colors_only = to_simple_filter(ansi_colors_only)
def __missing__(self, attrs):
fgcolor, bgcolor, bold, underline, italic, blink, reverse = attrs
parts = []
- parts.extend(self._colors_to_code(fgcolor, bgcolor))
-
+ parts.extend(self._colors_to_code(fgcolor, bgcolor))
+
if bold:
parts.append('1')
if italic:
@@ -275,72 +275,72 @@ class _EscapeCodeCache(dict):
self[attrs] = result
return result
- def _color_name_to_rgb(self, color):
- " Turn 'ffffff', into (0xff, 0xff, 0xff). "
- try:
- rgb = int(color, 16)
- except ValueError:
- raise
- else:
+ def _color_name_to_rgb(self, color):
+ " Turn 'ffffff', into (0xff, 0xff, 0xff). "
+ try:
+ rgb = int(color, 16)
+ except ValueError:
+ raise
+ else:
r = (rgb >> 16) & 0xff
g = (rgb >> 8) & 0xff
b = rgb & 0xff
- return r, g, b
-
- def _colors_to_code(self, fg_color, bg_color):
- " Return a tuple with the vt100 values that represent this color. "
- # When requesting ANSI colors only, and both fg/bg color were converted
- # to ANSI, ensure that the foreground and background color are not the
- # same. (Unless they were explicitely defined to be the same color.)
- fg_ansi = [()]
-
- def get(color, bg):
- table = BG_ANSI_COLORS if bg else FG_ANSI_COLORS
-
- if color is None:
- return ()
-
- # 16 ANSI colors. (Given by name.)
- elif color in table:
- return (table[color], )
-
- # RGB colors. (Defined as 'ffffff'.)
- else:
- try:
- rgb = self._color_name_to_rgb(color)
- except ValueError:
- return ()
-
- # When only 16 colors are supported, use that.
- if self.ansi_colors_only():
- if bg: # Background.
- if fg_color != bg_color:
- exclude = (fg_ansi[0], )
- else:
- exclude = ()
- code, name = _16_bg_colors.get_code(rgb, exclude=exclude)
- return (code, )
- else: # Foreground.
- code, name = _16_fg_colors.get_code(rgb)
- fg_ansi[0] = name
- return (code, )
-
- # True colors. (Only when this feature is enabled.)
- elif self.true_color:
- r, g, b = rgb
- return (48 if bg else 38, 2, r, g, b)
-
- # 256 RGB colors.
- else:
- return (48 if bg else 38, 5, _256_colors[rgb])
-
- result = []
- result.extend(get(fg_color, False))
- result.extend(get(bg_color, True))
-
- return map(six.text_type, result)
-
-
+ return r, g, b
+
+ def _colors_to_code(self, fg_color, bg_color):
+ " Return a tuple with the vt100 values that represent this color. "
+ # When requesting ANSI colors only, and both fg/bg color were converted
+ # to ANSI, ensure that the foreground and background color are not the
+ # same. (Unless they were explicitely defined to be the same color.)
+ fg_ansi = [()]
+
+ def get(color, bg):
+ table = BG_ANSI_COLORS if bg else FG_ANSI_COLORS
+
+ if color is None:
+ return ()
+
+ # 16 ANSI colors. (Given by name.)
+ elif color in table:
+ return (table[color], )
+
+ # RGB colors. (Defined as 'ffffff'.)
+ else:
+ try:
+ rgb = self._color_name_to_rgb(color)
+ except ValueError:
+ return ()
+
+ # When only 16 colors are supported, use that.
+ if self.ansi_colors_only():
+ if bg: # Background.
+ if fg_color != bg_color:
+ exclude = (fg_ansi[0], )
+ else:
+ exclude = ()
+ code, name = _16_bg_colors.get_code(rgb, exclude=exclude)
+ return (code, )
+ else: # Foreground.
+ code, name = _16_fg_colors.get_code(rgb)
+ fg_ansi[0] = name
+ return (code, )
+
+ # True colors. (Only when this feature is enabled.)
+ elif self.true_color:
+ r, g, b = rgb
+ return (48 if bg else 38, 2, r, g, b)
+
+ # 256 RGB colors.
+ else:
+ return (48 if bg else 38, 5, _256_colors[rgb])
+
+ result = []
+ result.extend(get(fg_color, False))
+ result.extend(get(bg_color, True))
+
+ return map(six.text_type, result)
+
+
def _get_size(fileno):
# Thanks to fabric (fabfile.org), and
# http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/
@@ -356,13 +356,13 @@ def _get_size(fileno):
import termios
# Buffer for the C call
- buf = array.array(b'h' if six.PY2 else u'h', [0, 0, 0, 0])
+ buf = array.array(b'h' if six.PY2 else u'h', [0, 0, 0, 0])
# Do TIOCGWINSZ (Get)
- # Note: We should not pass 'True' as a fourth parameter to 'ioctl'. (True
- # is the default.) This causes segmentation faults on some systems.
- # See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/364
- fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf)
+ # Note: We should not pass 'True' as a fourth parameter to 'ioctl'. (True
+ # is the default.) This causes segmentation faults on some systems.
+ # See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/364
+ fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf)
# Return rows, cols
return buf[0], buf[1]
@@ -371,74 +371,74 @@ def _get_size(fileno):
class Vt100_Output(Output):
"""
:param get_size: A callable which returns the `Size` of the output terminal.
- :param stdout: Any object with has a `write` and `flush` method + an 'encoding' property.
+ :param stdout: Any object with has a `write` and `flush` method + an 'encoding' property.
:param true_color: Use 24bit color instead of 256 colors. (Can be a :class:`SimpleFilter`.)
- When `ansi_colors_only` is set, only 16 colors are used.
- :param ansi_colors_only: Restrict to 16 ANSI colors only.
- :param term: The terminal environment variable. (xterm, xterm-256color, linux, ...)
- :param write_binary: Encode the output before writing it. If `True` (the
- default), the `stdout` object is supposed to expose an `encoding` attribute.
+ When `ansi_colors_only` is set, only 16 colors are used.
+ :param ansi_colors_only: Restrict to 16 ANSI colors only.
+ :param term: The terminal environment variable. (xterm, xterm-256color, linux, ...)
+ :param write_binary: Encode the output before writing it. If `True` (the
+ default), the `stdout` object is supposed to expose an `encoding` attribute.
"""
- def __init__(self, stdout, get_size, true_color=False,
- ansi_colors_only=None, term=None, write_binary=True):
- assert callable(get_size)
- assert term is None or isinstance(term, six.text_type)
- assert all(hasattr(stdout, a) for a in ('write', 'flush'))
-
- if write_binary:
- assert hasattr(stdout, 'encoding')
-
+ def __init__(self, stdout, get_size, true_color=False,
+ ansi_colors_only=None, term=None, write_binary=True):
+ assert callable(get_size)
+ assert term is None or isinstance(term, six.text_type)
+ assert all(hasattr(stdout, a) for a in ('write', 'flush'))
+
+ if write_binary:
+ assert hasattr(stdout, 'encoding')
+
self._buffer = []
self.stdout = stdout
- self.write_binary = write_binary
+ self.write_binary = write_binary
self.get_size = get_size
self.true_color = to_simple_filter(true_color)
- self.term = term or 'xterm'
-
- # ANSI colors only?
- if ansi_colors_only is None:
- # When not given, use the following default.
- ANSI_COLORS_ONLY = bool(os.environ.get(
- 'PROMPT_TOOLKIT_ANSI_COLORS_ONLY', False))
-
- @Condition
- def ansi_colors_only():
- return ANSI_COLORS_ONLY or term in ('linux', 'eterm-color')
- else:
- ansi_colors_only = to_simple_filter(ansi_colors_only)
-
- self.ansi_colors_only = ansi_colors_only
-
- # Cache for escape codes.
- self._escape_code_cache = _EscapeCodeCache(ansi_colors_only=ansi_colors_only)
- self._escape_code_cache_true_color = _EscapeCodeCache(
- true_color=True, ansi_colors_only=ansi_colors_only)
-
+ self.term = term or 'xterm'
+
+ # ANSI colors only?
+ if ansi_colors_only is None:
+ # When not given, use the following default.
+ ANSI_COLORS_ONLY = bool(os.environ.get(
+ 'PROMPT_TOOLKIT_ANSI_COLORS_ONLY', False))
+
+ @Condition
+ def ansi_colors_only():
+ return ANSI_COLORS_ONLY or term in ('linux', 'eterm-color')
+ else:
+ ansi_colors_only = to_simple_filter(ansi_colors_only)
+
+ self.ansi_colors_only = ansi_colors_only
+
+ # Cache for escape codes.
+ self._escape_code_cache = _EscapeCodeCache(ansi_colors_only=ansi_colors_only)
+ self._escape_code_cache_true_color = _EscapeCodeCache(
+ true_color=True, ansi_colors_only=ansi_colors_only)
+
@classmethod
- def from_pty(cls, stdout, true_color=False, ansi_colors_only=None, term=None):
+ def from_pty(cls, stdout, true_color=False, ansi_colors_only=None, term=None):
"""
Create an Output class from a pseudo terminal.
(This will take the dimensions by reading the pseudo
terminal attributes.)
"""
- assert stdout.isatty()
+ assert stdout.isatty()
def get_size():
rows, columns = _get_size(stdout.fileno())
# If terminal (incorrectly) reports its size as 0, pick a reasonable default.
# See https://github.com/ipython/ipython/issues/10071
return Size(rows=(rows or 24), columns=(columns or 80))
- return cls(stdout, get_size, true_color=true_color,
- ansi_colors_only=ansi_colors_only, term=term)
-
- def fileno(self):
- " Return file descriptor. "
- return self.stdout.fileno()
-
- def encoding(self):
- " Return encoding used for stdout. "
- return self.stdout.encoding
-
+ return cls(stdout, get_size, true_color=true_color,
+ ansi_colors_only=ansi_colors_only, term=term)
+
+ def fileno(self):
+ " Return file descriptor. "
+ return self.stdout.fileno()
+
+ def encoding(self):
+ " Return encoding used for stdout. "
+ return self.stdout.encoding
+
def write_raw(self, data):
"""
Write raw data to output.
@@ -456,8 +456,8 @@ class Vt100_Output(Output):
"""
Set terminal title.
"""
- if self.term not in ('linux', 'eterm-color'): # Not supported by the Linux console.
- self.write_raw('\x1b]2;%s\x07' % title.replace('\x1b', '').replace('\x07', ''))
+ if self.term not in ('linux', 'eterm-color'): # Not supported by the Linux console.
+ self.write_raw('\x1b]2;%s\x07' % title.replace('\x1b', '').replace('\x07', ''))
def clear_title(self):
self.set_title('')
@@ -514,10 +514,10 @@ class Vt100_Output(Output):
:param attrs: `Attrs` instance.
"""
- if self.true_color() and not self.ansi_colors_only():
- self.write_raw(self._escape_code_cache_true_color[attrs])
+ if self.true_color() and not self.ansi_colors_only():
+ self.write_raw(self._escape_code_cache_true_color[attrs])
else:
- self.write_raw(self._escape_code_cache[attrs])
+ self.write_raw(self._escape_code_cache[attrs])
def disable_autowrap(self):
self.write_raw('\x1b[?7l')
@@ -537,7 +537,7 @@ class Vt100_Output(Output):
def cursor_up(self, amount):
if amount == 0:
- pass
+ pass
elif amount == 1:
self.write_raw('\x1b[A')
else:
@@ -545,7 +545,7 @@ class Vt100_Output(Output):
def cursor_down(self, amount):
if amount == 0:
- pass
+ pass
elif amount == 1:
# Note: Not the same as '\n', '\n' can cause the window content to
# scroll.
@@ -555,7 +555,7 @@ class Vt100_Output(Output):
def cursor_forward(self, amount):
if amount == 0:
- pass
+ pass
elif amount == 1:
self.write_raw('\x1b[C')
else:
@@ -563,7 +563,7 @@ class Vt100_Output(Output):
def cursor_backward(self, amount):
if amount == 0:
- pass
+ pass
elif amount == 1:
self.write_raw('\b') # '\x1b[D'
else:
@@ -590,11 +590,11 @@ class Vt100_Output(Output):
# UnicodeEncodeError crashes. E.g. u'\xb7' does not appear in 'ascii'.)
# My Arch Linux installation of july 2015 reported 'ANSI_X3.4-1968'
# for sys.stdout.encoding in xterm.
- if self.write_binary:
- if hasattr(self.stdout, 'buffer'):
- out = self.stdout.buffer # Py3.
- else:
- out = self.stdout
+ if self.write_binary:
+ if hasattr(self.stdout, 'buffer'):
+ out = self.stdout.buffer # Py3.
+ else:
+ out = self.stdout
out.write(data.encode(self.stdout.encoding or 'utf-8', 'replace'))
else:
self.stdout.write(data)
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_input.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_input.py
index 74a7decd61..410e5fa517 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_input.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_input.py
@@ -1,18 +1,18 @@
-from __future__ import unicode_literals
+from __future__ import unicode_literals
from ctypes import windll, pointer
from ctypes.wintypes import DWORD, HANDLE
-from six.moves import range
+from six.moves import range
from prompt_toolkit.key_binding.input_processor import KeyPress
from prompt_toolkit.keys import Keys
-from prompt_toolkit.mouse_events import MouseEventType
+from prompt_toolkit.mouse_events import MouseEventType
from prompt_toolkit.win32_types import EventTypes, KEY_EVENT_RECORD, MOUSE_EVENT_RECORD, INPUT_RECORD, STD_INPUT_HANDLE
-import msvcrt
-import os
-import sys
-import six
-
+import msvcrt
+import os
+import sys
+import six
+
__all__ = (
'ConsoleInputReader',
'raw_mode',
@@ -21,10 +21,10 @@ __all__ = (
class ConsoleInputReader(object):
- """
- :param recognize_paste: When True, try to discover paste actions and turn
- the event into a BracketedPaste.
- """
+ """
+ :param recognize_paste: When True, try to discover paste actions and turn
+ the event into a BracketedPaste.
+ """
# Keys with character data.
mappings = {
b'\x1b': Keys.Escape,
@@ -104,70 +104,70 @@ class ConsoleInputReader(object):
LEFT_CTRL_PRESSED = 0x0008
RIGHT_CTRL_PRESSED = 0x0004
- def __init__(self, recognize_paste=True):
- self._fdcon = None
- self.recognize_paste = recognize_paste
+ def __init__(self, recognize_paste=True):
+ self._fdcon = None
+ self.recognize_paste = recognize_paste
- # When stdin is a tty, use that handle, otherwise, create a handle from
- # CONIN$.
- if sys.stdin.isatty():
+ # When stdin is a tty, use that handle, otherwise, create a handle from
+ # CONIN$.
+ if sys.stdin.isatty():
self.handle = HANDLE(windll.kernel32.GetStdHandle(STD_INPUT_HANDLE))
- else:
- self._fdcon = os.open('CONIN$', os.O_RDWR | os.O_BINARY)
+ else:
+ self._fdcon = os.open('CONIN$', os.O_RDWR | os.O_BINARY)
self.handle = HANDLE(msvcrt.get_osfhandle(self._fdcon))
-
- def close(self):
- " Close fdcon. "
- if self._fdcon is not None:
- os.close(self._fdcon)
-
+
+ def close(self):
+ " Close fdcon. "
+ if self._fdcon is not None:
+ os.close(self._fdcon)
+
def read(self):
"""
- Return a list of `KeyPress` instances. It won't return anything when
- there was nothing to read. (This function doesn't block.)
+ Return a list of `KeyPress` instances. It won't return anything when
+ there was nothing to read. (This function doesn't block.)
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx
"""
- max_count = 2048 # Max events to read at the same time.
+ max_count = 2048 # Max events to read at the same time.
read = DWORD(0)
arrtype = INPUT_RECORD * max_count
input_records = arrtype()
# Get next batch of input event.
- windll.kernel32.ReadConsoleInputW(
- self.handle, pointer(input_records), max_count, pointer(read))
-
- # First, get all the keys from the input buffer, in order to determine
- # whether we should consider this a paste event or not.
- all_keys = list(self._get_keys(read, input_records))
-
- if self.recognize_paste and self._is_paste(all_keys):
- gen = iter(all_keys)
- for k in gen:
- # Pasting: if the current key consists of text or \n, turn it
- # into a BracketedPaste.
- data = []
- while k and (isinstance(k.key, six.text_type) or
- k.key == Keys.ControlJ):
- data.append(k.data)
- try:
- k = next(gen)
- except StopIteration:
- k = None
-
- if data:
- yield KeyPress(Keys.BracketedPaste, ''.join(data))
- if k is not None:
- yield k
- else:
- for k in all_keys:
- yield k
-
- def _get_keys(self, read, input_records):
- """
- Generator that yields `KeyPress` objects from the input records.
- """
+ windll.kernel32.ReadConsoleInputW(
+ self.handle, pointer(input_records), max_count, pointer(read))
+
+ # First, get all the keys from the input buffer, in order to determine
+ # whether we should consider this a paste event or not.
+ all_keys = list(self._get_keys(read, input_records))
+
+ if self.recognize_paste and self._is_paste(all_keys):
+ gen = iter(all_keys)
+ for k in gen:
+ # Pasting: if the current key consists of text or \n, turn it
+ # into a BracketedPaste.
+ data = []
+ while k and (isinstance(k.key, six.text_type) or
+ k.key == Keys.ControlJ):
+ data.append(k.data)
+ try:
+ k = next(gen)
+ except StopIteration:
+ k = None
+
+ if data:
+ yield KeyPress(Keys.BracketedPaste, ''.join(data))
+ if k is not None:
+ yield k
+ else:
+ for k in all_keys:
+ yield k
+
+ def _get_keys(self, read, input_records):
+ """
+ Generator that yields `KeyPress` objects from the input records.
+ """
for i in range(read.value):
ir = input_records[i]
@@ -181,35 +181,35 @@ class ConsoleInputReader(object):
# Process if this is a key event. (We also have mouse, menu and
# focus events.)
if type(ev) == KEY_EVENT_RECORD and ev.KeyDown:
- for key_press in self._event_to_key_presses(ev):
- yield key_press
+ for key_press in self._event_to_key_presses(ev):
+ yield key_press
elif type(ev) == MOUSE_EVENT_RECORD:
- for key_press in self._handle_mouse(ev):
- yield key_press
-
- @staticmethod
- def _is_paste(keys):
- """
- Return `True` when we should consider this list of keys as a paste
- event. Pasted text on windows will be turned into a
- `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably
- the best possible way to detect pasting of text and handle that
- correctly.)
- """
- # Consider paste when it contains at least one newline and at least one
- # other character.
- text_count = 0
- newline_count = 0
-
- for k in keys:
- if isinstance(k.key, six.text_type):
- text_count += 1
- if k.key == Keys.ControlJ:
- newline_count += 1
-
- return newline_count >= 1 and text_count > 1
-
+ for key_press in self._handle_mouse(ev):
+ yield key_press
+
+ @staticmethod
+ def _is_paste(keys):
+ """
+ Return `True` when we should consider this list of keys as a paste
+ event. Pasted text on windows will be turned into a
+ `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably
+ the best possible way to detect pasting of text and handle that
+ correctly.)
+ """
+ # Consider paste when it contains at least one newline and at least one
+ # other character.
+ text_count = 0
+ newline_count = 0
+
+ for k in keys:
+ if isinstance(k.key, six.text_type):
+ text_count += 1
+ if k.key == Keys.ControlJ:
+ newline_count += 1
+
+ return newline_count >= 1 and text_count > 1
+
def _event_to_key_presses(self, ev):
"""
For this `KEY_EVENT_RECORD`, return a list of `KeyPress` instances.
@@ -219,20 +219,20 @@ class ConsoleInputReader(object):
result = None
u_char = ev.uChar.UnicodeChar
- ascii_char = u_char.encode('utf-8')
+ ascii_char = u_char.encode('utf-8')
+
+ # NOTE: We don't use `ev.uChar.AsciiChar`. That appears to be latin-1
+ # encoded. See also:
+ # https://github.com/ipython/ipython/issues/10004
+ # https://github.com/jonathanslenders/python-prompt-toolkit/issues/389
- # NOTE: We don't use `ev.uChar.AsciiChar`. That appears to be latin-1
- # encoded. See also:
- # https://github.com/ipython/ipython/issues/10004
- # https://github.com/jonathanslenders/python-prompt-toolkit/issues/389
-
if u_char == '\x00':
if ev.VirtualKeyCode in self.keycodes:
result = KeyPress(self.keycodes[ev.VirtualKeyCode], '')
else:
if ascii_char in self.mappings:
- if self.mappings[ascii_char] == Keys.ControlJ:
- u_char = '\n' # Windows sends \n, turn into \r for unix compatibility.
+ if self.mappings[ascii_char] == Keys.ControlJ:
+ u_char = '\n' # Windows sends \n, turn into \r for unix compatibility.
result = KeyPress(self.mappings[ascii_char], u_char)
else:
result = KeyPress(u_char, u_char)
@@ -299,7 +299,7 @@ class ConsoleInputReader(object):
# Check event type.
if ev.ButtonState == FROM_LEFT_1ST_BUTTON_PRESSED:
# On a key press, generate both the mouse down and up event.
- for event_type in [MouseEventType.MOUSE_DOWN, MouseEventType.MOUSE_UP]:
+ for event_type in [MouseEventType.MOUSE_DOWN, MouseEventType.MOUSE_UP]:
data = ';'.join([
event_type,
str(ev.MousePosition.X),
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_output.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_output.py
index 577c61c130..d4dddbab42 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_output.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/terminal/win32_output.py
@@ -7,7 +7,7 @@ from prompt_toolkit.renderer import Output
from prompt_toolkit.styles import ANSI_COLOR_NAMES
from prompt_toolkit.win32_types import CONSOLE_SCREEN_BUFFER_INFO, STD_OUTPUT_HANDLE, STD_INPUT_HANDLE, COORD, SMALL_RECT
-import os
+import os
import six
__all__ = (
@@ -40,26 +40,26 @@ _DEBUG_RENDER_OUTPUT = False
_DEBUG_RENDER_OUTPUT_FILENAME = r'prompt-toolkit-windows-output.log'
-class NoConsoleScreenBufferError(Exception):
- """
- Raised when the application is not running inside a Windows Console, but
- the user tries to instantiate Win32Output.
- """
- def __init__(self):
- # Are we running in 'xterm' on Windows, like git-bash for instance?
- xterm = 'xterm' in os.environ.get('TERM', '')
-
- if xterm:
- message = ('Found %s, while expecting a Windows console. '
- 'Maybe try to run this program using "winpty" '
- 'or run it in cmd.exe instead. Or otherwise, '
- 'in case of Cygwin, use the Python executable '
- 'that is compiled for Cygwin.' % os.environ['TERM'])
- else:
- message = 'No Windows console found. Are you running cmd.exe?'
- super(NoConsoleScreenBufferError, self).__init__(message)
-
-
+class NoConsoleScreenBufferError(Exception):
+ """
+ Raised when the application is not running inside a Windows Console, but
+ the user tries to instantiate Win32Output.
+ """
+ def __init__(self):
+ # Are we running in 'xterm' on Windows, like git-bash for instance?
+ xterm = 'xterm' in os.environ.get('TERM', '')
+
+ if xterm:
+ message = ('Found %s, while expecting a Windows console. '
+ 'Maybe try to run this program using "winpty" '
+ 'or run it in cmd.exe instead. Or otherwise, '
+ 'in case of Cygwin, use the Python executable '
+ 'that is compiled for Cygwin.' % os.environ['TERM'])
+ else:
+ message = 'No Windows console found. Are you running cmd.exe?'
+ super(NoConsoleScreenBufferError, self).__init__(message)
+
+
class Win32Output(Output):
"""
I/O abstraction for rendering to Windows consoles.
@@ -76,21 +76,21 @@ class Win32Output(Output):
self.color_lookup_table = ColorLookupTable()
- # Remember the default console colors.
- info = self.get_win32_screen_buffer_info()
- self.default_attrs = info.wAttributes if info else 15
-
+ # Remember the default console colors.
+ info = self.get_win32_screen_buffer_info()
+ self.default_attrs = info.wAttributes if info else 15
+
if _DEBUG_RENDER_OUTPUT:
self.LOG = open(_DEBUG_RENDER_OUTPUT_FILENAME, 'ab')
- def fileno(self):
- " Return file descriptor. "
- return self.stdout.fileno()
-
- def encoding(self):
- " Return encoding used for stdout. "
- return self.stdout.encoding
-
+ def fileno(self):
+ " Return file descriptor. "
+ return self.stdout.fileno()
+
+ def encoding(self):
+ " Return encoding used for stdout. "
+ return self.stdout.encoding
+
def write(self, data):
self._buffer.append(data)
@@ -168,8 +168,8 @@ class Win32Output(Output):
if success:
return sbinfo
- else:
- raise NoConsoleScreenBufferError
+ else:
+ raise NoConsoleScreenBufferError
def set_title(self, title):
"""
@@ -221,31 +221,31 @@ class Win32Output(Output):
byref(chars_written))
def reset_attributes(self):
- " Reset the console foreground/background color. "
- self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole,
- self.default_attrs)
+ " Reset the console foreground/background color. "
+ self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole,
+ self.default_attrs)
def set_attributes(self, attrs):
fgcolor, bgcolor, bold, underline, italic, blink, reverse = attrs
- # Start from the default attributes.
- attrs = self.default_attrs
-
- # Override the last four bits: foreground color.
- if fgcolor is not None:
- attrs = attrs & ~0xf
- attrs |= self.color_lookup_table.lookup_fg_color(fgcolor)
-
- # Override the next four bits: background color.
- if bgcolor is not None:
- attrs = attrs & ~0xf0
- attrs |= self.color_lookup_table.lookup_bg_color(bgcolor)
-
- # Reverse: swap these four bits groups.
+ # Start from the default attributes.
+ attrs = self.default_attrs
+
+ # Override the last four bits: foreground color.
+ if fgcolor is not None:
+ attrs = attrs & ~0xf
+ attrs |= self.color_lookup_table.lookup_fg_color(fgcolor)
+
+ # Override the next four bits: background color.
+ if bgcolor is not None:
+ attrs = attrs & ~0xf0
+ attrs |= self.color_lookup_table.lookup_bg_color(bgcolor)
+
+ # Reverse: swap these four bits groups.
if reverse:
- attrs = (attrs & ~0xff) | ((attrs & 0xf) << 4) | ((attrs & 0xf0) >> 4)
+ attrs = (attrs & ~0xff) | ((attrs & 0xf) << 4) | ((attrs & 0xf0) >> 4)
- self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole, attrs)
+ self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole, attrs)
def disable_autowrap(self):
# Not supported by Windows.
@@ -327,11 +327,11 @@ class Win32Output(Output):
# Scroll vertical
win_height = sr.Bottom - sr.Top
- if 0 < sr.Bottom - cursor_pos.Y < win_height - 1:
- # no vertical scroll if cursor already on the screen
- result.Bottom = sr.Bottom
- else:
- result.Bottom = max(win_height, cursor_pos.Y)
+ if 0 < sr.Bottom - cursor_pos.Y < win_height - 1:
+ # no vertical scroll if cursor already on the screen
+ result.Bottom = sr.Bottom
+ else:
+ result.Bottom = max(win_height, cursor_pos.Y)
result.Top = result.Bottom - win_height
# Scroll API
@@ -429,27 +429,27 @@ class BACKROUND_COLOR:
def _create_ansi_color_dict(color_cls):
" Create a table that maps the 16 named ansi colors to their Windows code. "
return {
- 'ansidefault': color_cls.BLACK,
- 'ansiblack': color_cls.BLACK,
- 'ansidarkgray': color_cls.BLACK | color_cls.INTENSITY,
- 'ansilightgray': color_cls.GRAY,
- 'ansiwhite': color_cls.GRAY | color_cls.INTENSITY,
-
+ 'ansidefault': color_cls.BLACK,
+ 'ansiblack': color_cls.BLACK,
+ 'ansidarkgray': color_cls.BLACK | color_cls.INTENSITY,
+ 'ansilightgray': color_cls.GRAY,
+ 'ansiwhite': color_cls.GRAY | color_cls.INTENSITY,
+
# Low intensity.
- 'ansidarkred': color_cls.RED,
- 'ansidarkgreen': color_cls.GREEN,
- 'ansibrown': color_cls.YELLOW,
- 'ansidarkblue': color_cls.BLUE,
- 'ansipurple': color_cls.MAGENTA,
- 'ansiteal': color_cls.CYAN,
+ 'ansidarkred': color_cls.RED,
+ 'ansidarkgreen': color_cls.GREEN,
+ 'ansibrown': color_cls.YELLOW,
+ 'ansidarkblue': color_cls.BLUE,
+ 'ansipurple': color_cls.MAGENTA,
+ 'ansiteal': color_cls.CYAN,
# High intensity.
- 'ansired': color_cls.RED | color_cls.INTENSITY,
- 'ansigreen': color_cls.GREEN | color_cls.INTENSITY,
- 'ansiyellow': color_cls.YELLOW | color_cls.INTENSITY,
- 'ansiblue': color_cls.BLUE | color_cls.INTENSITY,
- 'ansifuchsia': color_cls.MAGENTA | color_cls.INTENSITY,
- 'ansiturquoise': color_cls.CYAN | color_cls.INTENSITY,
+ 'ansired': color_cls.RED | color_cls.INTENSITY,
+ 'ansigreen': color_cls.GREEN | color_cls.INTENSITY,
+ 'ansiyellow': color_cls.YELLOW | color_cls.INTENSITY,
+ 'ansiblue': color_cls.BLUE | color_cls.INTENSITY,
+ 'ansifuchsia': color_cls.MAGENTA | color_cls.INTENSITY,
+ 'ansiturquoise': color_cls.CYAN | color_cls.INTENSITY,
}
FG_ANSI_COLORS = _create_ansi_color_dict(FOREGROUND_COLOR)
@@ -492,7 +492,7 @@ class ColorLookupTable(object):
(0xff, 0x44, 0xff, FG.MAGENTA | FG.INTENSITY, BG.MAGENTA | BG.INTENSITY),
(0xff, 0xff, 0x44, FG.YELLOW | FG.INTENSITY, BG.YELLOW | BG.INTENSITY),
- (0x44, 0x44, 0x44, FG.BLACK | FG.INTENSITY, BG.BLACK | BG.INTENSITY),
+ (0x44, 0x44, 0x44, FG.BLACK | FG.INTENSITY, BG.BLACK | BG.INTENSITY),
(0xff, 0xff, 0xff, FG.GRAY | FG.INTENSITY, BG.GRAY | BG.INTENSITY),
]
@@ -529,7 +529,7 @@ class ColorLookupTable(object):
self.best_match[color] = indexes
return indexes
- def lookup_fg_color(self, fg_color):
+ def lookup_fg_color(self, fg_color):
"""
Return the color for use in the
`windll.kernel32.SetConsoleTextAttribute` API call.
@@ -538,19 +538,19 @@ class ColorLookupTable(object):
"""
# Foreground.
if fg_color in FG_ANSI_COLORS:
- return FG_ANSI_COLORS[fg_color]
+ return FG_ANSI_COLORS[fg_color]
else:
- return self._color_indexes(fg_color)[0]
-
- def lookup_bg_color(self, bg_color):
- """
- Return the color for use in the
- `windll.kernel32.SetConsoleTextAttribute` API call.
-
- :param bg_color: Background as text. E.g. 'ffffff' or 'red'
- """
+ return self._color_indexes(fg_color)[0]
+
+ def lookup_bg_color(self, bg_color):
+ """
+ Return the color for use in the
+ `windll.kernel32.SetConsoleTextAttribute` API call.
+
+ :param bg_color: Background as text. E.g. 'ffffff' or 'red'
+ """
# Background.
if bg_color in BG_ANSI_COLORS:
- return BG_ANSI_COLORS[bg_color]
+ return BG_ANSI_COLORS[bg_color]
else:
- return self._color_indexes(bg_color)[1]
+ return self._color_indexes(bg_color)[1]
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/token.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/token.py
index 5e2a15787c..5170daf38a 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/token.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/token.py
@@ -1,47 +1,47 @@
-"""
-The Token class, interchangeable with ``pygments.token``.
-
-A `Token` has some semantics for a piece of text that is given a style through
-a :class:`~prompt_toolkit.styles.Style` class. A pygments lexer for instance,
-returns a list of (Token, text) tuples. Each fragment of text has a token
-assigned, which when combined with a style sheet, will determine the fine
-style.
-"""
-
-# If we don't need any lexers or style classes from Pygments, we don't want
-# Pygments to be installed for only the following 10 lines of code. So, there
-# is some duplication, but this should stay compatible with Pygments.
-
-__all__ = (
- 'Token',
- 'ZeroWidthEscape',
-)
-
-
-class _TokenType(tuple):
- def __getattr__(self, val):
- if not val or not val[0].isupper():
- return tuple.__getattribute__(self, val)
-
- new = _TokenType(self + (val,))
- setattr(self, val, new)
- return new
-
- def __repr__(self):
- return 'Token' + (self and '.' or '') + '.'.join(self)
-
-
-# Prefer the Token class from Pygments. If Pygments is not installed, use our
-# minimalistic Token class.
-try:
- from pygments.token import Token
-except ImportError:
- Token = _TokenType()
-
-
-# Built-in tokens:
-
-#: `ZeroWidthEscape` can be used for raw VT escape sequences that don't
-#: cause the cursor position to move. (E.g. FinalTerm's escape sequences
-#: for shell integration.)
-ZeroWidthEscape = Token.ZeroWidthEscape
+"""
+The Token class, interchangeable with ``pygments.token``.
+
+A `Token` has some semantics for a piece of text that is given a style through
+a :class:`~prompt_toolkit.styles.Style` class. A pygments lexer for instance,
+returns a list of (Token, text) tuples. Each fragment of text has a token
+assigned, which when combined with a style sheet, will determine the fine
+style.
+"""
+
+# If we don't need any lexers or style classes from Pygments, we don't want
+# Pygments to be installed for only the following 10 lines of code. So, there
+# is some duplication, but this should stay compatible with Pygments.
+
+__all__ = (
+ 'Token',
+ 'ZeroWidthEscape',
+)
+
+
+class _TokenType(tuple):
+ def __getattr__(self, val):
+ if not val or not val[0].isupper():
+ return tuple.__getattribute__(self, val)
+
+ new = _TokenType(self + (val,))
+ setattr(self, val, new)
+ return new
+
+ def __repr__(self):
+ return 'Token' + (self and '.' or '') + '.'.join(self)
+
+
+# Prefer the Token class from Pygments. If Pygments is not installed, use our
+# minimalistic Token class.
+try:
+ from pygments.token import Token
+except ImportError:
+ Token = _TokenType()
+
+
+# Built-in tokens:
+
+#: `ZeroWidthEscape` can be used for raw VT escape sequences that don't
+#: cause the cursor position to move. (E.g. FinalTerm's escape sequences
+#: for shell integration.)
+ZeroWidthEscape = Token.ZeroWidthEscape
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/utils.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/utils.py
index 233821e6ff..3cd931883c 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/utils.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/utils.py
@@ -1,17 +1,17 @@
from __future__ import unicode_literals
-import inspect
+import inspect
import os
import signal
import sys
import threading
-import weakref
+import weakref
from wcwidth import wcwidth
-from six.moves import range
+from six.moves import range
__all__ = (
- 'Event',
+ 'Event',
'DummyContext',
'get_cwidth',
'suspend_to_background_supported',
@@ -19,58 +19,58 @@ __all__ = (
'is_windows',
'in_main_thread',
'take_using_weights',
- 'test_callable_args',
+ 'test_callable_args',
)
-class Event(object):
+class Event(object):
"""
- Simple event to which event handlers can be attached. For instance::
+ Simple event to which event handlers can be attached. For instance::
- class Cls:
- def __init__(self):
- # Define event. The first parameter is the sender.
- self.event = Event(self)
+ class Cls:
+ def __init__(self):
+ # Define event. The first parameter is the sender.
+ self.event = Event(self)
- obj = Cls()
+ obj = Cls()
- def handler(sender):
- pass
+ def handler(sender):
+ pass
- # Add event handler by using the += operator.
- obj.event += handler
-
- # Fire event.
- obj.event()
+ # Add event handler by using the += operator.
+ obj.event += handler
+
+ # Fire event.
+ obj.event()
"""
- def __init__(self, sender, handler=None):
- self.sender = sender
- self._handlers = []
+ def __init__(self, sender, handler=None):
+ self.sender = sender
+ self._handlers = []
+
+ if handler is not None:
+ self += handler
- if handler is not None:
- self += handler
-
- def __call__(self):
- " Fire event. "
+ def __call__(self):
+ " Fire event. "
for handler in self._handlers:
- handler(self.sender)
+ handler(self.sender)
+
+ def fire(self):
+ " Alias for just calling the event. "
+ self()
- def fire(self):
- " Alias for just calling the event. "
- self()
-
def __iadd__(self, handler):
"""
Add another handler to this callback.
- (Handler should be a callable that takes exactly one parameter: the
- sender object.)
+ (Handler should be a callable that takes exactly one parameter: the
+ sender object.)
"""
- # Test handler.
- assert callable(handler)
- if not test_callable_args(handler, [None]):
- raise TypeError("%r doesn't take exactly one argument." % handler)
-
- # Add to list of event handlers.
+ # Test handler.
+ assert callable(handler)
+ if not test_callable_args(handler, [None]):
+ raise TypeError("%r doesn't take exactly one argument." % handler)
+
+ # Add to list of event handlers.
self._handlers.append(handler)
return self
@@ -82,53 +82,53 @@ class Event(object):
return self
-# Cache of signatures. Improves the performance of `test_callable_args`.
-_signatures_cache = weakref.WeakKeyDictionary()
-
-
-def test_callable_args(func, args):
- """
- Return True when this function can be called with the given arguments.
- """
- assert isinstance(args, (list, tuple))
- signature = getattr(inspect, 'signature', None)
-
- if signature is not None:
- # For Python 3, use inspect.signature.
- try:
- sig = _signatures_cache[func]
- except KeyError:
- sig = signature(func)
- _signatures_cache[func] = sig
-
- try:
- sig.bind(*args)
- except TypeError:
- return False
- else:
- return True
- else:
- # For older Python versions, fall back to using getargspec.
- spec = inspect.getargspec(func)
-
- # Drop the 'self'
- def drop_self(spec):
- args, varargs, varkw, defaults = spec
- if args[0:1] == ['self']:
- args = args[1:]
- return inspect.ArgSpec(args, varargs, varkw, defaults)
-
- spec = drop_self(spec)
-
- # When taking *args, always return True.
- if spec.varargs is not None:
- return True
-
- # Test whether the given amount of args is between the min and max
- # accepted argument counts.
- return len(spec.args) - len(spec.defaults or []) <= len(args) <= len(spec.args)
-
-
+# Cache of signatures. Improves the performance of `test_callable_args`.
+_signatures_cache = weakref.WeakKeyDictionary()
+
+
+def test_callable_args(func, args):
+ """
+ Return True when this function can be called with the given arguments.
+ """
+ assert isinstance(args, (list, tuple))
+ signature = getattr(inspect, 'signature', None)
+
+ if signature is not None:
+ # For Python 3, use inspect.signature.
+ try:
+ sig = _signatures_cache[func]
+ except KeyError:
+ sig = signature(func)
+ _signatures_cache[func] = sig
+
+ try:
+ sig.bind(*args)
+ except TypeError:
+ return False
+ else:
+ return True
+ else:
+ # For older Python versions, fall back to using getargspec.
+ spec = inspect.getargspec(func)
+
+ # Drop the 'self'
+ def drop_self(spec):
+ args, varargs, varkw, defaults = spec
+ if args[0:1] == ['self']:
+ args = args[1:]
+ return inspect.ArgSpec(args, varargs, varkw, defaults)
+
+ spec = drop_self(spec)
+
+ # When taking *args, always return True.
+ if spec.varargs is not None:
+ return True
+
+ # Test whether the given amount of args is between the min and max
+ # accepted argument counts.
+ return len(spec.args) - len(spec.defaults or []) <= len(args) <= len(spec.args)
+
+
class DummyContext(object):
"""
(contextlib.nested is not available on Py3)
@@ -154,11 +154,11 @@ class _CharSizesCache(dict):
else:
result = sum(max(0, wcwidth(c)) for c in string)
- # Cache for short strings.
- # (It's hard to tell what we can consider short...)
- if len(string) < 256:
- self[string] = result
-
+ # Cache for short strings.
+ # (It's hard to tell what we can consider short...)
+ if len(string) < 256:
+ self[string] = result
+
return result
diff --git a/contrib/python/prompt-toolkit/py2/prompt_toolkit/validation.py b/contrib/python/prompt-toolkit/py2/prompt_toolkit/validation.py
index 384805226f..0027873f88 100644
--- a/contrib/python/prompt-toolkit/py2/prompt_toolkit/validation.py
+++ b/contrib/python/prompt-toolkit/py2/prompt_toolkit/validation.py
@@ -56,7 +56,7 @@ class ConditionalValidator(Validator):
assert isinstance(validator, Validator)
self.validator = validator
- self.filter = to_simple_filter(filter)
+ self.filter = to_simple_filter(filter)
def validate(self, document):
# Call the validator only if the filter is active.
diff --git a/contrib/python/prompt-toolkit/py2/ya.make b/contrib/python/prompt-toolkit/py2/ya.make
index dd98b8cc65..db22aa0a70 100644
--- a/contrib/python/prompt-toolkit/py2/ya.make
+++ b/contrib/python/prompt-toolkit/py2/ya.make
@@ -5,7 +5,7 @@ OWNER(blinkov nslus g:python-contrib)
VERSION(1.0.18)
LICENSE(BSD-3-Clause)
-
+
PEERDIR(
contrib/python/six
contrib/python/wcwidth
@@ -40,7 +40,7 @@ PY_SRCS(
prompt_toolkit/auto_suggest.py
prompt_toolkit/buffer.py
prompt_toolkit/buffer_mapping.py
- prompt_toolkit/cache.py
+ prompt_toolkit/cache.py
prompt_toolkit/clipboard/__init__.py
prompt_toolkit/clipboard/base.py
prompt_toolkit/clipboard/in_memory.py
@@ -75,7 +75,7 @@ PY_SRCS(
prompt_toolkit/eventloop/inputhook.py
prompt_toolkit/eventloop/posix.py
prompt_toolkit/eventloop/posix_utils.py
- prompt_toolkit/eventloop/select.py
+ prompt_toolkit/eventloop/select.py
prompt_toolkit/eventloop/utils.py
prompt_toolkit/eventloop/win32.py
prompt_toolkit/filters/__init__.py
@@ -89,14 +89,14 @@ PY_SRCS(
prompt_toolkit/key_binding/__init__.py
prompt_toolkit/key_binding/bindings/__init__.py
prompt_toolkit/key_binding/bindings/basic.py
- prompt_toolkit/key_binding/bindings/completion.py
+ prompt_toolkit/key_binding/bindings/completion.py
prompt_toolkit/key_binding/bindings/emacs.py
- prompt_toolkit/key_binding/bindings/named_commands.py
+ prompt_toolkit/key_binding/bindings/named_commands.py
prompt_toolkit/key_binding/bindings/scroll.py
prompt_toolkit/key_binding/bindings/utils.py
prompt_toolkit/key_binding/bindings/vi.py
prompt_toolkit/key_binding/defaults.py
- prompt_toolkit/key_binding/digraphs.py
+ prompt_toolkit/key_binding/digraphs.py
prompt_toolkit/key_binding/input_processor.py
prompt_toolkit/key_binding/manager.py
prompt_toolkit/key_binding/registry.py
@@ -122,19 +122,19 @@ PY_SRCS(
prompt_toolkit/search_state.py
prompt_toolkit/selection.py
prompt_toolkit/shortcuts.py
- prompt_toolkit/styles/__init__.py
- prompt_toolkit/styles/base.py
- prompt_toolkit/styles/defaults.py
- prompt_toolkit/styles/from_dict.py
- prompt_toolkit/styles/from_pygments.py
- prompt_toolkit/styles/utils.py
+ prompt_toolkit/styles/__init__.py
+ prompt_toolkit/styles/base.py
+ prompt_toolkit/styles/defaults.py
+ prompt_toolkit/styles/from_dict.py
+ prompt_toolkit/styles/from_pygments.py
+ prompt_toolkit/styles/utils.py
prompt_toolkit/terminal/__init__.py
prompt_toolkit/terminal/conemu_output.py
prompt_toolkit/terminal/vt100_input.py
prompt_toolkit/terminal/vt100_output.py
prompt_toolkit/terminal/win32_input.py
prompt_toolkit/terminal/win32_output.py
- prompt_toolkit/token.py
+ prompt_toolkit/token.py
prompt_toolkit/utils.py
prompt_toolkit/validation.py
prompt_toolkit/win32_types.py
@@ -147,7 +147,7 @@ RESOURCE_FILES(
)
END()
-
+
RECURSE_FOR_TESTS(
tests
)
diff --git a/contrib/python/prompt-toolkit/ya.make b/contrib/python/prompt-toolkit/ya.make
index 807b031a88..f1f936eb3f 100644
--- a/contrib/python/prompt-toolkit/ya.make
+++ b/contrib/python/prompt-toolkit/ya.make
@@ -3,7 +3,7 @@ PY23_LIBRARY()
LICENSE(Service-Py23-Proxy)
OWNER(g:python-contrib)
-
+
IF (PYTHON2)
PEERDIR(contrib/python/prompt-toolkit/py2)
ELSE()
@@ -13,7 +13,7 @@ ENDIF()
NO_LINT()
END()
-
+
RECURSE(
py2
py3
diff --git a/contrib/python/py/ya.make b/contrib/python/py/ya.make
index ff0ad933d3..cc86cb7fa9 100644
--- a/contrib/python/py/ya.make
+++ b/contrib/python/py/ya.make
@@ -5,7 +5,7 @@ PY23_LIBRARY()
OWNER(g:python-contrib)
VERSION(1.11.0)
-
+
LICENSE(MIT)
NO_LINT()
diff --git a/contrib/python/traitlets/py2/traitlets/config/application.py b/contrib/python/traitlets/py2/traitlets/config/application.py
index 5f750b5138..d3a4c45e77 100644
--- a/contrib/python/traitlets/py2/traitlets/config/application.py
+++ b/contrib/python/traitlets/py2/traitlets/config/application.py
@@ -6,13 +6,13 @@
from __future__ import print_function
-from copy import deepcopy
+from copy import deepcopy
import json
import logging
import os
import re
import sys
-from collections import defaultdict, OrderedDict
+from collections import defaultdict, OrderedDict
from decorator import decorator
@@ -22,14 +22,14 @@ from traitlets.config.loader import (
)
from traitlets.traitlets import (
- Bool, Unicode, List, Enum, Dict, Instance, TraitError, observe, observe_compat, default,
+ Bool, Unicode, List, Enum, Dict, Instance, TraitError, observe, observe_compat, default,
)
from ipython_genutils.importstring import import_item
from ipython_genutils.text import indent, wrap_paragraphs, dedent
from ipython_genutils import py3compat
-import six
-
+import six
+
#-----------------------------------------------------------------------------
# Descriptions for the various sections
#-----------------------------------------------------------------------------
@@ -63,24 +63,24 @@ subcommand 'cmd', do: `{app} cmd -h`.
# Application class
#-----------------------------------------------------------------------------
-
-
-_envvar = os.environ.get('TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR','')
-if _envvar.lower() in {'1','true'}:
- TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = True
-elif _envvar.lower() in {'0','false',''} :
- TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = False
-else:
- raise ValueError("Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
-
-
+
+
+_envvar = os.environ.get('TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR','')
+if _envvar.lower() in {'1','true'}:
+ TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = True
+elif _envvar.lower() in {'0','false',''} :
+ TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = False
+else:
+ raise ValueError("Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
+
+
@decorator
def catch_config_error(method, app, *args, **kwargs):
"""Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
On a TraitError (generally caused by bad config), this will print the trait's
message, and exit the app.
-
+
For use on init methods, to prevent invoking excepthook on invalid input.
"""
try:
@@ -99,16 +99,16 @@ class ApplicationError(Exception):
class LevelFormatter(logging.Formatter):
"""Formatter with additional `highlevel` record
-
+
This field is empty if log level is less than highlevel_limit,
otherwise it is formatted with self.highlevel_format.
-
+
Useful for adding 'WARNING' to warning messages,
without adding 'INFO' to info, etc.
"""
highlevel_limit = logging.WARN
highlevel_format = " %(levelname)s |"
-
+
def format(self, record):
if record.levelno >= self.highlevel_limit:
record.highlevel = self.highlevel_format % record.__dict__
@@ -116,7 +116,7 @@ class LevelFormatter(logging.Formatter):
record.highlevel = ""
return super(LevelFormatter, self).format(record)
-
+
class Application(SingletonConfigurable):
"""A singleton application with full configuration support."""
@@ -131,7 +131,7 @@ class Application(SingletonConfigurable):
option_description = Unicode(option_description)
keyvalue_description = Unicode(keyvalue_description)
subcommand_description = Unicode(subcommand_description)
-
+
python_config_loader_class = PyFileConfigLoader
json_config_loader_class = JSONFileConfigLoader
@@ -158,13 +158,13 @@ class Application(SingletonConfigurable):
# The version string of this application.
version = Unicode(u'0.0')
-
+
# the argv used to initialize the application
argv = List()
- # Whether failing to load config files should prevent startup
- raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)
-
+ # Whether failing to load config files should prevent startup
+ raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)
+
# The log level for the application
log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
default_value=logging.WARN,
@@ -174,15 +174,15 @@ class Application(SingletonConfigurable):
@observe_compat
def _log_level_changed(self, change):
"""Adjust the log level when log_level is set."""
- new = change.new
- if isinstance(new, six.string_types):
+ new = change.new
+ if isinstance(new, six.string_types):
new = getattr(logging, new)
self.log_level = new
self.log.setLevel(new)
-
+
_log_formatter_cls = LevelFormatter
-
- log_datefmt = Unicode("%Y-%m-%d %H:%M:%S",
+
+ log_datefmt = Unicode("%Y-%m-%d %H:%M:%S",
help="The date format used by logging formatters for %(asctime)s"
).tag(config=True)
@@ -197,7 +197,7 @@ class Application(SingletonConfigurable):
_log_handler = self.log.handlers[0]
_log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
_log_handler.setFormatter(_log_formatter)
-
+
@default('log')
def _log_default(self):
"""Start logging for this application.
@@ -217,7 +217,7 @@ class Application(SingletonConfigurable):
break
else:
_log = _log.parent
- if sys.executable and sys.executable.endswith('pythonw.exe'):
+ if sys.executable and sys.executable.endswith('pythonw.exe'):
# this should really go to a file, but file-logging is only
# hooked up in parallel applications
_log_handler = logging.StreamHandler(open(os.devnull, 'w'))
@@ -240,11 +240,11 @@ class Application(SingletonConfigurable):
@observe_compat
def _flags_changed(self, change):
"""ensure flags dict is valid"""
- new = change.new
+ new = change.new
for key, value in new.items():
assert len(value) == 2, "Bad flag: %r:%s" % (key, value)
assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s" % (key, value)
- assert isinstance(value[1], six.string_types), "Bad flag: %r:%s" % (key, value)
+ assert isinstance(value[1], six.string_types), "Bad flag: %r:%s" % (key, value)
# subcommands for launching other applications
@@ -259,34 +259,34 @@ class Application(SingletonConfigurable):
# extra command-line arguments that don't set config values
extra_args = List(Unicode())
- cli_config = Instance(Config, (), {},
- help="""The subset of our configuration that came from the command-line
+ cli_config = Instance(Config, (), {},
+ help="""The subset of our configuration that came from the command-line
+
+ We re-load this configuration after loading config files,
+ to ensure that it maintains highest priority.
+ """
+ )
- We re-load this configuration after loading config files,
- to ensure that it maintains highest priority.
- """
- )
-
_loaded_config_files = List()
-
+
def __init__(self, **kwargs):
SingletonConfigurable.__init__(self, **kwargs)
# Ensure my class is in self.classes, so my attributes appear in command line
# options and config files.
- cls = self.__class__
- if cls not in self.classes:
- if self.classes is cls.classes:
- # class attr, assign instead of insert
- cls.classes = [cls] + self.classes
- else:
- self.classes.insert(0, self.__class__)
-
+ cls = self.__class__
+ if cls not in self.classes:
+ if self.classes is cls.classes:
+ # class attr, assign instead of insert
+ cls.classes = [cls] + self.classes
+ else:
+ self.classes.insert(0, self.__class__)
+
@observe('config')
@observe_compat
def _config_changed(self, change):
super(Application, self)._config_changed(change)
self.log.debug('Config changed:')
- self.log.debug(repr(change.new))
+ self.log.debug(repr(change.new))
@catch_config_error
def initialize(self, argv=None):
@@ -317,7 +317,7 @@ class Application(SingletonConfigurable):
for c in cls.mro()[:-3]:
classdict[c.__name__] = c
- for alias, longname in self.aliases.items():
+ for alias, longname in self.aliases.items():
classname, traitname = longname.split('.',1)
cls = classdict[classname]
@@ -337,7 +337,7 @@ class Application(SingletonConfigurable):
return
lines = []
- for m, (cfg,help) in self.flags.items():
+ for m, (cfg,help) in self.flags.items():
prefix = '--' if len(m) > 1 else '-'
lines.append(prefix+m)
lines.append(indent(dedent(help.strip())))
@@ -370,7 +370,7 @@ class Application(SingletonConfigurable):
app=self.name)):
lines.append(p)
lines.append('')
- for subc, (cls, help) in self.subcommands.items():
+ for subc, (cls, help) in self.subcommands.items():
lines.append(subc)
if help:
lines.append(indent(dedent(help.strip())))
@@ -442,26 +442,26 @@ class Application(SingletonConfigurable):
"""Initialize a subcommand with argv."""
subapp,help = self.subcommands.get(subc)
- if isinstance(subapp, six.string_types):
+ if isinstance(subapp, six.string_types):
subapp = import_item(subapp)
# clear existing instances
self.__class__.clear_instance()
# instantiate
- self.subapp = subapp.instance(parent=self)
+ self.subapp = subapp.instance(parent=self)
# and initialize subapp
self.subapp.initialize(argv)
-
+
def flatten_flags(self):
"""flatten flags and aliases, so cl-args override as expected.
-
+
This prevents issues such as an alias pointing to InteractiveShell,
but a config file setting the same trait in TerminalInteraciveShell
getting inappropriate priority over the command-line arg.
Only aliases with exactly one descendent in the class list
will be promoted.
-
+
"""
# build a tree of classes in our list that inherit from a particular
# it will be a dict by parent classname of classes in our list
@@ -475,20 +475,20 @@ class Application(SingletonConfigurable):
# flatten aliases, which have the form:
# { 'alias' : 'Class.trait' }
aliases = {}
- for alias, cls_trait in self.aliases.items():
+ for alias, cls_trait in self.aliases.items():
cls,trait = cls_trait.split('.',1)
children = mro_tree[cls]
if len(children) == 1:
# exactly one descendent, promote alias
cls = children[0]
aliases[alias] = '.'.join([cls,trait])
-
+
# flatten flags, which are of the form:
# { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
flags = {}
- for key, (flagdict, help) in self.flags.items():
+ for key, (flagdict, help) in self.flags.items():
newflag = {}
- for cls, subdict in flagdict.items():
+ for cls, subdict in flagdict.items():
children = mro_tree[cls]
# exactly one descendent, promote flag section
if len(children) == 1:
@@ -502,7 +502,7 @@ class Application(SingletonConfigurable):
"""Parse the command line arguments."""
argv = sys.argv[1:] if argv is None else argv
self.argv = [ py3compat.cast_unicode(arg) for arg in argv ]
-
+
if argv and argv[0] == 'help':
# turn `ipython help notebook` into `ipython notebook -h`
argv = argv[1:] + ['-h']
@@ -530,33 +530,33 @@ class Application(SingletonConfigurable):
if '--version' in interpreted_argv or '-V' in interpreted_argv:
self.print_version()
self.exit(0)
-
+
# flatten flags&aliases, so cl-args get appropriate priority:
flags,aliases = self.flatten_flags()
loader = KVArgParseConfigLoader(argv=argv, aliases=aliases,
flags=flags, log=self.log)
- self.cli_config = deepcopy(loader.load_config())
- self.update_config(self.cli_config)
+ self.cli_config = deepcopy(loader.load_config())
+ self.update_config(self.cli_config)
# store unparsed args in extra_args
self.extra_args = loader.extra_args
@classmethod
- def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
+ def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
"""Load config files (py,json) by filename and path.
yield each config object in turn.
"""
-
+
if not isinstance(path, list):
path = [path]
for path in path[::-1]:
# path list is in descending priority order, so load files backwards:
pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
if log:
- log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
+ log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
- loaded = []
- filenames = []
+ loaded = []
+ filenames = []
for loader in [pyloader, jsonloader]:
config = None
try:
@@ -568,8 +568,8 @@ class Application(SingletonConfigurable):
# unlikely event that the error raised before filefind finished
filename = loader.full_filename or basefilename
# problem while running the file
- if raise_config_file_errors:
- raise
+ if raise_config_file_errors:
+ raise
if log:
log.error("Exception while loading config file %s",
filename, exc_info=True)
@@ -577,16 +577,16 @@ class Application(SingletonConfigurable):
if log:
log.debug("Loaded config file: %s", loader.full_filename)
if config:
- for filename, earlier_config in zip(filenames, loaded):
- collisions = earlier_config.collisions(config)
- if collisions and log:
- log.warning("Collisions detected in {0} and {1} config files."
- " {1} has higher priority: {2}".format(
- filename, loader.full_filename, json.dumps(collisions, indent=2),
- ))
+ for filename, earlier_config in zip(filenames, loaded):
+ collisions = earlier_config.collisions(config)
+ if collisions and log:
+ log.warning("Collisions detected in {0} and {1} config files."
+ " {1} has higher priority: {2}".format(
+ filename, loader.full_filename, json.dumps(collisions, indent=2),
+ ))
yield (config, loader.full_filename)
- loaded.append(config)
- filenames.append(loader.full_filename)
+ loaded.append(config)
+ filenames.append(loader.full_filename)
@property
def loaded_config_files(self):
@@ -597,55 +597,55 @@ class Application(SingletonConfigurable):
def load_config_file(self, filename, path=None):
"""Load config files by filename and path."""
filename, ext = os.path.splitext(filename)
- new_config = Config()
+ new_config = Config()
for (config, filename) in self._load_config_files(filename, path=path, log=self.log,
- raise_config_file_errors=self.raise_config_file_errors,
- ):
- new_config.merge(config)
+ raise_config_file_errors=self.raise_config_file_errors,
+ ):
+ new_config.merge(config)
if filename not in self._loaded_config_files: # only add to list of loaded files if not previously loaded
self._loaded_config_files.append(filename)
- # add self.cli_config to preserve CLI config priority
- new_config.merge(self.cli_config)
- self.update_config(new_config)
-
-
- def _classes_in_config_sample(self):
- """
- Yields only classes with own traits, and their subclasses.
-
- Thus, produced sample config-file will contain all classes
- on which a trait-value may be overridden:
-
- - either on the class owning the trait,
- - or on its subclasses, even if those subclasses do not define
- any traits themselves.
- """
- cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True)))
- for cls
- in self._classes_inc_parents())
-
- def is_any_parent_included(cls):
- return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__)
-
- ## Mark "empty" classes for inclusion if their parents own-traits,
- # and loop until no more classes gets marked.
- #
- while True:
- to_incl_orig = cls_to_config.copy()
- cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls))
- for cls, inc_yes
- in cls_to_config.items())
- if cls_to_config == to_incl_orig:
- break
- for cl, inc_yes in cls_to_config.items():
- if inc_yes:
- yield cl
-
+ # add self.cli_config to preserve CLI config priority
+ new_config.merge(self.cli_config)
+ self.update_config(new_config)
+
+
+ def _classes_in_config_sample(self):
+ """
+ Yields only classes with own traits, and their subclasses.
+
+ Thus, produced sample config-file will contain all classes
+ on which a trait-value may be overridden:
+
+ - either on the class owning the trait,
+ - or on its subclasses, even if those subclasses do not define
+ any traits themselves.
+ """
+ cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True)))
+ for cls
+ in self._classes_inc_parents())
+
+ def is_any_parent_included(cls):
+ return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__)
+
+ ## Mark "empty" classes for inclusion if their parents own-traits,
+ # and loop until no more classes gets marked.
+ #
+ while True:
+ to_incl_orig = cls_to_config.copy()
+ cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls))
+ for cls, inc_yes
+ in cls_to_config.items())
+ if cls_to_config == to_incl_orig:
+ break
+ for cl, inc_yes in cls_to_config.items():
+ if inc_yes:
+ yield cl
+
def generate_config_file(self):
"""generate default config file from Configurables"""
lines = ["# Configuration file for %s." % self.name]
lines.append('')
- for cls in self._classes_in_config_sample():
+ for cls in self._classes_in_config_sample():
lines.append(cls.class_config_section())
return '\n'.join(lines)
@@ -656,7 +656,7 @@ class Application(SingletonConfigurable):
@classmethod
def launch_instance(cls, argv=None, **kwargs):
"""Launch a global instance of this Application
-
+
If a global instance already exists, this reinitializes and starts it
"""
app = cls.instance(**kwargs)
@@ -702,7 +702,7 @@ def boolean_flag(name, configurable, set_help='', unset_help=''):
def get_config():
"""Get the config object for the global Application instance, if there is one
-
+
otherwise return an empty config object
"""
if Application.initialized():
diff --git a/contrib/python/traitlets/py2/traitlets/config/configurable.py b/contrib/python/traitlets/py2/traitlets/config/configurable.py
index 7e34c5a84a..1174fcf017 100644
--- a/contrib/python/traitlets/py2/traitlets/config/configurable.py
+++ b/contrib/python/traitlets/py2/traitlets/config/configurable.py
@@ -4,12 +4,12 @@
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-from __future__ import print_function, absolute_import
+from __future__ import print_function, absolute_import
from copy import deepcopy
-import warnings
+import warnings
-from .loader import Config, LazyConfigValue, _is_section_key
+from .loader import Config, LazyConfigValue, _is_section_key
from traitlets.traitlets import HasTraits, Instance, observe, observe_compat, default
from ipython_genutils.text import indent, dedent, wrap_paragraphs
@@ -66,12 +66,12 @@ class Configurable(HasTraits):
if kwargs.get('config', None) is None:
kwargs['config'] = parent.config
self.parent = parent
-
+
config = kwargs.pop('config', None)
-
+
# load kwarg traits, other than config
super(Configurable, self).__init__(**kwargs)
-
+
# load config
if config is not None:
# We used to deepcopy, but for now we are trying to just save
@@ -85,7 +85,7 @@ class Configurable(HasTraits):
else:
# allow _config_default to return something
self._load_config(self.config)
-
+
# Ensure explicit kwargs are applied after loading config.
# This is usually redundant, but ensures config doesn't override
# explicitly assigned values.
@@ -95,25 +95,25 @@ class Configurable(HasTraits):
#-------------------------------------------------------------------------
# Static trait notifiations
#-------------------------------------------------------------------------
-
+
@classmethod
def section_names(cls):
"""return section names as a list"""
return [c.__name__ for c in reversed(cls.__mro__) if
issubclass(c, Configurable) and issubclass(cls, c)
]
-
+
def _find_my_config(self, cfg):
"""extract my config from a global Config object
-
+
will construct a Config object of only the config values that apply to me
based on my mro(), as well as those of my parent(s) if they exist.
-
+
If I am Bar and my parent is Foo, and their parent is Tim,
this will return merge following config sections, in this order::
-
+
[Bar, Foo.bar, Tim.Foo.Bar]
-
+
With the last item being the highest priority.
"""
cfgs = [cfg]
@@ -127,20 +127,20 @@ class Configurable(HasTraits):
if c._has_section(sname):
my_config.merge(c[sname])
return my_config
-
+
def _load_config(self, cfg, section_names=None, traits=None):
"""load traits from a Config object"""
-
+
if traits is None:
traits = self.traits(config=True)
if section_names is None:
section_names = self.section_names()
-
+
my_config = self._find_my_config(cfg)
-
+
# hold trait notifications until after all config has been loaded
with self.hold_trait_notifications():
- for name, config_value in my_config.items():
+ for name, config_value in my_config.items():
if name in traits:
if isinstance(config_value, LazyConfigValue):
# ConfigValue is a wrapper for using append / update on containers
@@ -151,21 +151,21 @@ class Configurable(HasTraits):
# config object. If we don't, a mutable config_value will be
# shared by all instances, effectively making it a class attribute.
setattr(self, name, deepcopy(config_value))
- elif not _is_section_key(name) and not isinstance(config_value, Config):
+ elif not _is_section_key(name) and not isinstance(config_value, Config):
from difflib import get_close_matches
- if isinstance(self, LoggingConfigurable):
- warn = self.log.warning
- else:
- warn = lambda msg: warnings.warn(msg, stacklevel=9)
+ if isinstance(self, LoggingConfigurable):
+ warn = self.log.warning
+ else:
+ warn = lambda msg: warnings.warn(msg, stacklevel=9)
matches = get_close_matches(name, traits)
- msg = u"Config option `{option}` not recognized by `{klass}`.".format(
- option=name, klass=self.__class__.__name__)
-
+ msg = u"Config option `{option}` not recognized by `{klass}`.".format(
+ option=name, klass=self.__class__.__name__)
+
if len(matches) == 1:
- msg += u" Did you mean `{matches}`?".format(matches=matches[0])
+ msg += u" Did you mean `{matches}`?".format(matches=matches[0])
elif len(matches) >= 1:
- msg +=" Did you mean one of: `{matches}`?".format(matches=', '.join(sorted(matches)))
- warn(msg)
+ msg +=" Did you mean one of: `{matches}`?".format(matches=', '.join(sorted(matches)))
+ warn(msg)
@observe('config')
@observe_compat
@@ -183,23 +183,23 @@ class Configurable(HasTraits):
# classes that are Configurable subclasses. This starts with Configurable
# and works down the mro loading the config for each section.
section_names = self.section_names()
- self._load_config(change.new, traits=traits, section_names=section_names)
+ self._load_config(change.new, traits=traits, section_names=section_names)
def update_config(self, config):
- """Update config and load the new values"""
- # traitlets prior to 4.2 created a copy of self.config in order to trigger change events.
- # Some projects (IPython < 5) relied upon one side effect of this,
- # that self.config prior to update_config was not modified in-place.
- # For backward-compatibility, we must ensure that self.config
- # is a new object and not modified in-place,
- # but config consumers should not rely on this behavior.
- self.config = deepcopy(self.config)
- # load config
- self._load_config(config)
- # merge it into self.config
+ """Update config and load the new values"""
+ # traitlets prior to 4.2 created a copy of self.config in order to trigger change events.
+ # Some projects (IPython < 5) relied upon one side effect of this,
+ # that self.config prior to update_config was not modified in-place.
+ # For backward-compatibility, we must ensure that self.config
+ # is a new object and not modified in-place,
+ # but config consumers should not rely on this behavior.
+ self.config = deepcopy(self.config)
+ # load config
+ self._load_config(config)
+ # merge it into self.config
self.config.merge(config)
- # TODO: trigger change event if/when dict-update change events take place
- # DO NOT trigger full trait-change
+ # TODO: trigger change event if/when dict-update change events take place
+ # DO NOT trigger full trait-change
@classmethod
def class_get_help(cls, inst=None):
@@ -220,7 +220,7 @@ class Configurable(HasTraits):
@classmethod
def class_get_trait_help(cls, trait, inst=None):
"""Get the help string for a single trait.
-
+
If `inst` is given, it's current trait values will be used in place of
the class default.
"""
@@ -261,19 +261,19 @@ class Configurable(HasTraits):
"""return a commented, wrapped block."""
s = '\n\n'.join(wrap_paragraphs(s, 78))
- return '## ' + s.replace('\n', '\n# ')
+ return '## ' + s.replace('\n', '\n# ')
# section header
breaker = '#' + '-'*78
- parent_classes = ','.join(p.__name__ for p in cls.__bases__)
- s = "# %s(%s) configuration" % (cls.__name__, parent_classes)
+ parent_classes = ','.join(p.__name__ for p in cls.__bases__)
+ s = "# %s(%s) configuration" % (cls.__name__, parent_classes)
lines = [breaker, s, breaker, '']
# get the description trait
desc = cls.class_traits().get('description')
if desc:
desc = desc.default_value
- if not desc:
- # no description from trait, use __doc__
+ if not desc:
+ # no description from trait, use __doc__
desc = getattr(cls, '__doc__', '')
if desc:
lines.append(c(desc))
@@ -281,7 +281,7 @@ class Configurable(HasTraits):
for name, trait in sorted(cls.class_own_traits(config=True).items()):
lines.append(c(trait.help))
- lines.append('#c.%s.%s = %s' % (cls.__name__, name, trait.default_value_repr()))
+ lines.append('#c.%s.%s = %s' % (cls.__name__, name, trait.default_value_repr()))
lines.append('')
return '\n'.join(lines)
diff --git a/contrib/python/traitlets/py2/traitlets/config/loader.py b/contrib/python/traitlets/py2/traitlets/config/loader.py
index a79a398c3d..803b36276f 100644
--- a/contrib/python/traitlets/py2/traitlets/config/loader.py
+++ b/contrib/python/traitlets/py2/traitlets/config/loader.py
@@ -16,7 +16,7 @@ from ast import literal_eval
from ipython_genutils.path import filefind
from ipython_genutils import py3compat
from ipython_genutils.encoding import DEFAULT_ENCODING
-from six import text_type
+from six import text_type
from traitlets.traitlets import HasTraits, List, Any
#-----------------------------------------------------------------------------
@@ -182,7 +182,7 @@ class Config(dict):
def merge(self, other):
"""merge another config object into this one"""
to_update = {}
- for k, v in other.items():
+ for k, v in other.items():
if k not in self:
to_update[k] = v
else: # I have this key
@@ -385,17 +385,17 @@ class FileConfigLoader(ConfigLoader):
self.full_filename = filefind(self.filename, self.path)
class JSONFileConfigLoader(FileConfigLoader):
- """A JSON file loader for config
-
- Can also act as a context manager that rewrite the configuration file to disk on exit.
-
- Example::
-
- with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c:
- c.MyNewConfigurable.new_value = 'Updated'
-
- """
-
+ """A JSON file loader for config
+
+ Can also act as a context manager that rewrite the configuration file to disk on exit.
+
+ Example::
+
+ with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c:
+ c.MyNewConfigurable.new_value = 'Updated'
+
+ """
+
def load_config(self):
"""Load the config from a file and return it as a Config object."""
self.clear()
@@ -422,24 +422,24 @@ class JSONFileConfigLoader(FileConfigLoader):
else:
raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
- def __enter__(self):
- self.load_config()
- return self.config
-
- def __exit__(self, exc_type, exc_value, traceback):
- """
- Exit the context manager but do not handle any errors.
-
- In case of any error, we do not want to write the potentially broken
- configuration to disk.
- """
- self.config.version = 1
- json_config = json.dumps(self.config, indent=2)
- with open(self.full_filename, 'w') as f:
- f.write(json_config)
-
-
-
+ def __enter__(self):
+ self.load_config()
+ return self.config
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ """
+ Exit the context manager but do not handle any errors.
+
+ In case of any error, we do not want to write the potentially broken
+ configuration to disk.
+ """
+ self.config.version = 1
+ json_config = json.dumps(self.config, indent=2)
+ with open(self.full_filename, 'w') as f:
+ f.write(json_config)
+
+
+
class PyFileConfigLoader(FileConfigLoader):
"""A config loader for pure python files.
@@ -521,7 +521,7 @@ class CommandLineConfigLoader(ConfigLoader):
if isinstance(cfg, (dict, Config)):
# don't clobber whole config sections, update
# each section from config:
- for sec,c in cfg.items():
+ for sec,c in cfg.items():
self.config[sec].update(c)
else:
raise TypeError("Invalid flag: %r" % cfg)
@@ -603,7 +603,7 @@ class KeyValueConfigLoader(CommandLineConfigLoader):
if enc is None:
enc = DEFAULT_ENCODING
for arg in argv:
- if not isinstance(arg, text_type):
+ if not isinstance(arg, text_type):
# only decode if not already decoded
arg = arg.decode(enc)
uargv.append(arg)
@@ -769,7 +769,7 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
def _convert_to_config(self):
"""self.parsed_data->self.config"""
- for k, v in vars(self.parsed_data).items():
+ for k, v in vars(self.parsed_data).items():
exec("self.config.%s = v"%k, locals(), globals())
class KVArgParseConfigLoader(ArgParseConfigLoader):
@@ -786,17 +786,17 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
if flags is None:
flags = self.flags
paa = self.parser.add_argument
- for key,value in aliases.items():
+ for key,value in aliases.items():
if key in flags:
# flags
nargs = '?'
else:
nargs = None
if len(key) is 1:
- paa('-'+key, '--'+key, type=text_type, dest=value, nargs=nargs)
+ paa('-'+key, '--'+key, type=text_type, dest=value, nargs=nargs)
else:
- paa('--'+key, type=text_type, dest=value, nargs=nargs)
- for key, (value, help) in flags.items():
+ paa('--'+key, type=text_type, dest=value, nargs=nargs)
+ for key, (value, help) in flags.items():
if key in self.aliases:
#
self.alias_flags[self.aliases[key]] = value
@@ -815,7 +815,7 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
else:
subcs = []
- for k, v in vars(self.parsed_data).items():
+ for k, v in vars(self.parsed_data).items():
if v is None:
# it was a flag that shares the name of an alias
subcs.append(self.alias_flags[k])
diff --git a/contrib/python/traitlets/py2/traitlets/config/manager.py b/contrib/python/traitlets/py2/traitlets/config/manager.py
index f5cf21904e..5e5ebde9af 100644
--- a/contrib/python/traitlets/py2/traitlets/config/manager.py
+++ b/contrib/python/traitlets/py2/traitlets/config/manager.py
@@ -7,7 +7,7 @@ import io
import json
import os
-from six import PY3
+from six import PY3
from traitlets.config import LoggingConfigurable
from traitlets.traitlets import Unicode
diff --git a/contrib/python/traitlets/py2/traitlets/log.py b/contrib/python/traitlets/py2/traitlets/log.py
index c7166c14c8..af86b325f5 100644
--- a/contrib/python/traitlets/py2/traitlets/log.py
+++ b/contrib/python/traitlets/py2/traitlets/log.py
@@ -9,19 +9,19 @@ _logger = None
def get_logger():
"""Grab the global logger instance.
-
+
If a global Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
-
+
if _logger is None:
from .config import Application
if Application.initialized():
_logger = Application.instance().log
else:
- _logger = logging.getLogger('traitlets')
- # Add a NullHandler to silence warnings about not being
- # initialized, per best practice for libraries.
- _logger.addHandler(logging.NullHandler())
+ _logger = logging.getLogger('traitlets')
+ # Add a NullHandler to silence warnings about not being
+ # initialized, per best practice for libraries.
+ _logger.addHandler(logging.NullHandler())
return _logger
diff --git a/contrib/python/traitlets/py2/traitlets/traitlets.py b/contrib/python/traitlets/py2/traitlets/traitlets.py
index b3134c819b..c07daf7400 100644
--- a/contrib/python/traitlets/py2/traitlets/traitlets.py
+++ b/contrib/python/traitlets/py2/traitlets/traitlets.py
@@ -42,11 +42,11 @@ Inheritance diagram:
import contextlib
import inspect
-import os
+import os
import re
import sys
import types
-import enum
+import enum
try:
from types import ClassType, InstanceType
ClassTypes = (ClassType, type)
@@ -54,12 +54,12 @@ except:
ClassTypes = (type,)
from warnings import warn, warn_explicit
-import six
+import six
from .utils.getargspec import getargspec
from .utils.importstring import import_item
from .utils.sentinel import Sentinel
-from .utils.bunch import Bunch
+from .utils.bunch import Bunch
SequenceTypes = (list, tuple, set, frozenset)
@@ -91,39 +91,39 @@ class TraitError(Exception):
# Utilities
#-----------------------------------------------------------------------------
-from ipython_genutils.py3compat import cast_unicode_py2
-
-_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
-
-def isidentifier(s):
- if six.PY2:
- return bool(_name_re.match(s))
- else:
- return s.isidentifier()
-
-_deprecations_shown = set()
-def _should_warn(key):
- """Add our own checks for too many deprecation warnings.
-
- Limit to once per package.
- """
- env_flag = os.environ.get('TRAITLETS_ALL_DEPRECATIONS')
- if env_flag and env_flag != '0':
- return True
-
- if key not in _deprecations_shown:
- _deprecations_shown.add(key)
- return True
- else:
- return False
-
+from ipython_genutils.py3compat import cast_unicode_py2
+
+_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
+
+def isidentifier(s):
+ if six.PY2:
+ return bool(_name_re.match(s))
+ else:
+ return s.isidentifier()
+
+_deprecations_shown = set()
+def _should_warn(key):
+ """Add our own checks for too many deprecation warnings.
+
+ Limit to once per package.
+ """
+ env_flag = os.environ.get('TRAITLETS_ALL_DEPRECATIONS')
+ if env_flag and env_flag != '0':
+ return True
+
+ if key not in _deprecations_shown:
+ _deprecations_shown.add(key)
+ return True
+ else:
+ return False
+
def _deprecated_method(method, cls, method_name, msg):
"""Show deprecation warning about a magic method definition.
Uses warn_explicit to bind warning to method definition instead of triggering code,
which isn't relevant.
"""
- warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
+ warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
classname=cls.__name__, method_name=method_name, msg=msg
)
@@ -131,15 +131,15 @@ def _deprecated_method(method, cls, method_name, msg):
if method_name in parent.__dict__:
cls = parent
break
- # limit deprecation messages to once per package
- package_name = cls.__module__.split('.', 1)[0]
- key = (package_name, msg)
- if not _should_warn(key):
- return
+ # limit deprecation messages to once per package
+ package_name = cls.__module__.split('.', 1)[0]
+ key = (package_name, msg)
+ if not _should_warn(key):
+ return
try:
fname = inspect.getsourcefile(method) or "<unknown>"
lineno = inspect.getsourcelines(method)[1] or 0
- except (IOError, TypeError) as e:
+ except (IOError, TypeError) as e:
# Failed to inspect for some reason
warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning)
else:
@@ -150,7 +150,7 @@ def class_of(object):
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
- if isinstance( object, six.string_types ):
+ if isinstance( object, six.string_types ):
return add_article( object )
return add_article( object.__class__.__name__ )
@@ -171,7 +171,7 @@ def repr_type(obj):
error messages.
"""
the_type = type(obj)
- if six.PY2 and the_type is InstanceType:
+ if six.PY2 and the_type is InstanceType:
# Old-style class.
the_type = obj.__class__
msg = '%r %r' % (obj, the_type)
@@ -200,14 +200,14 @@ def parse_notifier_name(names):
>>> parse_notifier_name(All)
[All]
"""
- if names is All or isinstance(names, six.string_types):
+ if names is All or isinstance(names, six.string_types):
return [names]
- else:
+ else:
if not names or All in names:
return [All]
for n in names:
- if not isinstance(n, six.string_types):
- raise TypeError("names must be strings, not %r" % n)
+ if not isinstance(n, six.string_types):
+ raise TypeError("names must be strings, not %r" % n)
return names
@@ -288,13 +288,13 @@ class link(object):
if self.updating:
return
with self._busy_updating():
- setattr(self.target[0], self.target[1], change.new)
+ setattr(self.target[0], self.target[1], change.new)
def _update_source(self, change):
if self.updating:
return
with self._busy_updating():
- setattr(self.source[0], self.source[1], change.new)
+ setattr(self.source[0], self.source[1], change.new)
def unlink(self):
self.source[0].unobserve(self._update_target, names=self.source[1])
@@ -344,7 +344,7 @@ class directional_link(object):
return
with self._busy_updating():
setattr(self.target[0], self.target[1],
- self._transform(change.new))
+ self._transform(change.new))
def unlink(self):
self.source[0].unobserve(self._update, names=self.source[1])
@@ -354,7 +354,7 @@ dlink = directional_link
#-----------------------------------------------------------------------------
-# Base Descriptor Class
+# Base Descriptor Class
#-----------------------------------------------------------------------------
@@ -429,32 +429,32 @@ class TraitType(BaseDescriptor):
"""
if default_value is not Undefined:
self.default_value = default_value
- if allow_none:
+ if allow_none:
self.allow_none = allow_none
if read_only is not None:
self.read_only = read_only
self.help = help if help is not None else ''
- if len(kwargs) > 0:
+ if len(kwargs) > 0:
stacklevel = 1
f = inspect.currentframe()
# count supers to determine stacklevel for warning
while f.f_code.co_name == '__init__':
stacklevel += 1
f = f.f_back
- mod = f.f_globals.get('__name__') or ''
- pkg = mod.split('.', 1)[0]
- key = tuple(['metadata-tag', pkg] + sorted(kwargs))
- if _should_warn(key):
- warn("metadata %s was set from the constructor. "
- "With traitlets 4.1, metadata should be set using the .tag() method, "
- "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
- DeprecationWarning, stacklevel=stacklevel)
+ mod = f.f_globals.get('__name__') or ''
+ pkg = mod.split('.', 1)[0]
+ key = tuple(['metadata-tag', pkg] + sorted(kwargs))
+ if _should_warn(key):
+ warn("metadata %s was set from the constructor. "
+ "With traitlets 4.1, metadata should be set using the .tag() method, "
+ "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
+ DeprecationWarning, stacklevel=stacklevel)
if len(self.metadata) > 0:
self.metadata = self.metadata.copy()
- self.metadata.update(kwargs)
+ self.metadata.update(kwargs)
else:
- self.metadata = kwargs
+ self.metadata = kwargs
else:
self.metadata = self.metadata.copy()
if config is not None:
@@ -470,14 +470,14 @@ class TraitType(BaseDescriptor):
Use self.default_value instead
"""
- warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
+ warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
stacklevel=2)
return self.default_value
def init_default_value(self, obj):
"""DEPRECATED: Set the static default value for the trait type.
"""
- warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
+ warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
stacklevel=2)
value = self._validate(obj, self.default_value)
obj._trait_values[self.name] = value
@@ -488,7 +488,7 @@ class TraitType(BaseDescriptor):
This looks for:
- * default generators registered with the @default descriptor.
+ * default generators registered with the @default descriptor.
* obj._{name}_default() on the class with the traitlet, or a subclass
that obj belongs to.
* trait.make_dynamic_default, which is defined by Instance
@@ -516,14 +516,14 @@ class TraitType(BaseDescriptor):
def instance_init(self, obj):
# If no dynamic initialiser is present, and the trait implementation or
# use provides a static default, transfer that to obj._trait_values.
- with obj.cross_validation_lock:
- if (self._dynamic_default_callable(obj) is None) \
- and (self.default_value is not Undefined):
- v = self._validate(obj, self.default_value)
- if self.name is not None:
- obj._trait_values[self.name] = v
-
- def get(self, obj, cls=None):
+ with obj.cross_validation_lock:
+ if (self._dynamic_default_callable(obj) is None) \
+ and (self.default_value is not Undefined):
+ v = self._validate(obj, self.default_value)
+ if self.name is not None:
+ obj._trait_values[self.name] = v
+
+ def get(self, obj, cls=None):
try:
value = obj._trait_values[self.name]
except KeyError:
@@ -595,7 +595,7 @@ class TraitType(BaseDescriptor):
def _cross_validate(self, obj, value):
if self.name in obj._trait_validators:
- proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
+ proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
value = obj._trait_validators[self.name](obj, proposal)
elif hasattr(obj, '_%s_validate' % self.name):
meth_name = '_%s_validate' % self.name
@@ -633,7 +633,7 @@ class TraitType(BaseDescriptor):
msg = "use the instance .help string directly, like x.help"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
- warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
+ warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
return self.metadata.get(key, default)
def set_metadata(self, key, value):
@@ -645,7 +645,7 @@ class TraitType(BaseDescriptor):
msg = "use the instance .help string directly, like x.help = value"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
- warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
+ warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
self.metadata[key] = value
def tag(self, **metadata):
@@ -655,11 +655,11 @@ class TraitType(BaseDescriptor):
>>> Int(0).tag(config=True, sync=True)
"""
- maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
- if maybe_constructor_keywords:
- warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
- maybe_constructor_keywords, UserWarning, stacklevel=2)
-
+ maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
+ if maybe_constructor_keywords:
+ warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
+ maybe_constructor_keywords, UserWarning, stacklevel=2)
+
self.metadata.update(metadata)
return self
@@ -697,13 +697,13 @@ class _CallbackWrapper(object):
if self.nargs == 0:
self.cb()
elif self.nargs == 1:
- self.cb(change.name)
+ self.cb(change.name)
elif self.nargs == 2:
- self.cb(change.name, change.new)
+ self.cb(change.name, change.new)
elif self.nargs == 3:
- self.cb(change.name, change.old, change.new)
+ self.cb(change.name, change.old, change.new)
elif self.nargs == 4:
- self.cb(change.name, change.old, change.new, change.owner)
+ self.cb(change.name, change.old, change.new, change.owner)
def _callback_wrapper(cb):
if isinstance(cb, _CallbackWrapper):
@@ -721,13 +721,13 @@ class MetaHasDescriptors(type):
def __new__(mcls, name, bases, classdict):
"""Create the HasDescriptors class."""
- for k, v in classdict.items():
+ for k, v in classdict.items():
# ----------------------------------------------------------------
# Support of deprecated behavior allowing for TraitType types
# to be used instead of TraitType instances.
if inspect.isclass(v) and issubclass(v, TraitType):
- warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
- " Passing types is deprecated in traitlets 4.1.",
+ warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
+ " Passing types is deprecated in traitlets 4.1.",
DeprecationWarning, stacklevel=2)
classdict[k] = v()
# ----------------------------------------------------------------
@@ -746,7 +746,7 @@ class MetaHasDescriptors(type):
BaseDescriptor in the class dict of the newly created ``cls`` before
calling their :attr:`class_init` method.
"""
- for k, v in classdict.items():
+ for k, v in classdict.items():
if isinstance(v, BaseDescriptor):
v.class_init(cls, k)
@@ -762,10 +762,10 @@ class MetaHasTraits(MetaHasDescriptors):
def observe(*names, **kwargs):
"""A decorator which can be used to observe Traits on a class.
- The handler passed to the decorator will be called with one ``change``
- dict argument. The change dictionary at least holds a 'type' key and a
- 'name' key, corresponding respectively to the type of notification and the
- name of the attribute that triggered the notification.
+ The handler passed to the decorator will be called with one ``change``
+ dict argument. The change dictionary at least holds a 'type' key and a
+ 'name' key, corresponding respectively to the type of notification and the
+ name of the attribute that triggered the notification.
Other keys may be passed depending on the value of 'type'. In the case
where type is 'change', we also have the following keys:
@@ -778,27 +778,27 @@ def observe(*names, **kwargs):
----------
*names
The str names of the Traits to observe on the object.
- type: str, kwarg-only
- The type of event to observe (e.g. 'change')
+ type: str, kwarg-only
+ The type of event to observe (e.g. 'change')
"""
- if not names:
- raise TypeError("Please specify at least one trait name to observe.")
- for name in names:
- if name is not All and not isinstance(name, six.string_types):
- raise TypeError("trait names to observe must be strings or All, not %r" % name)
+ if not names:
+ raise TypeError("Please specify at least one trait name to observe.")
+ for name in names:
+ if name is not All and not isinstance(name, six.string_types):
+ raise TypeError("trait names to observe must be strings or All, not %r" % name)
return ObserveHandler(names, type=kwargs.get('type', 'change'))
def observe_compat(func):
"""Backward-compatibility shim decorator for observers
-
+
Use with:
-
+
@observe('name')
@observe_compat
def _foo_changed(self, change):
...
-
+
With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
Allows adoption of new observer API without breaking subclasses that override and super.
"""
@@ -807,15 +807,15 @@ def observe_compat(func):
change = change_or_name
else:
clsname = self.__class__.__name__
- warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
+ warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
clsname, change_or_name), DeprecationWarning)
- change = Bunch(
- type='change',
- old=old,
- new=new,
- name=change_or_name,
- owner=self,
- )
+ change = Bunch(
+ type='change',
+ old=old,
+ new=new,
+ name=change_or_name,
+ owner=self,
+ )
return func(self, change)
return compatible_observer
@@ -837,18 +837,18 @@ def validate(*names):
Notes
-----
- Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
+ Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
the registered cross validator could potentially make changes to attributes
of the ``HasTraits`` instance. However, we recommend not to do so. The reason
is that the cross-validation of attributes may run in arbitrary order when
- exiting the ``hold_trait_notifications`` context, and such changes may not
+ exiting the ``hold_trait_notifications`` context, and such changes may not
commute.
"""
- if not names:
- raise TypeError("Please specify at least one trait name to validate.")
- for name in names:
- if name is not All and not isinstance(name, six.string_types):
- raise TypeError("trait names to validate must be strings or All, not %r" % name)
+ if not names:
+ raise TypeError("Please specify at least one trait name to validate.")
+ for name in names:
+ if name is not All and not isinstance(name, six.string_types):
+ raise TypeError("trait names to validate must be strings or All, not %r" % name)
return ValidateHandler(names)
@@ -890,8 +890,8 @@ def default(name):
return 3.0 # ignored since it is defined in a
# class derived from B.a.this_class.
"""
- if not isinstance(name, six.string_types):
- raise TypeError("Trait name must be a string or All, not %r" % name)
+ if not isinstance(name, six.string_types):
+ raise TypeError("Trait name must be a string or All, not %r" % name)
return DefaultHandler(name)
@@ -902,7 +902,7 @@ class EventHandler(BaseDescriptor):
return self
def __call__(self, *args, **kwargs):
- """Pass `*args` and `**kwargs` to the handler's function if it exists."""
+ """Pass `*args` and `**kwargs` to the handler's function if it exists."""
if hasattr(self, 'func'):
return self.func(*args, **kwargs)
else:
@@ -943,26 +943,26 @@ class DefaultHandler(EventHandler):
cls._trait_default_generators[self.trait_name] = self
-class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
+class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
"""The base class for all classes that have descriptors.
"""
- def __new__(cls, *args, **kwargs):
+ def __new__(cls, *args, **kwargs):
# This is needed because object.__new__ only accepts
# the cls argument.
new_meth = super(HasDescriptors, cls).__new__
if new_meth is object.__new__:
inst = new_meth(cls)
else:
- inst = new_meth(cls, *args, **kwargs)
- inst.setup_instance(*args, **kwargs)
+ inst = new_meth(cls, *args, **kwargs)
+ inst.setup_instance(*args, **kwargs)
return inst
- def setup_instance(self, *args, **kwargs):
- """
- This is called **before** self.__init__ is called.
- """
- self._cross_validation_lock = False
+ def setup_instance(self, *args, **kwargs):
+ """
+ This is called **before** self.__init__ is called.
+ """
+ self._cross_validation_lock = False
cls = self.__class__
for key in dir(cls):
# Some descriptors raise AttributeError like zope.interface's
@@ -977,46 +977,46 @@ class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
value.instance_init(self)
-class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
+class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
- def setup_instance(self, *args, **kwargs):
+ def setup_instance(self, *args, **kwargs):
self._trait_values = {}
self._trait_notifiers = {}
self._trait_validators = {}
- super(HasTraits, self).setup_instance(*args, **kwargs)
+ super(HasTraits, self).setup_instance(*args, **kwargs)
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args, **kwargs):
# Allow trait values to be set using keyword arguments.
# We need to use setattr for this to trigger validation and
# notifications.
- super_args = args
- super_kwargs = {}
+ super_args = args
+ super_kwargs = {}
with self.hold_trait_notifications():
- for key, value in kwargs.items():
- if self.has_trait(key):
- setattr(self, key, value)
- else:
- # passthrough args that don't set traits to super
- super_kwargs[key] = value
- try:
- super(HasTraits, self).__init__(*super_args, **super_kwargs)
- except TypeError as e:
- arg_s_list = [ repr(arg) for arg in super_args ]
- for k, v in super_kwargs.items():
- arg_s_list.append("%s=%r" % (k, v))
- arg_s = ', '.join(arg_s_list)
- warn(
- "Passing unrecoginized arguments to super({classname}).__init__({arg_s}).\n"
- "{error}\n"
- "This is deprecated in traitlets 4.2."
- "This error will be raised in a future release of traitlets."
- .format(
- arg_s=arg_s, classname=self.__class__.__name__,
- error=e,
- ),
- DeprecationWarning,
- stacklevel=2,
- )
+ for key, value in kwargs.items():
+ if self.has_trait(key):
+ setattr(self, key, value)
+ else:
+ # passthrough args that don't set traits to super
+ super_kwargs[key] = value
+ try:
+ super(HasTraits, self).__init__(*super_args, **super_kwargs)
+ except TypeError as e:
+ arg_s_list = [ repr(arg) for arg in super_args ]
+ for k, v in super_kwargs.items():
+ arg_s_list.append("%s=%r" % (k, v))
+ arg_s = ', '.join(arg_s_list)
+ warn(
+ "Passing unrecoginized arguments to super({classname}).__init__({arg_s}).\n"
+ "{error}\n"
+ "This is deprecated in traitlets 4.2."
+ "This error will be raised in a future release of traitlets."
+ .format(
+ arg_s=arg_s, classname=self.__class__.__name__,
+ error=e,
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
def __getstate__(self):
d = self.__dict__.copy()
@@ -1044,27 +1044,27 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
if isinstance(value, EventHandler):
value.instance_init(self)
- @property
+ @property
+ @contextlib.contextmanager
+ def cross_validation_lock(self):
+ """
+ A contextmanager for running a block with our cross validation lock set
+ to True.
+
+ At the end of the block, the lock's value is restored to its value
+ prior to entering the block.
+ """
+ if self._cross_validation_lock:
+ yield
+ return
+ else:
+ try:
+ self._cross_validation_lock = True
+ yield
+ finally:
+ self._cross_validation_lock = False
+
@contextlib.contextmanager
- def cross_validation_lock(self):
- """
- A contextmanager for running a block with our cross validation lock set
- to True.
-
- At the end of the block, the lock's value is restored to its value
- prior to entering the block.
- """
- if self._cross_validation_lock:
- yield
- return
- else:
- try:
- self._cross_validation_lock = True
- yield
- finally:
- self._cross_validation_lock = False
-
- @contextlib.contextmanager
def hold_trait_notifications(self):
"""Context manager for bundling trait change notifications and cross
validation.
@@ -1073,7 +1073,7 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
race conditions in trait notifiers requesting other trait values.
All trait notifications will fire after all values have been assigned.
"""
- if self._cross_validation_lock:
+ if self._cross_validation_lock:
yield
return
else:
@@ -1085,15 +1085,15 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
if past_changes is None:
return [change]
else:
- if past_changes[-1]['type'] == 'change' and change.type == 'change':
- past_changes[-1]['new'] = change.new
+ if past_changes[-1]['type'] == 'change' and change.type == 'change':
+ past_changes[-1]['new'] = change.new
else:
# In case of changes other than 'change', append the notification.
past_changes.append(change)
return past_changes
def hold(change):
- name = change.name
+ name = change.name
cache[name] = compress(cache.get(name), change)
try:
@@ -1106,24 +1106,24 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
for name in list(cache.keys()):
trait = getattr(self.__class__, name)
value = trait._cross_validate(self, getattr(self, name))
- self.set_trait(name, value)
+ self.set_trait(name, value)
except TraitError as e:
# Roll back in case of TraitError during final cross validation.
self.notify_change = lambda x: None
for name, changes in cache.items():
for change in changes[::-1]:
# TODO: Separate in a rollback function per notification type.
- if change.type == 'change':
- if change.old is not Undefined:
- self.set_trait(name, change.old)
+ if change.type == 'change':
+ if change.old is not Undefined:
+ self.set_trait(name, change.old)
else:
self._trait_values.pop(name)
cache = {}
raise e
finally:
self._cross_validation_lock = False
- # Restore method retrieval from class
- del self.notify_change
+ # Restore method retrieval from class
+ del self.notify_change
# trigger delayed notifications
for changes in cache.values():
@@ -1131,19 +1131,19 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
self.notify_change(change)
def _notify_trait(self, name, old_value, new_value):
- self.notify_change(Bunch(
- name=name,
- old=old_value,
- new=new_value,
- owner=self,
- type='change',
- ))
+ self.notify_change(Bunch(
+ name=name,
+ old=old_value,
+ new=new_value,
+ owner=self,
+ type='change',
+ ))
def notify_change(self, change):
- if not isinstance(change, Bunch):
- # cast to bunch if given a dict
- change = Bunch(change)
- name, type = change.name, change.type
+ if not isinstance(change, Bunch):
+ # cast to bunch if given a dict
+ change = Bunch(change)
+ name, type = change.name, change.type
callables = []
callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
@@ -1170,9 +1170,9 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
if isinstance(c, _CallbackWrapper):
c = c.__call__
- elif isinstance(c, EventHandler) and c.name is not None:
+ elif isinstance(c, EventHandler) and c.name is not None:
c = getattr(self, c.name)
-
+
c(change)
def _add_notifiers(self, handler, name, type):
@@ -1225,7 +1225,7 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
If False (the default), then install the handler. If True
then unintall it.
"""
- warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
+ warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
DeprecationWarning, stacklevel=2)
if name is None:
name = All
@@ -1243,8 +1243,8 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
----------
handler : callable
A callable that is called when a trait changes. Its
- signature should be ``handler(change)``, where ``change`` is a
- dictionary. The change dictionary at least holds a 'type' key.
+ signature should be ``handler(change)``, where ``change`` is a
+ dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
@@ -1267,7 +1267,7 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
def unobserve(self, handler, names=All, type='change'):
"""Remove a trait change handler.
- This is used to unregister handlers to trait change notifications.
+ This is used to unregister handlers to trait change notifications.
Parameters
----------
@@ -1297,19 +1297,19 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
pass
def _register_validator(self, handler, names):
- """Setup a handler to be called when a trait should be cross validated.
+ """Setup a handler to be called when a trait should be cross validated.
This is used to setup dynamic notifications for cross-validation.
If a validator is already registered for any of the provided names, a
- TraitError is raised and no new validator is registered.
+ TraitError is raised and no new validator is registered.
Parameters
----------
handler : callable
A callable that is called when the given trait is cross-validated.
- Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
- with the following attributes/keys:
+ Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
+ with the following attributes/keys:
* ``owner`` : the HasTraits instance
* ``value`` : the proposed value for the modified trait attribute
* ``trait`` : the TraitType instance associated with the attribute
@@ -1326,22 +1326,22 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
for name in names:
self._trait_validators[name] = handler
- def add_traits(self, **traits):
- """Dynamically add trait attributes to the HasTraits instance."""
- self.__class__ = type(self.__class__.__name__, (self.__class__,),
- traits)
- for trait in traits.values():
- trait.instance_init(self)
-
- def set_trait(self, name, value):
- """Forcibly sets trait attribute, including read-only attributes."""
- cls = self.__class__
- if not self.has_trait(name):
- raise TraitError("Class %s does not have a trait named %s" %
- (cls.__name__, name))
- else:
- getattr(cls, name).set(self, value)
-
+ def add_traits(self, **traits):
+ """Dynamically add trait attributes to the HasTraits instance."""
+ self.__class__ = type(self.__class__.__name__, (self.__class__,),
+ traits)
+ for trait in traits.values():
+ trait.instance_init(self)
+
+ def set_trait(self, name, value):
+ """Forcibly sets trait attribute, including read-only attributes."""
+ cls = self.__class__
+ if not self.has_trait(name):
+ raise TraitError("Class %s does not have a trait named %s" %
+ (cls.__name__, name))
+ else:
+ getattr(cls, name).set(self, value)
+
@classmethod
def class_trait_names(cls, **metadata):
"""Get a list of all the names of this class' traits.
@@ -1349,7 +1349,7 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
This method is just like the :meth:`trait_names` method,
but is unbound.
"""
- return list(cls.class_traits(**metadata))
+ return list(cls.class_traits(**metadata))
@classmethod
def class_traits(cls, **metadata):
@@ -1399,10 +1399,10 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
def has_trait(self, name):
"""Returns True if the object has a trait with the specified name."""
return isinstance(getattr(self.__class__, name, None), TraitType)
-
+
def trait_names(self, **metadata):
"""Get a list of all the names of this class' traits."""
- return list(self.traits(**metadata))
+ return list(self.traits(**metadata))
def traits(self, **metadata):
"""Get a ``dict`` of all the traits of this class. The dictionary
@@ -1443,48 +1443,48 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
except AttributeError:
raise TraitError("Class %s does not have a trait named %s" %
(self.__class__.__name__, traitname))
- metadata_name = '_' + traitname + '_metadata'
- if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
- return getattr(self, metadata_name).get(key, default)
+ metadata_name = '_' + traitname + '_metadata'
+ if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
+ return getattr(self, metadata_name).get(key, default)
else:
return trait.metadata.get(key, default)
- @classmethod
- def class_own_trait_events(cls, name):
- """Get a dict of all event handlers defined on this class, not a parent.
-
- Works like ``event_handlers``, except for excluding traits from parents.
- """
- sup = super(cls, cls)
- return {n: e for (n, e) in cls.events(name).items()
- if getattr(sup, n, None) is not e}
-
- @classmethod
- def trait_events(cls, name=None):
- """Get a ``dict`` of all the event handlers of this class.
-
- Parameters
- ----------
- name: str (default: None)
- The name of a trait of this class. If name is ``None`` then all
- the event handlers of this class will be returned instead.
-
- Returns
- -------
- The event handlers associated with a trait name, or all event handlers.
- """
- events = {}
- for k, v in getmembers(cls):
- if isinstance(v, EventHandler):
- if name is None:
- events[k] = v
- elif name in v.trait_names:
- events[k] = v
- elif hasattr(v, 'tags'):
- if cls.trait_names(**v.tags):
- events[k] = v
- return events
-
+ @classmethod
+ def class_own_trait_events(cls, name):
+ """Get a dict of all event handlers defined on this class, not a parent.
+
+ Works like ``event_handlers``, except for excluding traits from parents.
+ """
+ sup = super(cls, cls)
+ return {n: e for (n, e) in cls.events(name).items()
+ if getattr(sup, n, None) is not e}
+
+ @classmethod
+ def trait_events(cls, name=None):
+ """Get a ``dict`` of all the event handlers of this class.
+
+ Parameters
+ ----------
+ name: str (default: None)
+ The name of a trait of this class. If name is ``None`` then all
+ the event handlers of this class will be returned instead.
+
+ Returns
+ -------
+ The event handlers associated with a trait name, or all event handlers.
+ """
+ events = {}
+ for k, v in getmembers(cls):
+ if isinstance(v, EventHandler):
+ if name is None:
+ events[k] = v
+ elif name in v.trait_names:
+ events[k] = v
+ elif hasattr(v, 'tags'):
+ if cls.trait_names(**v.tags):
+ events[k] = v
+ return events
+
#-----------------------------------------------------------------------------
# Actual TraitTypes implementations/subclasses
#-----------------------------------------------------------------------------
@@ -1508,7 +1508,7 @@ class ClassBasedTraitType(TraitType):
def error(self, obj, value):
kind = type(value)
- if six.PY2 and kind is InstanceType:
+ if six.PY2 and kind is InstanceType:
msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
@@ -1527,7 +1527,7 @@ class ClassBasedTraitType(TraitType):
class Type(ClassBasedTraitType):
"""A trait whose value must be a subclass of a specified class."""
- def __init__ (self, default_value=Undefined, klass=None, **kwargs):
+ def __init__ (self, default_value=Undefined, klass=None, **kwargs):
"""Construct a Type trait
A Type trait specifies that its values must be subclasses of
@@ -1562,16 +1562,16 @@ class Type(ClassBasedTraitType):
else:
klass = default_value
- if not (inspect.isclass(klass) or isinstance(klass, six.string_types)):
+ if not (inspect.isclass(klass) or isinstance(klass, six.string_types)):
raise TraitError("A Type trait must specify a class.")
self.klass = klass
- super(Type, self).__init__(new_default_value, **kwargs)
+ super(Type, self).__init__(new_default_value, **kwargs)
def validate(self, obj, value):
"""Validates that the value is a valid object instance."""
- if isinstance(value, six.string_types):
+ if isinstance(value, six.string_types):
try:
value = self._resolve_string(value)
except ImportError:
@@ -1587,10 +1587,10 @@ class Type(ClassBasedTraitType):
def info(self):
""" Returns a description of the trait."""
- if isinstance(self.klass, six.string_types):
+ if isinstance(self.klass, six.string_types):
klass = self.klass
else:
- klass = self.klass.__module__ + '.' + self.klass.__name__
+ klass = self.klass.__module__ + '.' + self.klass.__name__
result = "a subclass of '%s'" % klass
if self.allow_none:
return result + ' or None'
@@ -1601,14 +1601,14 @@ class Type(ClassBasedTraitType):
super(Type, self).instance_init(obj)
def _resolve_classes(self):
- if isinstance(self.klass, six.string_types):
+ if isinstance(self.klass, six.string_types):
self.klass = self._resolve_string(self.klass)
- if isinstance(self.default_value, six.string_types):
+ if isinstance(self.default_value, six.string_types):
self.default_value = self._resolve_string(self.default_value)
def default_value_repr(self):
value = self.default_value
- if isinstance(value, six.string_types):
+ if isinstance(value, six.string_types):
return repr(value)
else:
return repr('{}.{}'.format(value.__module__, value.__name__))
@@ -1624,7 +1624,7 @@ class Instance(ClassBasedTraitType):
klass = None
- def __init__(self, klass=None, args=None, kw=None, **kwargs):
+ def __init__(self, klass=None, args=None, kw=None, **kwargs):
"""Construct an Instance trait.
This trait allows values that are instances of a particular
@@ -1653,8 +1653,8 @@ class Instance(ClassBasedTraitType):
"""
if klass is None:
klass = self.klass
-
- if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, six.string_types)):
+
+ if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, six.string_types)):
self.klass = klass
else:
raise TraitError('The klass attribute must be a class'
@@ -1668,7 +1668,7 @@ class Instance(ClassBasedTraitType):
self.default_args = args
self.default_kwargs = kw
- super(Instance, self).__init__(**kwargs)
+ super(Instance, self).__init__(**kwargs)
def validate(self, obj, value):
if isinstance(value, self.klass):
@@ -1677,7 +1677,7 @@ class Instance(ClassBasedTraitType):
self.error(obj, value)
def info(self):
- if isinstance(self.klass, six.string_types):
+ if isinstance(self.klass, six.string_types):
klass = self.klass
else:
klass = self.klass.__name__
@@ -1692,7 +1692,7 @@ class Instance(ClassBasedTraitType):
super(Instance, self).instance_init(obj)
def _resolve_classes(self):
- if isinstance(self.klass, six.string_types):
+ if isinstance(self.klass, six.string_types):
self.klass = self._resolve_string(self.klass)
def make_dynamic_default(self):
@@ -1742,8 +1742,8 @@ class This(ClassBasedTraitType):
info_text = 'an instance of the same type as the receiver or None'
- def __init__(self, **kwargs):
- super(This, self).__init__(None, **kwargs)
+ def __init__(self, **kwargs):
+ super(This, self).__init__(None, **kwargs)
def validate(self, obj, value):
# What if value is a superclass of obj.__class__? This is
@@ -1758,7 +1758,7 @@ class This(ClassBasedTraitType):
class Union(TraitType):
"""A trait type representing a Union type."""
- def __init__(self, trait_types, **kwargs):
+ def __init__(self, trait_types, **kwargs):
"""Construct a Union trait.
This trait allows values that are allowed by at least one of the
@@ -1776,8 +1776,8 @@ class Union(TraitType):
with the validation function of Float, then Bool, and finally Int.
"""
self.trait_types = trait_types
- self.info_text = " or ".join([tt.info() for tt in self.trait_types])
- super(Union, self).__init__(**kwargs)
+ self.info_text = " or ".join([tt.info() for tt in self.trait_types])
+ super(Union, self).__init__(**kwargs)
def class_init(self, cls, name):
for trait_type in self.trait_types:
@@ -1790,13 +1790,13 @@ class Union(TraitType):
super(Union, self).instance_init(obj)
def validate(self, obj, value):
- with obj.cross_validation_lock:
+ with obj.cross_validation_lock:
for trait_type in self.trait_types:
try:
v = trait_type._validate(obj, value)
- # In the case of an element trait, the name is None
- if self.name is not None:
- setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
+ # In the case of an element trait, the name is None
+ if self.name is not None:
+ setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
return v
except TraitError:
continue
@@ -1808,16 +1808,16 @@ class Union(TraitType):
else:
return Union(self.trait_types + [other])
- def make_dynamic_default(self):
- if self.default_value is not Undefined:
- return self.default_value
- for trait_type in self.trait_types:
- if trait_type.default_value is not Undefined:
- return trait_type.default_value
- elif hasattr(trait_type, 'make_dynamic_default'):
- return trait_type.make_dynamic_default()
-
-
+ def make_dynamic_default(self):
+ if self.default_value is not Undefined:
+ return self.default_value
+ for trait_type in self.trait_types:
+ if trait_type.default_value is not Undefined:
+ return trait_type.default_value
+ elif hasattr(trait_type, 'make_dynamic_default'):
+ return trait_type.make_dynamic_default()
+
+
#-----------------------------------------------------------------------------
# Basic TraitTypes implementations/subclasses
#-----------------------------------------------------------------------------
@@ -1829,37 +1829,37 @@ class Any(TraitType):
info_text = 'any value'
-def _validate_bounds(trait, obj, value):
- """
- Validate that a number to be applied to a trait is between bounds.
-
- If value is not between min_bound and max_bound, this raises a
- TraitError with an error message appropriate for this trait.
- """
- if trait.min is not None and value < trait.min:
- raise TraitError(
- "The value of the '{name}' trait of {klass} instance should "
- "not be less than {min_bound}, but a value of {value} was "
- "specified".format(
- name=trait.name, klass=class_of(obj),
- value=value, min_bound=trait.min))
- if trait.max is not None and value > trait.max:
- raise TraitError(
- "The value of the '{name}' trait of {klass} instance should "
- "not be greater than {max_bound}, but a value of {value} was "
- "specified".format(
- name=trait.name, klass=class_of(obj),
- value=value, max_bound=trait.max))
- return value
-
-
+def _validate_bounds(trait, obj, value):
+ """
+ Validate that a number to be applied to a trait is between bounds.
+
+ If value is not between min_bound and max_bound, this raises a
+ TraitError with an error message appropriate for this trait.
+ """
+ if trait.min is not None and value < trait.min:
+ raise TraitError(
+ "The value of the '{name}' trait of {klass} instance should "
+ "not be less than {min_bound}, but a value of {value} was "
+ "specified".format(
+ name=trait.name, klass=class_of(obj),
+ value=value, min_bound=trait.min))
+ if trait.max is not None and value > trait.max:
+ raise TraitError(
+ "The value of the '{name}' trait of {klass} instance should "
+ "not be greater than {max_bound}, but a value of {value} was "
+ "specified".format(
+ name=trait.name, klass=class_of(obj),
+ value=value, max_bound=trait.max))
+ return value
+
+
class Int(TraitType):
"""An int trait."""
default_value = 0
info_text = 'an int'
- def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
+ def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
self.min = kwargs.pop('min', None)
self.max = kwargs.pop('max', None)
super(Int, self).__init__(default_value=default_value,
@@ -1868,7 +1868,7 @@ class Int(TraitType):
def validate(self, obj, value):
if not isinstance(value, int):
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
class CInt(Int):
@@ -1876,49 +1876,49 @@ class CInt(Int):
def validate(self, obj, value):
try:
- value = int(value)
+ value = int(value)
except:
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
+
-
-if six.PY2:
+if six.PY2:
class Long(TraitType):
"""A long integer trait."""
default_value = 0
info_text = 'a long'
- def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
- self.min = kwargs.pop('min', None)
- self.max = kwargs.pop('max', None)
- super(Long, self).__init__(
- default_value=default_value,
- allow_none=allow_none, **kwargs)
-
- def _validate_long(self, obj, value):
+ def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
+ self.min = kwargs.pop('min', None)
+ self.max = kwargs.pop('max', None)
+ super(Long, self).__init__(
+ default_value=default_value,
+ allow_none=allow_none, **kwargs)
+
+ def _validate_long(self, obj, value):
if isinstance(value, long):
return value
if isinstance(value, int):
return long(value)
self.error(obj, value)
- def validate(self, obj, value):
- value = self._validate_long(obj, value)
- return _validate_bounds(self, obj, value)
+ def validate(self, obj, value):
+ value = self._validate_long(obj, value)
+ return _validate_bounds(self, obj, value)
+
-
class CLong(Long):
"""A casting version of the long integer trait."""
def validate(self, obj, value):
try:
- value = long(value)
+ value = long(value)
except:
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
+
-
class Integer(TraitType):
"""An integer trait.
@@ -1927,14 +1927,14 @@ if six.PY2:
default_value = 0
info_text = 'an integer'
- def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
- self.min = kwargs.pop('min', None)
- self.max = kwargs.pop('max', None)
- super(Integer, self).__init__(
- default_value=default_value,
- allow_none=allow_none, **kwargs)
-
- def _validate_int(self, obj, value):
+ def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
+ self.min = kwargs.pop('min', None)
+ self.max = kwargs.pop('max', None)
+ super(Integer, self).__init__(
+ default_value=default_value,
+ allow_none=allow_none, **kwargs)
+
+ def _validate_int(self, obj, value):
if isinstance(value, int):
return value
if isinstance(value, long):
@@ -1948,25 +1948,25 @@ if six.PY2:
return int(value)
self.error(obj, value)
- def validate(self, obj, value):
- value = self._validate_int(obj, value)
- return _validate_bounds(self, obj, value)
+ def validate(self, obj, value):
+ value = self._validate_int(obj, value)
+ return _validate_bounds(self, obj, value)
+
+else:
+ Long, CLong = Int, CInt
+ Integer = Int
+
-else:
- Long, CLong = Int, CInt
- Integer = Int
-
-
class Float(TraitType):
"""A float trait."""
default_value = 0.0
info_text = 'a float'
- def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
+ def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
self.min = kwargs.pop('min', -float('inf'))
self.max = kwargs.pop('max', float('inf'))
- super(Float, self).__init__(default_value=default_value,
+ super(Float, self).__init__(default_value=default_value,
allow_none=allow_none, **kwargs)
def validate(self, obj, value):
@@ -1974,7 +1974,7 @@ class Float(TraitType):
value = float(value)
if not isinstance(value, float):
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
class CFloat(Float):
@@ -1982,12 +1982,12 @@ class CFloat(Float):
def validate(self, obj, value):
try:
- value = float(value)
+ value = float(value)
except:
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
+
-
class Complex(TraitType):
"""A trait for complex numbers."""
@@ -2043,7 +2043,7 @@ class Unicode(TraitType):
info_text = 'a unicode string'
def validate(self, obj, value):
- if isinstance(value, six.text_type):
+ if isinstance(value, six.text_type):
return value
if isinstance(value, bytes):
try:
@@ -2059,7 +2059,7 @@ class CUnicode(Unicode):
def validate(self, obj, value):
try:
- return six.text_type(value)
+ return six.text_type(value)
except:
self.error(obj, value)
@@ -2070,7 +2070,7 @@ class ObjectName(TraitType):
This does not check that the name exists in any scope."""
info_text = "a valid object identifier in Python"
- if six.PY2:
+ if six.PY2:
# Python 2:
def coerce_str(self, obj, value):
"In Python 2, coerce ascii-only unicode to str"
@@ -2080,13 +2080,13 @@ class ObjectName(TraitType):
except UnicodeEncodeError:
self.error(obj, value)
return value
- else:
- coerce_str = staticmethod(lambda _,s: s)
+ else:
+ coerce_str = staticmethod(lambda _,s: s)
def validate(self, obj, value):
value = self.coerce_str(obj, value)
- if isinstance(value, six.string_types) and isidentifier(value):
+ if isinstance(value, six.string_types) and isidentifier(value):
return value
self.error(obj, value)
@@ -2095,8 +2095,8 @@ class DottedObjectName(ObjectName):
def validate(self, obj, value):
value = self.coerce_str(obj, value)
- if isinstance(value, six.string_types) and all(isidentifier(a)
- for a in value.split('.')):
+ if isinstance(value, six.string_types) and all(isidentifier(a)
+ for a in value.split('.')):
return value
self.error(obj, value)
@@ -2126,11 +2126,11 @@ class CBool(Bool):
class Enum(TraitType):
"""An enum whose value must be in a given sequence."""
- def __init__(self, values, default_value=Undefined, **kwargs):
+ def __init__(self, values, default_value=Undefined, **kwargs):
self.values = values
- if kwargs.get('allow_none', False) and default_value is Undefined:
+ if kwargs.get('allow_none', False) and default_value is Undefined:
default_value = None
- super(Enum, self).__init__(default_value, **kwargs)
+ super(Enum, self).__init__(default_value, **kwargs)
def validate(self, obj, value):
if value in self.values:
@@ -2146,15 +2146,15 @@ class Enum(TraitType):
class CaselessStrEnum(Enum):
"""An enum of strings where the case should be ignored."""
-
- def __init__(self, values, default_value=Undefined, **kwargs):
- values = [cast_unicode_py2(value) for value in values]
- super(CaselessStrEnum, self).__init__(values, default_value=default_value, **kwargs)
-
+
+ def __init__(self, values, default_value=Undefined, **kwargs):
+ values = [cast_unicode_py2(value) for value in values]
+ super(CaselessStrEnum, self).__init__(values, default_value=default_value, **kwargs)
+
def validate(self, obj, value):
if isinstance(value, str):
- value = cast_unicode_py2(value)
- if not isinstance(value, six.string_types):
+ value = cast_unicode_py2(value)
+ if not isinstance(value, six.string_types):
self.error(obj, value)
for v in self.values:
@@ -2172,7 +2172,7 @@ class Container(Instance):
_valid_defaults = SequenceTypes
_trait = None
- def __init__(self, trait=None, default_value=None, **kwargs):
+ def __init__(self, trait=None, default_value=None, **kwargs):
"""Create a container trait type from a list, set, or tuple.
The default value is created by doing ``List(default_value)``,
@@ -2200,7 +2200,7 @@ class Container(Instance):
allow_none : bool [ default False ]
Whether to allow the value to be None
- **kwargs : any
+ **kwargs : any
further keys for extensions to the Trait (e.g. config)
"""
@@ -2218,14 +2218,14 @@ class Container(Instance):
if is_trait(trait):
if isinstance(trait, type):
- warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
- " Passing types is deprecated in traitlets 4.1.",
+ warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
+ " Passing types is deprecated in traitlets 4.1.",
DeprecationWarning, stacklevel=3)
self._trait = trait() if isinstance(trait, type) else trait
elif trait is not None:
raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
- super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
+ super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
def element_error(self, obj, element, validator):
e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
@@ -2272,7 +2272,7 @@ class List(Container):
klass = list
_cast_types = (tuple,)
- def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **kwargs):
+ def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **kwargs):
"""Create a List trait type from a list, set, or tuple.
The default value is created by doing ``list(default_value)``,
@@ -2306,7 +2306,7 @@ class List(Container):
self._minlen = minlen
self._maxlen = maxlen
super(List, self).__init__(trait=trait, default_value=default_value,
- **kwargs)
+ **kwargs)
def length_error(self, obj, value):
e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
@@ -2333,7 +2333,7 @@ class Set(List):
# Redefine __init__ just to make the docstring more accurate.
def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,
- **kwargs):
+ **kwargs):
"""Create a Set trait type from a list, set, or tuple.
The default value is created by doing ``set(default_value)``,
@@ -2364,7 +2364,7 @@ class Set(List):
maxlen : Int [ default sys.maxsize ]
The maximum length of the input list
"""
- super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
+ super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
class Tuple(Container):
@@ -2372,7 +2372,7 @@ class Tuple(Container):
klass = tuple
_cast_types = (list,)
- def __init__(self, *traits, **kwargs):
+ def __init__(self, *traits, **kwargs):
"""Create a tuple from a list, set, or tuple.
Create a fixed-type tuple with Traits:
@@ -2402,7 +2402,7 @@ class Tuple(Container):
will be cast to a tuple. If ``traits`` are specified,
``default_value`` must conform to the shape and type they specify.
"""
- default_value = kwargs.pop('default_value', Undefined)
+ default_value = kwargs.pop('default_value', Undefined)
# allow Tuple((values,)):
if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
default_value = traits[0]
@@ -2418,8 +2418,8 @@ class Tuple(Container):
self._traits = []
for trait in traits:
if isinstance(trait, type):
- warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
- " Passing types is deprecated in traitlets 4.1.",
+ warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
+ " Passing types is deprecated in traitlets 4.1.",
DeprecationWarning, stacklevel=2)
t = trait() if isinstance(trait, type) else trait
self._traits.append(t)
@@ -2427,7 +2427,7 @@ class Tuple(Container):
if self._traits and default_value is None:
# don't allow default to be an empty container if length is specified
args = None
- super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
+ super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
def validate_elements(self, obj, value):
if not self._traits:
@@ -2466,22 +2466,22 @@ class Dict(Instance):
_trait = None
def __init__(self, trait=None, traits=None, default_value=Undefined,
- **kwargs):
- """Create a dict trait type from a Python dict.
+ **kwargs):
+ """Create a dict trait type from a Python dict.
The default value is created by doing ``dict(default_value)``,
which creates a copy of the ``default_value``.
- Parameters
- ----------
-
+ Parameters
+ ----------
+
trait : TraitType [ optional ]
- The specified trait type to check and use to restrict contents of
- the Container. If unspecified, trait types are not checked.
+ The specified trait type to check and use to restrict contents of
+ the Container. If unspecified, trait types are not checked.
- traits : Dictionary of trait types [ optional ]
- A Python dictionary containing the types that are valid for
- restricting the content of the Dict Container for certain keys.
+ traits : Dictionary of trait types [ optional ]
+ A Python dictionary containing the types that are valid for
+ restricting the content of the Dict Container for certain keys.
default_value : SequenceType [ optional ]
The default value for the Dict. Must be dict, tuple, or None, and
@@ -2509,8 +2509,8 @@ class Dict(Instance):
# Case where a type of TraitType is provided rather than an instance
if is_trait(trait):
if isinstance(trait, type):
- warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
- " Passing types is deprecated in traitlets 4.1.",
+ warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
+ " Passing types is deprecated in traitlets 4.1.",
DeprecationWarning, stacklevel=2)
self._trait = trait() if isinstance(trait, type) else trait
elif trait is not None:
@@ -2518,7 +2518,7 @@ class Dict(Instance):
self._traits = traits
- super(Dict, self).__init__(klass=dict, args=args, **kwargs)
+ super(Dict, self).__init__(klass=dict, args=args, **kwargs)
def element_error(self, obj, element, validator):
e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
@@ -2533,26 +2533,26 @@ class Dict(Instance):
return value
def validate_elements(self, obj, value):
- use_dict = bool(self._traits)
- default_to = (self._trait or Any())
- if not use_dict and isinstance(default_to, Any):
+ use_dict = bool(self._traits)
+ default_to = (self._trait or Any())
+ if not use_dict and isinstance(default_to, Any):
return value
-
+
validated = {}
for key in value:
- if use_dict and key in self._traits:
- validate_with = self._traits[key]
- else:
- validate_with = default_to
+ if use_dict and key in self._traits:
+ validate_with = self._traits[key]
+ else:
+ validate_with = default_to
try:
- v = value[key]
- if not isinstance(validate_with, Any):
- v = validate_with._validate(obj, v)
+ v = value[key]
+ if not isinstance(validate_with, Any):
+ v = validate_with._validate(obj, v)
except TraitError:
- self.element_error(obj, v, validate_with)
+ self.element_error(obj, v, validate_with)
else:
validated[key] = v
-
+
return self.klass(validated)
def class_init(self, cls, name):
@@ -2584,7 +2584,7 @@ class TCPAddress(TraitType):
def validate(self, obj, value):
if isinstance(value, tuple):
if len(value) == 2:
- if isinstance(value[0], six.string_types) and isinstance(value[1], int):
+ if isinstance(value[0], six.string_types) and isinstance(value[1], int):
port = value[1]
if port >= 0 and port <= 65535:
return value
@@ -2603,88 +2603,88 @@ class CRegExp(TraitType):
return re.compile(value)
except:
self.error(obj, value)
-
-
-class UseEnum(TraitType):
- """Use a Enum class as model for the data type description.
- Note that if no default-value is provided, the first enum-value is used
- as default-value.
-
- .. sourcecode:: python
-
- # -- SINCE: Python 3.4 (or install backport: pip install enum34)
- import enum
- from traitlets import HasTraits, UseEnum
-
- class Color(enum.Enum):
- red = 1 # -- IMPLICIT: default_value
- blue = 2
- green = 3
-
- class MyEntity(HasTraits):
- color = UseEnum(Color, default_value=Color.blue)
-
- entity = MyEntity(color=Color.red)
- entity.color = Color.green # USE: Enum-value (preferred)
- entity.color = "green" # USE: name (as string)
- entity.color = "Color.green" # USE: scoped-name (as string)
- entity.color = 3 # USE: number (as int)
- assert entity.color is Color.green
- """
- default_value = None
- info_text = "Trait type adapter to a Enum class"
-
- def __init__(self, enum_class, default_value=None, **kwargs):
- assert issubclass(enum_class, enum.Enum), \
- "REQUIRE: enum.Enum, but was: %r" % enum_class
- allow_none = kwargs.get("allow_none", False)
- if default_value is None and not allow_none:
- default_value = list(enum_class.__members__.values())[0]
- super(UseEnum, self).__init__(default_value=default_value, **kwargs)
- self.enum_class = enum_class
- self.name_prefix = enum_class.__name__ + "."
-
- def select_by_number(self, value, default=Undefined):
- """Selects enum-value by using its number-constant."""
- assert isinstance(value, int)
- enum_members = self.enum_class.__members__
- for enum_item in enum_members.values():
- if enum_item.value == value:
- return enum_item
- # -- NOT FOUND:
- return default
-
- def select_by_name(self, value, default=Undefined):
- """Selects enum-value by using its name or scoped-name."""
- assert isinstance(value, six.string_types)
- if value.startswith(self.name_prefix):
- # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
- value = value.replace(self.name_prefix, "", 1)
- return self.enum_class.__members__.get(value, default)
-
- def validate(self, obj, value):
- if isinstance(value, self.enum_class):
- return value
- elif isinstance(value, int):
- # -- CONVERT: number => enum_value (item)
- value2 = self.select_by_number(value)
- if value2 is not Undefined:
- return value2
- elif isinstance(value, six.string_types):
- # -- CONVERT: name or scoped_name (as string) => enum_value (item)
- value2 = self.select_by_name(value)
- if value2 is not Undefined:
- return value2
- elif value is None:
- if self.allow_none:
- return None
- else:
- return self.default_value
- self.error(obj, value)
-
- def info(self):
- """Returns a description of this Enum trait (in case of errors)."""
- result = "Any of: %s" % ", ".join(self.enum_class.__members__.keys())
- if self.allow_none:
- return result + " or None"
- return result
+
+
+class UseEnum(TraitType):
+ """Use a Enum class as model for the data type description.
+ Note that if no default-value is provided, the first enum-value is used
+ as default-value.
+
+ .. sourcecode:: python
+
+ # -- SINCE: Python 3.4 (or install backport: pip install enum34)
+ import enum
+ from traitlets import HasTraits, UseEnum
+
+ class Color(enum.Enum):
+ red = 1 # -- IMPLICIT: default_value
+ blue = 2
+ green = 3
+
+ class MyEntity(HasTraits):
+ color = UseEnum(Color, default_value=Color.blue)
+
+ entity = MyEntity(color=Color.red)
+ entity.color = Color.green # USE: Enum-value (preferred)
+ entity.color = "green" # USE: name (as string)
+ entity.color = "Color.green" # USE: scoped-name (as string)
+ entity.color = 3 # USE: number (as int)
+ assert entity.color is Color.green
+ """
+ default_value = None
+ info_text = "Trait type adapter to a Enum class"
+
+ def __init__(self, enum_class, default_value=None, **kwargs):
+ assert issubclass(enum_class, enum.Enum), \
+ "REQUIRE: enum.Enum, but was: %r" % enum_class
+ allow_none = kwargs.get("allow_none", False)
+ if default_value is None and not allow_none:
+ default_value = list(enum_class.__members__.values())[0]
+ super(UseEnum, self).__init__(default_value=default_value, **kwargs)
+ self.enum_class = enum_class
+ self.name_prefix = enum_class.__name__ + "."
+
+ def select_by_number(self, value, default=Undefined):
+ """Selects enum-value by using its number-constant."""
+ assert isinstance(value, int)
+ enum_members = self.enum_class.__members__
+ for enum_item in enum_members.values():
+ if enum_item.value == value:
+ return enum_item
+ # -- NOT FOUND:
+ return default
+
+ def select_by_name(self, value, default=Undefined):
+ """Selects enum-value by using its name or scoped-name."""
+ assert isinstance(value, six.string_types)
+ if value.startswith(self.name_prefix):
+ # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
+ value = value.replace(self.name_prefix, "", 1)
+ return self.enum_class.__members__.get(value, default)
+
+ def validate(self, obj, value):
+ if isinstance(value, self.enum_class):
+ return value
+ elif isinstance(value, int):
+ # -- CONVERT: number => enum_value (item)
+ value2 = self.select_by_number(value)
+ if value2 is not Undefined:
+ return value2
+ elif isinstance(value, six.string_types):
+ # -- CONVERT: name or scoped_name (as string) => enum_value (item)
+ value2 = self.select_by_name(value)
+ if value2 is not Undefined:
+ return value2
+ elif value is None:
+ if self.allow_none:
+ return None
+ else:
+ return self.default_value
+ self.error(obj, value)
+
+ def info(self):
+ """Returns a description of this Enum trait (in case of errors)."""
+ result = "Any of: %s" % ", ".join(self.enum_class.__members__.keys())
+ if self.allow_none:
+ return result + " or None"
+ return result
diff --git a/contrib/python/traitlets/py2/traitlets/utils/bunch.py b/contrib/python/traitlets/py2/traitlets/utils/bunch.py
index dc40b5df7d..2edb830ad6 100644
--- a/contrib/python/traitlets/py2/traitlets/utils/bunch.py
+++ b/contrib/python/traitlets/py2/traitlets/utils/bunch.py
@@ -1,25 +1,25 @@
-"""Yet another implementation of bunch
-
-attribute-access of items on a dict.
-"""
-
-# Copyright (c) Jupyter Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-class Bunch(dict):
- """A dict with attribute-access"""
- def __getattr__(self, key):
- try:
- return self.__getitem__(key)
- except KeyError:
- raise AttributeError(key)
-
- def __setattr__(self, key, value):
- self.__setitem__(key, value)
-
- def __dir__(self):
- # py2-compat: can't use super because dict doesn't have __dir__
- names = dir({})
- names.extend(self.keys())
- return names
-
+"""Yet another implementation of bunch
+
+attribute-access of items on a dict.
+"""
+
+# Copyright (c) Jupyter Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+class Bunch(dict):
+ """A dict with attribute-access"""
+ def __getattr__(self, key):
+ try:
+ return self.__getitem__(key)
+ except KeyError:
+ raise AttributeError(key)
+
+ def __setattr__(self, key, value):
+ self.__setitem__(key, value)
+
+ def __dir__(self):
+ # py2-compat: can't use super because dict doesn't have __dir__
+ names = dir({})
+ names.extend(self.keys())
+ return names
+
diff --git a/contrib/python/traitlets/py2/traitlets/utils/getargspec.py b/contrib/python/traitlets/py2/traitlets/utils/getargspec.py
index f23750cbc1..0a047379fe 100644
--- a/contrib/python/traitlets/py2/traitlets/utils/getargspec.py
+++ b/contrib/python/traitlets/py2/traitlets/utils/getargspec.py
@@ -10,7 +10,7 @@
"""
import inspect
-from six import PY3
+from six import PY3
# Unmodified from sphinx below this line
diff --git a/contrib/python/traitlets/py2/traitlets/utils/importstring.py b/contrib/python/traitlets/py2/traitlets/utils/importstring.py
index 0228367446..5b4f643f41 100644
--- a/contrib/python/traitlets/py2/traitlets/utils/importstring.py
+++ b/contrib/python/traitlets/py2/traitlets/utils/importstring.py
@@ -5,8 +5,8 @@ A simple utility to import something by its string name.
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
-from ipython_genutils.py3compat import cast_bytes_py2
-from six import string_types
+from ipython_genutils.py3compat import cast_bytes_py2
+from six import string_types
def import_item(name):
"""Import and return ``bar`` given the string ``foo.bar``.
diff --git a/contrib/python/traitlets/py2/ya.make b/contrib/python/traitlets/py2/ya.make
index 1efff6da42..4a60107101 100644
--- a/contrib/python/traitlets/py2/ya.make
+++ b/contrib/python/traitlets/py2/ya.make
@@ -14,7 +14,7 @@ PEERDIR(
contrib/python/decorator
contrib/python/enum34
contrib/python/ipython-genutils
- contrib/python/six
+ contrib/python/six
)
NO_LINT()
@@ -31,7 +31,7 @@ PY_SRCS(
traitlets/log.py
traitlets/traitlets.py
traitlets/utils/__init__.py
- traitlets/utils/bunch.py
+ traitlets/utils/bunch.py
traitlets/utils/getargspec.py
traitlets/utils/importstring.py
traitlets/utils/sentinel.py
diff --git a/contrib/python/traitlets/py3/traitlets/config/application.py b/contrib/python/traitlets/py3/traitlets/config/application.py
index b81fd45b85..99a6ef7ee0 100644
--- a/contrib/python/traitlets/py3/traitlets/config/application.py
+++ b/contrib/python/traitlets/py3/traitlets/config/application.py
@@ -5,7 +5,7 @@
from collections import defaultdict, OrderedDict
-from copy import deepcopy
+from copy import deepcopy
import functools
import json
import logging
@@ -20,7 +20,7 @@ from traitlets.config.loader import (
KVArgParseConfigLoader, PyFileConfigLoader, Config, ArgumentError, ConfigFileNotFound, JSONFileConfigLoader
)
from traitlets.traitlets import (
- Bool, Unicode, List, Enum, Dict, Instance, TraitError, observe, observe_compat, default,
+ Bool, Unicode, List, Enum, Dict, Instance, TraitError, observe, observe_compat, default,
)
from ..utils.importstring import import_item
@@ -28,7 +28,7 @@ from ..utils import cast_unicode
from traitlets.utils.text import indent, wrap_paragraphs
from textwrap import dedent
-
+
#-----------------------------------------------------------------------------
# Descriptions for the various sections
#-----------------------------------------------------------------------------
@@ -63,23 +63,23 @@ subcommand 'cmd', do: `{app} cmd -h`.
# Application class
#-----------------------------------------------------------------------------
-
-
-_envvar = os.environ.get('TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR','')
-if _envvar.lower() in {'1','true'}:
- TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = True
-elif _envvar.lower() in {'0','false',''} :
- TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = False
-else:
- raise ValueError("Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
-
-
+
+
+_envvar = os.environ.get('TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR','')
+if _envvar.lower() in {'1','true'}:
+ TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = True
+elif _envvar.lower() in {'0','false',''} :
+ TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR = False
+else:
+ raise ValueError("Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
+
+
def catch_config_error(method):
"""Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
On a TraitError (generally caused by bad config), this will print the trait's
message, and exit the app.
-
+
For use on init methods, to prevent invoking excepthook on invalid input.
"""
@functools.wraps(method)
@@ -99,16 +99,16 @@ class ApplicationError(Exception):
class LevelFormatter(logging.Formatter):
"""Formatter with additional `highlevel` record
-
+
This field is empty if log level is less than highlevel_limit,
otherwise it is formatted with self.highlevel_format.
-
+
Useful for adding 'WARNING' to warning messages,
without adding 'INFO' to info, etc.
"""
highlevel_limit = logging.WARN
highlevel_format = " %(levelname)s |"
-
+
def format(self, record):
if record.levelno >= self.highlevel_limit:
record.highlevel = self.highlevel_format % record.__dict__
@@ -116,7 +116,7 @@ class LevelFormatter(logging.Formatter):
record.highlevel = ""
return super(LevelFormatter, self).format(record)
-
+
class Application(SingletonConfigurable):
"""A singleton application with full configuration support."""
@@ -131,7 +131,7 @@ class Application(SingletonConfigurable):
option_description = Unicode(option_description)
keyvalue_description = Unicode(keyvalue_description)
subcommand_description = Unicode(subcommand_description)
-
+
python_config_loader_class = PyFileConfigLoader
json_config_loader_class = JSONFileConfigLoader
@@ -164,13 +164,13 @@ class Application(SingletonConfigurable):
# The version string of this application.
version = Unicode('0.0')
-
+
# the argv used to initialize the application
argv = List()
- # Whether failing to load config files should prevent startup
- raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)
-
+ # Whether failing to load config files should prevent startup
+ raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)
+
# The log level for the application
log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
default_value=logging.WARN,
@@ -180,15 +180,15 @@ class Application(SingletonConfigurable):
@observe_compat
def _log_level_changed(self, change):
"""Adjust the log level when log_level is set."""
- new = change.new
+ new = change.new
if isinstance(new, str):
new = getattr(logging, new)
self.log_level = new
self.log.setLevel(new)
-
+
_log_formatter_cls = LevelFormatter
-
- log_datefmt = Unicode("%Y-%m-%d %H:%M:%S",
+
+ log_datefmt = Unicode("%Y-%m-%d %H:%M:%S",
help="The date format used by logging formatters for %(asctime)s"
).tag(config=True)
@@ -209,7 +209,7 @@ class Application(SingletonConfigurable):
return
_log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
_log_handler.setFormatter(_log_formatter)
-
+
@default('log')
def _log_default(self):
"""Start logging for this application.
@@ -229,7 +229,7 @@ class Application(SingletonConfigurable):
break
else:
_log = _log.parent
- if sys.executable and sys.executable.endswith('pythonw.exe'):
+ if sys.executable and sys.executable.endswith('pythonw.exe'):
# this should really go to a file, but file-logging is only
# hooked up in parallel applications
_log_handler = logging.StreamHandler(open(os.devnull, 'w'))
@@ -279,16 +279,16 @@ class Application(SingletonConfigurable):
# extra command-line arguments that don't set config values
extra_args = List(Unicode())
- cli_config = Instance(Config, (), {},
- help="""The subset of our configuration that came from the command-line
+ cli_config = Instance(Config, (), {},
+ help="""The subset of our configuration that came from the command-line
+
+ We re-load this configuration after loading config files,
+ to ensure that it maintains highest priority.
+ """
+ )
- We re-load this configuration after loading config files,
- to ensure that it maintains highest priority.
- """
- )
-
_loaded_config_files = List()
-
+
show_config = Bool(
help="Instead of starting the Application, dump configuration to stdout"
).tag(config=True)
@@ -311,14 +311,14 @@ class Application(SingletonConfigurable):
SingletonConfigurable.__init__(self, **kwargs)
# Ensure my class is in self.classes, so my attributes appear in command line
# options and config files.
- cls = self.__class__
- if cls not in self.classes:
- if self.classes is cls.classes:
- # class attr, assign instead of insert
+ cls = self.__class__
+ if cls not in self.classes:
+ if self.classes is cls.classes:
+ # class attr, assign instead of insert
self.classes = [cls] + self.classes
- else:
- self.classes.insert(0, self.__class__)
-
+ else:
+ self.classes.insert(0, self.__class__)
+
@observe('config')
@observe_compat
def _config_changed(self, change):
@@ -394,7 +394,7 @@ class Application(SingletonConfigurable):
for c in cls.mro()[:-3]:
classdict[c.__name__] = c
- for alias, longname in self.aliases.items():
+ for alias, longname in self.aliases.items():
try:
if isinstance(longname, tuple):
longname, fhelp = longname
@@ -489,7 +489,7 @@ class Application(SingletonConfigurable):
app=self.name)):
yield p
yield ''
- for subc, (cls, help) in self.subcommands.items():
+ for subc, (cls, help) in self.subcommands.items():
yield subc
if help:
yield indent(dedent(help.strip()))
@@ -602,10 +602,10 @@ class Application(SingletonConfigurable):
# ... and finally initialize subapp.
self.subapp.initialize(argv)
-
+
def flatten_flags(self):
"""Flatten flags and aliases for loaders, so cl-args override as expected.
-
+
This prevents issues such as an alias pointing to InteractiveShell,
but a config file setting the same trait in TerminalInteraciveShell
getting inappropriate priority over the command-line arg.
@@ -613,7 +613,7 @@ class Application(SingletonConfigurable):
Only aliases with exactly one descendent in the class list
will be promoted.
-
+
"""
# build a tree of classes in our list that inherit from a particular
# it will be a dict by parent classname of classes in our list
@@ -639,13 +639,13 @@ class Application(SingletonConfigurable):
alias = (alias, )
for al in alias:
aliases[al] = '.'.join([cls,trait])
-
+
# flatten flags, which are of the form:
# { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
flags = {}
- for key, (flagdict, help) in self.flags.items():
+ for key, (flagdict, help) in self.flags.items():
newflag = {}
- for cls, subdict in flagdict.items():
+ for cls, subdict in flagdict.items():
children = mro_tree[cls]
# exactly one descendent, promote flag section
if len(children) == 1:
@@ -672,7 +672,7 @@ class Application(SingletonConfigurable):
assert not isinstance(argv, str)
argv = sys.argv[1:] if argv is None else argv
self.argv = [cast_unicode(arg) for arg in argv ]
-
+
if argv and argv[0] == 'help':
# turn `ipython help notebook` into `ipython notebook -h`
argv = argv[1:] + ['-h']
@@ -700,7 +700,7 @@ class Application(SingletonConfigurable):
if '--version' in interpreted_argv or '-V' in interpreted_argv:
self.print_version()
self.exit(0)
-
+
# flatten flags&aliases, so cl-args get appropriate priority:
flags, aliases = self.flatten_flags()
classes = tuple(self._classes_with_config_traits())
@@ -711,27 +711,27 @@ class Application(SingletonConfigurable):
# traitlets 5: no longer print help output on error
# help output is huge, and comes after the error
raise
- self.update_config(self.cli_config)
+ self.update_config(self.cli_config)
# store unparsed args in extra_args
self.extra_args = loader.extra_args
@classmethod
- def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
+ def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
"""Load config files (py,json) by filename and path.
yield each config object in turn.
"""
-
+
if not isinstance(path, list):
path = [path]
for path in path[::-1]:
# path list is in descending priority order, so load files backwards:
pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
if log:
- log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
+ log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
- loaded = []
- filenames = []
+ loaded = []
+ filenames = []
for loader in [pyloader, jsonloader]:
config = None
try:
@@ -743,8 +743,8 @@ class Application(SingletonConfigurable):
# unlikely event that the error raised before filefind finished
filename = loader.full_filename or basefilename
# problem while running the file
- if raise_config_file_errors:
- raise
+ if raise_config_file_errors:
+ raise
if log:
log.error("Exception while loading config file %s",
filename, exc_info=True)
@@ -752,16 +752,16 @@ class Application(SingletonConfigurable):
if log:
log.debug("Loaded config file: %s", loader.full_filename)
if config:
- for filename, earlier_config in zip(filenames, loaded):
- collisions = earlier_config.collisions(config)
- if collisions and log:
- log.warning("Collisions detected in {0} and {1} config files."
- " {1} has higher priority: {2}".format(
- filename, loader.full_filename, json.dumps(collisions, indent=2),
- ))
+ for filename, earlier_config in zip(filenames, loaded):
+ collisions = earlier_config.collisions(config)
+ if collisions and log:
+ log.warning("Collisions detected in {0} and {1} config files."
+ " {1} has higher priority: {2}".format(
+ filename, loader.full_filename, json.dumps(collisions, indent=2),
+ ))
yield (config, loader.full_filename)
- loaded.append(config)
- filenames.append(loader.full_filename)
+ loaded.append(config)
+ filenames.append(loader.full_filename)
@property
def loaded_config_files(self):
@@ -772,55 +772,55 @@ class Application(SingletonConfigurable):
def load_config_file(self, filename, path=None):
"""Load config files by filename and path."""
filename, ext = os.path.splitext(filename)
- new_config = Config()
+ new_config = Config()
for (config, filename) in self._load_config_files(filename, path=path, log=self.log,
- raise_config_file_errors=self.raise_config_file_errors,
- ):
- new_config.merge(config)
+ raise_config_file_errors=self.raise_config_file_errors,
+ ):
+ new_config.merge(config)
if filename not in self._loaded_config_files: # only add to list of loaded files if not previously loaded
self._loaded_config_files.append(filename)
- # add self.cli_config to preserve CLI config priority
- new_config.merge(self.cli_config)
- self.update_config(new_config)
+ # add self.cli_config to preserve CLI config priority
+ new_config.merge(self.cli_config)
+ self.update_config(new_config)
def _classes_with_config_traits(self, classes=None):
- """
+ """
Yields only classes with configurable traits, and their subclasses.
-
+
:param classes:
The list of classes to iterate; if not set, uses :attr:`classes`.
- Thus, produced sample config-file will contain all classes
- on which a trait-value may be overridden:
-
- - either on the class owning the trait,
- - or on its subclasses, even if those subclasses do not define
- any traits themselves.
- """
+ Thus, produced sample config-file will contain all classes
+ on which a trait-value may be overridden:
+
+ - either on the class owning the trait,
+ - or on its subclasses, even if those subclasses do not define
+ any traits themselves.
+ """
if classes is None:
classes = self.classes
- cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True)))
- for cls
+ cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True)))
+ for cls
in self._classes_inc_parents(classes))
-
- def is_any_parent_included(cls):
- return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__)
-
- ## Mark "empty" classes for inclusion if their parents own-traits,
- # and loop until no more classes gets marked.
- #
- while True:
- to_incl_orig = cls_to_config.copy()
- cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls))
- for cls, inc_yes
- in cls_to_config.items())
- if cls_to_config == to_incl_orig:
- break
- for cl, inc_yes in cls_to_config.items():
- if inc_yes:
- yield cl
-
+
+ def is_any_parent_included(cls):
+ return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__)
+
+ ## Mark "empty" classes for inclusion if their parents own-traits,
+ # and loop until no more classes gets marked.
+ #
+ while True:
+ to_incl_orig = cls_to_config.copy()
+ cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls))
+ for cls, inc_yes
+ in cls_to_config.items())
+ if cls_to_config == to_incl_orig:
+ break
+ for cl, inc_yes in cls_to_config.items():
+ if inc_yes:
+ yield cl
+
def generate_config_file(self, classes=None):
"""generate default config file from Configurables"""
lines = ["# Configuration file for %s." % self.name]
@@ -838,7 +838,7 @@ class Application(SingletonConfigurable):
@classmethod
def launch_instance(cls, argv=None, **kwargs):
"""Launch a global instance of this Application
-
+
If a global instance already exists, this reinitializes and starts it
"""
app = cls.instance(**kwargs)
@@ -885,7 +885,7 @@ def boolean_flag(name, configurable, set_help='', unset_help=''):
def get_config():
"""Get the config object for the global Application instance, if there is one
-
+
otherwise return an empty config object
"""
if Application.initialized():
diff --git a/contrib/python/traitlets/py3/traitlets/config/configurable.py b/contrib/python/traitlets/py3/traitlets/config/configurable.py
index 0f80aa3a0b..3b2044a01b 100644
--- a/contrib/python/traitlets/py3/traitlets/config/configurable.py
+++ b/contrib/python/traitlets/py3/traitlets/config/configurable.py
@@ -6,7 +6,7 @@
from copy import deepcopy
import logging
-import warnings
+import warnings
from .loader import Config, LazyConfigValue, DeferredConfig, _is_section_key
from traitlets.traitlets import (
@@ -78,12 +78,12 @@ class Configurable(HasTraits):
if kwargs.get('config', None) is None:
kwargs['config'] = parent.config
self.parent = parent
-
+
config = kwargs.pop('config', None)
-
+
# load kwarg traits, other than config
super(Configurable, self).__init__(**kwargs)
-
+
# record traits set by config
config_override_names = set()
def notice_config_override(change):
@@ -109,7 +109,7 @@ class Configurable(HasTraits):
# allow _config_default to return something
self._load_config(self.config)
self.unobserve(notice_config_override)
-
+
for name in config_override_names:
setattr(self, name, kwargs[name])
@@ -117,25 +117,25 @@ class Configurable(HasTraits):
#-------------------------------------------------------------------------
# Static trait notifiations
#-------------------------------------------------------------------------
-
+
@classmethod
def section_names(cls):
"""return section names as a list"""
return [c.__name__ for c in reversed(cls.__mro__) if
issubclass(c, Configurable) and issubclass(cls, c)
]
-
+
def _find_my_config(self, cfg):
"""extract my config from a global Config object
-
+
will construct a Config object of only the config values that apply to me
based on my mro(), as well as those of my parent(s) if they exist.
-
+
If I am Bar and my parent is Foo, and their parent is Tim,
this will return merge following config sections, in this order::
-
+
[Bar, Foo.Bar, Tim.Foo.Bar]
-
+
With the last item being the highest priority.
"""
cfgs = [cfg]
@@ -149,20 +149,20 @@ class Configurable(HasTraits):
if c._has_section(sname):
my_config.merge(c[sname])
return my_config
-
+
def _load_config(self, cfg, section_names=None, traits=None):
"""load traits from a Config object"""
-
+
if traits is None:
traits = self.traits(config=True)
if section_names is None:
section_names = self.section_names()
-
+
my_config = self._find_my_config(cfg)
-
+
# hold trait notifications until after all config has been loaded
with self.hold_trait_notifications():
- for name, config_value in my_config.items():
+ for name, config_value in my_config.items():
if name in traits:
if isinstance(config_value, LazyConfigValue):
# ConfigValue is a wrapper for using append / update on containers
@@ -176,21 +176,21 @@ class Configurable(HasTraits):
# config object. If we don't, a mutable config_value will be
# shared by all instances, effectively making it a class attribute.
setattr(self, name, deepcopy(config_value))
- elif not _is_section_key(name) and not isinstance(config_value, Config):
+ elif not _is_section_key(name) and not isinstance(config_value, Config):
from difflib import get_close_matches
- if isinstance(self, LoggingConfigurable):
- warn = self.log.warning
- else:
- warn = lambda msg: warnings.warn(msg, stacklevel=9)
+ if isinstance(self, LoggingConfigurable):
+ warn = self.log.warning
+ else:
+ warn = lambda msg: warnings.warn(msg, stacklevel=9)
matches = get_close_matches(name, traits)
msg = "Config option `{option}` not recognized by `{klass}`.".format(
- option=name, klass=self.__class__.__name__)
-
+ option=name, klass=self.__class__.__name__)
+
if len(matches) == 1:
msg += " Did you mean `{matches}`?".format(matches=matches[0])
elif len(matches) >= 1:
- msg +=" Did you mean one of: `{matches}`?".format(matches=', '.join(sorted(matches)))
- warn(msg)
+ msg +=" Did you mean one of: `{matches}`?".format(matches=', '.join(sorted(matches)))
+ warn(msg)
@observe('config')
@observe_compat
@@ -208,23 +208,23 @@ class Configurable(HasTraits):
# classes that are Configurable subclasses. This starts with Configurable
# and works down the mro loading the config for each section.
section_names = self.section_names()
- self._load_config(change.new, traits=traits, section_names=section_names)
+ self._load_config(change.new, traits=traits, section_names=section_names)
def update_config(self, config):
- """Update config and load the new values"""
- # traitlets prior to 4.2 created a copy of self.config in order to trigger change events.
- # Some projects (IPython < 5) relied upon one side effect of this,
- # that self.config prior to update_config was not modified in-place.
- # For backward-compatibility, we must ensure that self.config
- # is a new object and not modified in-place,
- # but config consumers should not rely on this behavior.
- self.config = deepcopy(self.config)
- # load config
- self._load_config(config)
- # merge it into self.config
+ """Update config and load the new values"""
+ # traitlets prior to 4.2 created a copy of self.config in order to trigger change events.
+ # Some projects (IPython < 5) relied upon one side effect of this,
+ # that self.config prior to update_config was not modified in-place.
+ # For backward-compatibility, we must ensure that self.config
+ # is a new object and not modified in-place,
+ # but config consumers should not rely on this behavior.
+ self.config = deepcopy(self.config)
+ # load config
+ self._load_config(config)
+ # merge it into self.config
self.config.merge(config)
- # TODO: trigger change event if/when dict-update change events take place
- # DO NOT trigger full trait-change
+ # TODO: trigger change event if/when dict-update change events take place
+ # DO NOT trigger full trait-change
@classmethod
def class_get_help(cls, inst=None):
@@ -246,7 +246,7 @@ class Configurable(HasTraits):
@classmethod
def class_get_trait_help(cls, trait, inst=None, helptext=None):
"""Get the helptext string for a single trait.
-
+
:param inst:
If given, it's current trait values will be used in place of
the class default.
@@ -340,7 +340,7 @@ class Configurable(HasTraits):
"""return a commented, wrapped block."""
s = '\n\n'.join(wrap_paragraphs(s, 78))
- return '## ' + s.replace('\n', '\n# ')
+ return '## ' + s.replace('\n', '\n# ')
# section header
breaker = '#' + '-' * 78
@@ -349,14 +349,14 @@ class Configurable(HasTraits):
if issubclass(p, Configurable)
)
- s = "# %s(%s) configuration" % (cls.__name__, parent_classes)
+ s = "# %s(%s) configuration" % (cls.__name__, parent_classes)
lines = [breaker, s, breaker]
# get the description trait
desc = cls.class_traits().get('description')
if desc:
desc = desc.default_value
- if not desc:
- # no description from trait, use __doc__
+ if not desc:
+ # no description from trait, use __doc__
desc = getattr(cls, '__doc__', '')
if desc:
lines.append(c(desc))
diff --git a/contrib/python/traitlets/py3/traitlets/config/loader.py b/contrib/python/traitlets/py3/traitlets/config/loader.py
index bbab151db8..5360f889ab 100644
--- a/contrib/python/traitlets/py3/traitlets/config/loader.py
+++ b/contrib/python/traitlets/py3/traitlets/config/loader.py
@@ -255,7 +255,7 @@ class Config(dict):
def merge(self, other):
"""merge another config object into this one"""
to_update = {}
- for k, v in other.items():
+ for k, v in other.items():
if k not in self:
to_update[k] = v
else: # I have this key
@@ -542,17 +542,17 @@ class FileConfigLoader(ConfigLoader):
self.full_filename = filefind(self.filename, self.path)
class JSONFileConfigLoader(FileConfigLoader):
- """A JSON file loader for config
-
- Can also act as a context manager that rewrite the configuration file to disk on exit.
-
- Example::
-
- with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c:
- c.MyNewConfigurable.new_value = 'Updated'
-
- """
-
+ """A JSON file loader for config
+
+ Can also act as a context manager that rewrite the configuration file to disk on exit.
+
+ Example::
+
+ with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c:
+ c.MyNewConfigurable.new_value = 'Updated'
+
+ """
+
def load_config(self):
"""Load the config from a file and return it as a Config object."""
self.clear()
@@ -579,24 +579,24 @@ class JSONFileConfigLoader(FileConfigLoader):
else:
raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
- def __enter__(self):
- self.load_config()
- return self.config
-
- def __exit__(self, exc_type, exc_value, traceback):
- """
- Exit the context manager but do not handle any errors.
-
- In case of any error, we do not want to write the potentially broken
- configuration to disk.
- """
- self.config.version = 1
- json_config = json.dumps(self.config, indent=2)
- with open(self.full_filename, 'w') as f:
- f.write(json_config)
-
-
-
+ def __enter__(self):
+ self.load_config()
+ return self.config
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ """
+ Exit the context manager but do not handle any errors.
+
+ In case of any error, we do not want to write the potentially broken
+ configuration to disk.
+ """
+ self.config.version = 1
+ json_config = json.dumps(self.config, indent=2)
+ with open(self.full_filename, 'w') as f:
+ f.write(json_config)
+
+
+
class PyFileConfigLoader(FileConfigLoader):
"""A config loader for pure python files.
@@ -910,7 +910,7 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
def _convert_to_config(self):
"""self.parsed_data->self.config"""
- for k, v in vars(self.parsed_data).items():
+ for k, v in vars(self.parsed_data).items():
*path, key = k.split(".")
section = self.config
for p in path:
diff --git a/contrib/python/traitlets/py3/traitlets/log.py b/contrib/python/traitlets/py3/traitlets/log.py
index c7166c14c8..af86b325f5 100644
--- a/contrib/python/traitlets/py3/traitlets/log.py
+++ b/contrib/python/traitlets/py3/traitlets/log.py
@@ -9,19 +9,19 @@ _logger = None
def get_logger():
"""Grab the global logger instance.
-
+
If a global Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
-
+
if _logger is None:
from .config import Application
if Application.initialized():
_logger = Application.instance().log
else:
- _logger = logging.getLogger('traitlets')
- # Add a NullHandler to silence warnings about not being
- # initialized, per best practice for libraries.
- _logger.addHandler(logging.NullHandler())
+ _logger = logging.getLogger('traitlets')
+ # Add a NullHandler to silence warnings about not being
+ # initialized, per best practice for libraries.
+ _logger.addHandler(logging.NullHandler())
return _logger
diff --git a/contrib/python/traitlets/py3/traitlets/traitlets.py b/contrib/python/traitlets/py3/traitlets/traitlets.py
index 7643cbd132..6bdf7414d3 100644
--- a/contrib/python/traitlets/py3/traitlets/traitlets.py
+++ b/contrib/python/traitlets/py3/traitlets/traitlets.py
@@ -42,17 +42,17 @@ Inheritance diagram:
from ast import literal_eval
import contextlib
import inspect
-import os
+import os
import re
import sys
import types
-import enum
+import enum
from warnings import warn, warn_explicit
from .utils.getargspec import getargspec
from .utils.importstring import import_item
from .utils.sentinel import Sentinel
-from .utils.bunch import Bunch
+from .utils.bunch import Bunch
from .utils.descriptions import describe, class_of, add_article, repr_type
SequenceTypes = (list, tuple, set, frozenset)
@@ -113,34 +113,34 @@ class TraitError(Exception):
# Utilities
#-----------------------------------------------------------------------------
-_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
-
-def isidentifier(s):
+_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
+
+def isidentifier(s):
return s.isidentifier()
-
-_deprecations_shown = set()
-def _should_warn(key):
- """Add our own checks for too many deprecation warnings.
-
- Limit to once per package.
- """
- env_flag = os.environ.get('TRAITLETS_ALL_DEPRECATIONS')
- if env_flag and env_flag != '0':
- return True
-
- if key not in _deprecations_shown:
- _deprecations_shown.add(key)
- return True
- else:
- return False
-
+
+_deprecations_shown = set()
+def _should_warn(key):
+ """Add our own checks for too many deprecation warnings.
+
+ Limit to once per package.
+ """
+ env_flag = os.environ.get('TRAITLETS_ALL_DEPRECATIONS')
+ if env_flag and env_flag != '0':
+ return True
+
+ if key not in _deprecations_shown:
+ _deprecations_shown.add(key)
+ return True
+ else:
+ return False
+
def _deprecated_method(method, cls, method_name, msg):
"""Show deprecation warning about a magic method definition.
Uses warn_explicit to bind warning to method definition instead of triggering code,
which isn't relevant.
"""
- warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
+ warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
classname=cls.__name__, method_name=method_name, msg=msg
)
@@ -148,11 +148,11 @@ def _deprecated_method(method, cls, method_name, msg):
if method_name in parent.__dict__:
cls = parent
break
- # limit deprecation messages to once per package
- package_name = cls.__module__.split('.', 1)[0]
- key = (package_name, msg)
- if not _should_warn(key):
- return
+ # limit deprecation messages to once per package
+ package_name = cls.__module__.split('.', 1)[0]
+ key = (package_name, msg)
+ if not _should_warn(key):
+ return
try:
fname = inspect.getsourcefile(method) or "<unknown>"
lineno = inspect.getsourcelines(method)[1] or 0
@@ -197,12 +197,12 @@ def parse_notifier_name(names):
"""
if names is All or isinstance(names, str):
return [names]
- else:
+ else:
if not names or All in names:
return [All]
for n in names:
if not isinstance(n, str):
- raise TypeError("names must be strings, not %r" % n)
+ raise TypeError("names must be strings, not %r" % n)
return names
@@ -358,7 +358,7 @@ class directional_link(object):
return
with self._busy_updating():
setattr(self.target[0], self.target[1],
- self._transform(change.new))
+ self._transform(change.new))
def unlink(self):
self.source[0].unobserve(self._update, names=self.source[1])
@@ -367,7 +367,7 @@ dlink = directional_link
#-----------------------------------------------------------------------------
-# Base Descriptor Class
+# Base Descriptor Class
#-----------------------------------------------------------------------------
@@ -447,32 +447,32 @@ class TraitType(BaseDescriptor):
"""
if default_value is not Undefined:
self.default_value = default_value
- if allow_none:
+ if allow_none:
self.allow_none = allow_none
if read_only is not None:
self.read_only = read_only
self.help = help if help is not None else ''
- if len(kwargs) > 0:
+ if len(kwargs) > 0:
stacklevel = 1
f = inspect.currentframe()
# count supers to determine stacklevel for warning
while f.f_code.co_name == '__init__':
stacklevel += 1
f = f.f_back
- mod = f.f_globals.get('__name__') or ''
- pkg = mod.split('.', 1)[0]
- key = tuple(['metadata-tag', pkg] + sorted(kwargs))
- if _should_warn(key):
- warn("metadata %s was set from the constructor. "
- "With traitlets 4.1, metadata should be set using the .tag() method, "
- "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
- DeprecationWarning, stacklevel=stacklevel)
+ mod = f.f_globals.get('__name__') or ''
+ pkg = mod.split('.', 1)[0]
+ key = tuple(['metadata-tag', pkg] + sorted(kwargs))
+ if _should_warn(key):
+ warn("metadata %s was set from the constructor. "
+ "With traitlets 4.1, metadata should be set using the .tag() method, "
+ "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
+ DeprecationWarning, stacklevel=stacklevel)
if len(self.metadata) > 0:
self.metadata = self.metadata.copy()
- self.metadata.update(kwargs)
+ self.metadata.update(kwargs)
else:
- self.metadata = kwargs
+ self.metadata = kwargs
else:
self.metadata = self.metadata.copy()
if config is not None:
@@ -519,20 +519,20 @@ class TraitType(BaseDescriptor):
"""DEPRECATED: Retrieve the static default value for this trait.
Use self.default_value instead
"""
- warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
+ warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
stacklevel=2)
return self.default_value
def init_default_value(self, obj):
"""DEPRECATED: Set the static default value for the trait type.
"""
- warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
+ warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
stacklevel=2)
value = self._validate(obj, self.default_value)
obj._trait_values[self.name] = value
return value
- def get(self, obj, cls=None):
+ def get(self, obj, cls=None):
try:
value = obj._trait_values[self.name]
except KeyError:
@@ -616,7 +616,7 @@ class TraitType(BaseDescriptor):
def _cross_validate(self, obj, value):
if self.name in obj._trait_validators:
- proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
+ proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
value = obj._trait_validators[self.name](obj, proposal)
elif hasattr(obj, '_%s_validate' % self.name):
meth_name = '_%s_validate' % self.name
@@ -700,7 +700,7 @@ class TraitType(BaseDescriptor):
msg = "use the instance .help string directly, like x.help"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
- warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
+ warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
return self.metadata.get(key, default)
def set_metadata(self, key, value):
@@ -712,7 +712,7 @@ class TraitType(BaseDescriptor):
msg = "use the instance .help string directly, like x.help = value"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
- warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
+ warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
self.metadata[key] = value
def tag(self, **metadata):
@@ -722,11 +722,11 @@ class TraitType(BaseDescriptor):
>>> Int(0).tag(config=True, sync=True)
"""
- maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
- if maybe_constructor_keywords:
- warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
- maybe_constructor_keywords, UserWarning, stacklevel=2)
-
+ maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
+ if maybe_constructor_keywords:
+ warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
+ maybe_constructor_keywords, UserWarning, stacklevel=2)
+
self.metadata.update(metadata)
return self
@@ -764,13 +764,13 @@ class _CallbackWrapper(object):
if self.nargs == 0:
self.cb()
elif self.nargs == 1:
- self.cb(change.name)
+ self.cb(change.name)
elif self.nargs == 2:
- self.cb(change.name, change.new)
+ self.cb(change.name, change.new)
elif self.nargs == 3:
- self.cb(change.name, change.old, change.new)
+ self.cb(change.name, change.old, change.new)
elif self.nargs == 4:
- self.cb(change.name, change.old, change.new, change.owner)
+ self.cb(change.name, change.old, change.new, change.owner)
def _callback_wrapper(cb):
if isinstance(cb, _CallbackWrapper):
@@ -788,13 +788,13 @@ class MetaHasDescriptors(type):
def __new__(mcls, name, bases, classdict):
"""Create the HasDescriptors class."""
- for k, v in classdict.items():
+ for k, v in classdict.items():
# ----------------------------------------------------------------
# Support of deprecated behavior allowing for TraitType types
# to be used instead of TraitType instances.
if inspect.isclass(v) and issubclass(v, TraitType):
- warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
- " Passing types is deprecated in traitlets 4.1.",
+ warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
+ " Passing types is deprecated in traitlets 4.1.",
DeprecationWarning, stacklevel=2)
classdict[k] = v()
# ----------------------------------------------------------------
@@ -813,7 +813,7 @@ class MetaHasDescriptors(type):
BaseDescriptor in the class dict of the newly created ``cls`` before
calling their :attr:`class_init` method.
"""
- for k, v in classdict.items():
+ for k, v in classdict.items():
if isinstance(v, BaseDescriptor):
v.class_init(cls, k)
@@ -833,10 +833,10 @@ class MetaHasTraits(MetaHasDescriptors):
def observe(*names, type="change"):
"""A decorator which can be used to observe Traits on a class.
- The handler passed to the decorator will be called with one ``change``
- dict argument. The change dictionary at least holds a 'type' key and a
- 'name' key, corresponding respectively to the type of notification and the
- name of the attribute that triggered the notification.
+ The handler passed to the decorator will be called with one ``change``
+ dict argument. The change dictionary at least holds a 'type' key and a
+ 'name' key, corresponding respectively to the type of notification and the
+ name of the attribute that triggered the notification.
Other keys may be passed depending on the value of 'type'. In the case
where type is 'change', we also have the following keys:
@@ -850,26 +850,26 @@ def observe(*names, type="change"):
*names
The str names of the Traits to observe on the object.
type : str, kwarg-only
- The type of event to observe (e.g. 'change')
+ The type of event to observe (e.g. 'change')
"""
- if not names:
- raise TypeError("Please specify at least one trait name to observe.")
- for name in names:
+ if not names:
+ raise TypeError("Please specify at least one trait name to observe.")
+ for name in names:
if name is not All and not isinstance(name, str):
- raise TypeError("trait names to observe must be strings or All, not %r" % name)
+ raise TypeError("trait names to observe must be strings or All, not %r" % name)
return ObserveHandler(names, type=type)
def observe_compat(func):
"""Backward-compatibility shim decorator for observers
-
+
Use with:
-
+
@observe('name')
@observe_compat
def _foo_changed(self, change):
...
-
+
With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
Allows adoption of new observer API without breaking subclasses that override and super.
"""
@@ -878,15 +878,15 @@ def observe_compat(func):
change = change_or_name
else:
clsname = self.__class__.__name__
- warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
+ warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
clsname, change_or_name), DeprecationWarning)
- change = Bunch(
- type='change',
- old=old,
- new=new,
- name=change_or_name,
- owner=self,
- )
+ change = Bunch(
+ type='change',
+ old=old,
+ new=new,
+ name=change_or_name,
+ owner=self,
+ )
return func(self, change)
return compatible_observer
@@ -909,18 +909,18 @@ def validate(*names):
Notes
-----
- Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
+ Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
the registered cross validator could potentially make changes to attributes
of the ``HasTraits`` instance. However, we recommend not to do so. The reason
is that the cross-validation of attributes may run in arbitrary order when
- exiting the ``hold_trait_notifications`` context, and such changes may not
+ exiting the ``hold_trait_notifications`` context, and such changes may not
commute.
"""
- if not names:
- raise TypeError("Please specify at least one trait name to validate.")
- for name in names:
+ if not names:
+ raise TypeError("Please specify at least one trait name to validate.")
+ for name in names:
if name is not All and not isinstance(name, str):
- raise TypeError("trait names to validate must be strings or All, not %r" % name)
+ raise TypeError("trait names to validate must be strings or All, not %r" % name)
return ValidateHandler(names)
@@ -961,7 +961,7 @@ def default(name):
# class derived from B.a.this_class.
"""
if not isinstance(name, str):
- raise TypeError("Trait name must be a string or All, not %r" % name)
+ raise TypeError("Trait name must be a string or All, not %r" % name)
return DefaultHandler(name)
@@ -972,7 +972,7 @@ class EventHandler(BaseDescriptor):
return self
def __call__(self, *args, **kwargs):
- """Pass `*args` and `**kwargs` to the handler's function if it exists."""
+ """Pass `*args` and `**kwargs` to the handler's function if it exists."""
if hasattr(self, 'func'):
return self.func(*args, **kwargs)
else:
@@ -1028,19 +1028,19 @@ class HasDescriptors(metaclass=MetaHasDescriptors):
if new_meth is object.__new__:
inst = new_meth(cls)
else:
- inst = new_meth(cls, *args, **kwargs)
- inst.setup_instance(*args, **kwargs)
+ inst = new_meth(cls, *args, **kwargs)
+ inst.setup_instance(*args, **kwargs)
return inst
def setup_instance(*args, **kwargs):
- """
- This is called **before** self.__init__ is called.
- """
+ """
+ This is called **before** self.__init__ is called.
+ """
# Pass self as args[0] to allow "self" as keyword argument
self = args[0]
args = args[1:]
- self._cross_validation_lock = False
+ self._cross_validation_lock = False
cls = self.__class__
for key in dir(cls):
# Some descriptors raise AttributeError like zope.interface's
@@ -1065,40 +1065,40 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
self._trait_values = {}
self._trait_notifiers = {}
self._trait_validators = {}
- super(HasTraits, self).setup_instance(*args, **kwargs)
+ super(HasTraits, self).setup_instance(*args, **kwargs)
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args, **kwargs):
# Allow trait values to be set using keyword arguments.
# We need to use setattr for this to trigger validation and
# notifications.
- super_args = args
- super_kwargs = {}
+ super_args = args
+ super_kwargs = {}
with self.hold_trait_notifications():
- for key, value in kwargs.items():
- if self.has_trait(key):
- setattr(self, key, value)
- else:
- # passthrough args that don't set traits to super
- super_kwargs[key] = value
- try:
- super(HasTraits, self).__init__(*super_args, **super_kwargs)
- except TypeError as e:
- arg_s_list = [ repr(arg) for arg in super_args ]
- for k, v in super_kwargs.items():
- arg_s_list.append("%s=%r" % (k, v))
- arg_s = ', '.join(arg_s_list)
- warn(
+ for key, value in kwargs.items():
+ if self.has_trait(key):
+ setattr(self, key, value)
+ else:
+ # passthrough args that don't set traits to super
+ super_kwargs[key] = value
+ try:
+ super(HasTraits, self).__init__(*super_args, **super_kwargs)
+ except TypeError as e:
+ arg_s_list = [ repr(arg) for arg in super_args ]
+ for k, v in super_kwargs.items():
+ arg_s_list.append("%s=%r" % (k, v))
+ arg_s = ', '.join(arg_s_list)
+ warn(
"Passing unrecognized arguments to super({classname}).__init__({arg_s}).\n"
- "{error}\n"
- "This is deprecated in traitlets 4.2."
- "This error will be raised in a future release of traitlets."
- .format(
- arg_s=arg_s, classname=self.__class__.__name__,
- error=e,
- ),
- DeprecationWarning,
- stacklevel=2,
- )
+ "{error}\n"
+ "This is deprecated in traitlets 4.2."
+ "This error will be raised in a future release of traitlets."
+ .format(
+ arg_s=arg_s, classname=self.__class__.__name__,
+ error=e,
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
def __getstate__(self):
d = self.__dict__.copy()
@@ -1129,27 +1129,27 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
if isinstance(value, EventHandler):
value.instance_init(self)
- @property
+ @property
+ @contextlib.contextmanager
+ def cross_validation_lock(self):
+ """
+ A contextmanager for running a block with our cross validation lock set
+ to True.
+
+ At the end of the block, the lock's value is restored to its value
+ prior to entering the block.
+ """
+ if self._cross_validation_lock:
+ yield
+ return
+ else:
+ try:
+ self._cross_validation_lock = True
+ yield
+ finally:
+ self._cross_validation_lock = False
+
@contextlib.contextmanager
- def cross_validation_lock(self):
- """
- A contextmanager for running a block with our cross validation lock set
- to True.
-
- At the end of the block, the lock's value is restored to its value
- prior to entering the block.
- """
- if self._cross_validation_lock:
- yield
- return
- else:
- try:
- self._cross_validation_lock = True
- yield
- finally:
- self._cross_validation_lock = False
-
- @contextlib.contextmanager
def hold_trait_notifications(self):
"""Context manager for bundling trait change notifications and cross
validation.
@@ -1158,7 +1158,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
race conditions in trait notifiers requesting other trait values.
All trait notifications will fire after all values have been assigned.
"""
- if self._cross_validation_lock:
+ if self._cross_validation_lock:
yield
return
else:
@@ -1170,15 +1170,15 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
if past_changes is None:
return [change]
else:
- if past_changes[-1]['type'] == 'change' and change.type == 'change':
- past_changes[-1]['new'] = change.new
+ if past_changes[-1]['type'] == 'change' and change.type == 'change':
+ past_changes[-1]['new'] = change.new
else:
# In case of changes other than 'change', append the notification.
past_changes.append(change)
return past_changes
def hold(change):
- name = change.name
+ name = change.name
cache[name] = compress(cache.get(name), change)
try:
@@ -1191,24 +1191,24 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
for name in list(cache.keys()):
trait = getattr(self.__class__, name)
value = trait._cross_validate(self, getattr(self, name))
- self.set_trait(name, value)
+ self.set_trait(name, value)
except TraitError as e:
# Roll back in case of TraitError during final cross validation.
self.notify_change = lambda x: None
for name, changes in cache.items():
for change in changes[::-1]:
# TODO: Separate in a rollback function per notification type.
- if change.type == 'change':
- if change.old is not Undefined:
- self.set_trait(name, change.old)
+ if change.type == 'change':
+ if change.old is not Undefined:
+ self.set_trait(name, change.old)
else:
self._trait_values.pop(name)
cache = {}
raise e
finally:
self._cross_validation_lock = False
- # Restore method retrieval from class
- del self.notify_change
+ # Restore method retrieval from class
+ del self.notify_change
# trigger delayed notifications
for changes in cache.values():
@@ -1216,13 +1216,13 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
self.notify_change(change)
def _notify_trait(self, name, old_value, new_value):
- self.notify_change(Bunch(
- name=name,
- old=old_value,
- new=new_value,
- owner=self,
- type='change',
- ))
+ self.notify_change(Bunch(
+ name=name,
+ old=old_value,
+ new=new_value,
+ owner=self,
+ type='change',
+ ))
def notify_change(self, change):
"""Notify observers of a change event"""
@@ -1231,7 +1231,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
def _notify_observers(self, event):
"""Notify observers of any event"""
if not isinstance(event, Bunch):
- # cast to bunch if given a dict
+ # cast to bunch if given a dict
event = Bunch(event)
name, type = event.name, event.type
@@ -1260,9 +1260,9 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
if isinstance(c, _CallbackWrapper):
c = c.__call__
- elif isinstance(c, EventHandler) and c.name is not None:
+ elif isinstance(c, EventHandler) and c.name is not None:
c = getattr(self, c.name)
-
+
c(event)
def _add_notifiers(self, handler, name, type):
@@ -1315,7 +1315,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
If False (the default), then install the handler. If True
then unintall it.
"""
- warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
+ warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
DeprecationWarning, stacklevel=2)
if name is None:
name = All
@@ -1333,8 +1333,8 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
----------
handler : callable
A callable that is called when a trait changes. Its
- signature should be ``handler(change)``, where ``change`` is a
- dictionary. The change dictionary at least holds a 'type' key.
+ signature should be ``handler(change)``, where ``change`` is a
+ dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
@@ -1357,7 +1357,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
def unobserve(self, handler, names=All, type='change'):
"""Remove a trait change handler.
- This is used to unregister handlers to trait change notifications.
+ This is used to unregister handlers to trait change notifications.
Parameters
----------
@@ -1387,19 +1387,19 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
pass
def _register_validator(self, handler, names):
- """Setup a handler to be called when a trait should be cross validated.
+ """Setup a handler to be called when a trait should be cross validated.
This is used to setup dynamic notifications for cross-validation.
If a validator is already registered for any of the provided names, a
- TraitError is raised and no new validator is registered.
+ TraitError is raised and no new validator is registered.
Parameters
----------
handler : callable
A callable that is called when the given trait is cross-validated.
- Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
- with the following attributes/keys:
+ Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
+ with the following attributes/keys:
* ``owner`` : the HasTraits instance
* ``value`` : the proposed value for the modified trait attribute
* ``trait`` : the TraitType instance associated with the attribute
@@ -1416,8 +1416,8 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
for name in names:
self._trait_validators[name] = handler
- def add_traits(self, **traits):
- """Dynamically add trait attributes to the HasTraits instance."""
+ def add_traits(self, **traits):
+ """Dynamically add trait attributes to the HasTraits instance."""
cls = self.__class__
attrs = {"__module__": cls.__module__}
if hasattr(cls, "__qualname__"):
@@ -1425,18 +1425,18 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
attrs["__qualname__"] = cls.__qualname__
attrs.update(traits)
self.__class__ = type(cls.__name__, (cls,), attrs)
- for trait in traits.values():
- trait.instance_init(self)
-
- def set_trait(self, name, value):
- """Forcibly sets trait attribute, including read-only attributes."""
- cls = self.__class__
- if not self.has_trait(name):
- raise TraitError("Class %s does not have a trait named %s" %
- (cls.__name__, name))
- else:
- getattr(cls, name).set(self, value)
-
+ for trait in traits.values():
+ trait.instance_init(self)
+
+ def set_trait(self, name, value):
+ """Forcibly sets trait attribute, including read-only attributes."""
+ cls = self.__class__
+ if not self.has_trait(name):
+ raise TraitError("Class %s does not have a trait named %s" %
+ (cls.__name__, name))
+ else:
+ getattr(cls, name).set(self, value)
+
@classmethod
def class_trait_names(cls, **metadata):
"""Get a list of all the names of this class' traits.
@@ -1444,7 +1444,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
This method is just like the :meth:`trait_names` method,
but is unbound.
"""
- return list(cls.class_traits(**metadata))
+ return list(cls.class_traits(**metadata))
@classmethod
def class_traits(cls, **metadata):
@@ -1494,7 +1494,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
def has_trait(self, name):
"""Returns True if the object has a trait with the specified name."""
return isinstance(getattr(self.__class__, name, None), TraitType)
-
+
def trait_has_value(self, name):
"""Returns True if the specified trait has a value.
@@ -1589,7 +1589,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
def trait_names(self, **metadata):
"""Get a list of all the names of this class' traits."""
- return list(self.traits(**metadata))
+ return list(self.traits(**metadata))
def traits(self, **metadata):
"""Get a ``dict`` of all the traits of this class. The dictionary
@@ -1630,48 +1630,48 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
except AttributeError:
raise TraitError("Class %s does not have a trait named %s" %
(self.__class__.__name__, traitname))
- metadata_name = '_' + traitname + '_metadata'
- if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
- return getattr(self, metadata_name).get(key, default)
+ metadata_name = '_' + traitname + '_metadata'
+ if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
+ return getattr(self, metadata_name).get(key, default)
else:
return trait.metadata.get(key, default)
- @classmethod
- def class_own_trait_events(cls, name):
- """Get a dict of all event handlers defined on this class, not a parent.
-
- Works like ``event_handlers``, except for excluding traits from parents.
- """
- sup = super(cls, cls)
- return {n: e for (n, e) in cls.events(name).items()
- if getattr(sup, n, None) is not e}
-
- @classmethod
- def trait_events(cls, name=None):
- """Get a ``dict`` of all the event handlers of this class.
-
- Parameters
- ----------
+ @classmethod
+ def class_own_trait_events(cls, name):
+ """Get a dict of all event handlers defined on this class, not a parent.
+
+ Works like ``event_handlers``, except for excluding traits from parents.
+ """
+ sup = super(cls, cls)
+ return {n: e for (n, e) in cls.events(name).items()
+ if getattr(sup, n, None) is not e}
+
+ @classmethod
+ def trait_events(cls, name=None):
+ """Get a ``dict`` of all the event handlers of this class.
+
+ Parameters
+ ----------
name : str (default: None)
- The name of a trait of this class. If name is ``None`` then all
- the event handlers of this class will be returned instead.
-
- Returns
- -------
- The event handlers associated with a trait name, or all event handlers.
- """
- events = {}
- for k, v in getmembers(cls):
- if isinstance(v, EventHandler):
- if name is None:
- events[k] = v
- elif name in v.trait_names:
- events[k] = v
- elif hasattr(v, 'tags'):
- if cls.trait_names(**v.tags):
- events[k] = v
- return events
-
+ The name of a trait of this class. If name is ``None`` then all
+ the event handlers of this class will be returned instead.
+
+ Returns
+ -------
+ The event handlers associated with a trait name, or all event handlers.
+ """
+ events = {}
+ for k, v in getmembers(cls):
+ if isinstance(v, EventHandler):
+ if name is None:
+ events[k] = v
+ elif name in v.trait_names:
+ events[k] = v
+ elif hasattr(v, 'tags'):
+ if cls.trait_names(**v.tags):
+ events[k] = v
+ return events
+
#-----------------------------------------------------------------------------
# Actual TraitTypes implementations/subclasses
#-----------------------------------------------------------------------------
@@ -1762,7 +1762,7 @@ class Type(ClassBasedTraitType):
if isinstance(self.klass, str):
klass = self.klass
else:
- klass = self.klass.__module__ + '.' + self.klass.__name__
+ klass = self.klass.__module__ + '.' + self.klass.__name__
result = "a subclass of '%s'" % klass
if self.allow_none:
return result + ' or None'
@@ -1796,7 +1796,7 @@ class Instance(ClassBasedTraitType):
klass = None
- def __init__(self, klass=None, args=None, kw=None, **kwargs):
+ def __init__(self, klass=None, args=None, kw=None, **kwargs):
"""Construct an Instance trait.
This trait allows values that are instances of a particular
@@ -1827,7 +1827,7 @@ class Instance(ClassBasedTraitType):
"""
if klass is None:
klass = self.klass
-
+
if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)):
self.klass = klass
else:
@@ -1842,7 +1842,7 @@ class Instance(ClassBasedTraitType):
self.default_args = args
self.default_kwargs = kw
- super(Instance, self).__init__(**kwargs)
+ super(Instance, self).__init__(**kwargs)
def validate(self, obj, value):
if isinstance(value, self.klass):
@@ -1917,8 +1917,8 @@ class This(ClassBasedTraitType):
info_text = 'an instance of the same type as the receiver or None'
- def __init__(self, **kwargs):
- super(This, self).__init__(None, **kwargs)
+ def __init__(self, **kwargs):
+ super(This, self).__init__(None, **kwargs)
def validate(self, obj, value):
# What if value is a superclass of obj.__class__? This is
@@ -1933,7 +1933,7 @@ class This(ClassBasedTraitType):
class Union(TraitType):
"""A trait type representing a Union type."""
- def __init__(self, trait_types, **kwargs):
+ def __init__(self, trait_types, **kwargs):
"""Construct a Union trait.
This trait allows values that are allowed by at least one of the
@@ -1951,8 +1951,8 @@ class Union(TraitType):
with the validation function of Float, then Bool, and finally Int.
"""
self.trait_types = list(trait_types)
- self.info_text = " or ".join([tt.info() for tt in self.trait_types])
- super(Union, self).__init__(**kwargs)
+ self.info_text = " or ".join([tt.info() for tt in self.trait_types])
+ super(Union, self).__init__(**kwargs)
def default(self, obj=None):
default = super(Union, self).default(obj)
@@ -1974,13 +1974,13 @@ class Union(TraitType):
super(Union, self).instance_init(obj)
def validate(self, obj, value):
- with obj.cross_validation_lock:
+ with obj.cross_validation_lock:
for trait_type in self.trait_types:
try:
v = trait_type._validate(obj, value)
- # In the case of an element trait, the name is None
- if self.name is not None:
- setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
+ # In the case of an element trait, the name is None
+ if self.name is not None:
+ setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
return v
except TraitError:
continue
@@ -1992,7 +1992,7 @@ class Union(TraitType):
else:
return Union(self.trait_types + [other])
-
+
#-----------------------------------------------------------------------------
# Basic TraitTypes implementations/subclasses
#-----------------------------------------------------------------------------
@@ -2005,37 +2005,37 @@ class Any(TraitType):
info_text = 'any value'
-def _validate_bounds(trait, obj, value):
- """
- Validate that a number to be applied to a trait is between bounds.
-
- If value is not between min_bound and max_bound, this raises a
- TraitError with an error message appropriate for this trait.
- """
- if trait.min is not None and value < trait.min:
- raise TraitError(
- "The value of the '{name}' trait of {klass} instance should "
- "not be less than {min_bound}, but a value of {value} was "
- "specified".format(
- name=trait.name, klass=class_of(obj),
- value=value, min_bound=trait.min))
- if trait.max is not None and value > trait.max:
- raise TraitError(
- "The value of the '{name}' trait of {klass} instance should "
- "not be greater than {max_bound}, but a value of {value} was "
- "specified".format(
- name=trait.name, klass=class_of(obj),
- value=value, max_bound=trait.max))
- return value
-
-
+def _validate_bounds(trait, obj, value):
+ """
+ Validate that a number to be applied to a trait is between bounds.
+
+ If value is not between min_bound and max_bound, this raises a
+ TraitError with an error message appropriate for this trait.
+ """
+ if trait.min is not None and value < trait.min:
+ raise TraitError(
+ "The value of the '{name}' trait of {klass} instance should "
+ "not be less than {min_bound}, but a value of {value} was "
+ "specified".format(
+ name=trait.name, klass=class_of(obj),
+ value=value, min_bound=trait.min))
+ if trait.max is not None and value > trait.max:
+ raise TraitError(
+ "The value of the '{name}' trait of {klass} instance should "
+ "not be greater than {max_bound}, but a value of {value} was "
+ "specified".format(
+ name=trait.name, klass=class_of(obj),
+ value=value, max_bound=trait.max))
+ return value
+
+
class Int(TraitType):
"""An int trait."""
default_value = 0
info_text = 'an int'
- def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
+ def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
self.min = kwargs.pop('min', None)
self.max = kwargs.pop('max', None)
super(Int, self).__init__(default_value=default_value,
@@ -2044,7 +2044,7 @@ class Int(TraitType):
def validate(self, obj, value):
if not isinstance(value, int):
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
def from_string(self, s):
if self.allow_none and s == 'None':
@@ -2057,12 +2057,12 @@ class CInt(Int):
def validate(self, obj, value):
try:
- value = int(value)
+ value = int(value)
except Exception:
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
+
-
Long, CLong = Int, CInt
Integer = Int
@@ -2073,10 +2073,10 @@ class Float(TraitType):
default_value = 0.0
info_text = 'a float'
- def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
+ def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
self.min = kwargs.pop('min', -float('inf'))
self.max = kwargs.pop('max', float('inf'))
- super(Float, self).__init__(default_value=default_value,
+ super(Float, self).__init__(default_value=default_value,
allow_none=allow_none, **kwargs)
def validate(self, obj, value):
@@ -2084,7 +2084,7 @@ class Float(TraitType):
value = float(value)
if not isinstance(value, float):
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
def from_string(self, s):
if self.allow_none and s == 'None':
@@ -2097,12 +2097,12 @@ class CFloat(Float):
def validate(self, obj, value):
try:
- value = float(value)
+ value = float(value)
except Exception:
self.error(obj, value)
- return _validate_bounds(self, obj, value)
+ return _validate_bounds(self, obj, value)
+
-
class Complex(TraitType):
"""A trait for complex numbers."""
@@ -2243,7 +2243,7 @@ class DottedObjectName(ObjectName):
value = self.coerce_str(obj, value)
if isinstance(value, str) and all(isidentifier(a)
- for a in value.split('.')):
+ for a in value.split('.')):
return value
self.error(obj, value)
@@ -2289,11 +2289,11 @@ class CBool(Bool):
class Enum(TraitType):
"""An enum whose value must be in a given sequence."""
- def __init__(self, values, default_value=Undefined, **kwargs):
+ def __init__(self, values, default_value=Undefined, **kwargs):
self.values = values
- if kwargs.get('allow_none', False) and default_value is Undefined:
+ if kwargs.get('allow_none', False) and default_value is Undefined:
default_value = None
- super(Enum, self).__init__(default_value, **kwargs)
+ super(Enum, self).__init__(default_value, **kwargs)
def validate(self, obj, value):
if value in self.values:
@@ -2331,10 +2331,10 @@ class Enum(TraitType):
class CaselessStrEnum(Enum):
"""An enum of strings where the case should be ignored."""
-
- def __init__(self, values, default_value=Undefined, **kwargs):
+
+ def __init__(self, values, default_value=Undefined, **kwargs):
super().__init__(values, default_value=default_value, **kwargs)
-
+
def validate(self, obj, value):
if not isinstance(value, str):
self.error(obj, value)
@@ -2444,7 +2444,7 @@ class Container(Instance):
will be cast to the container type.
allow_none : bool [ default False ]
Whether to allow the value to be None
- **kwargs : any
+ **kwargs : any
further keys for extensions to the Trait (e.g. config)
"""
@@ -2630,7 +2630,7 @@ class List(Container):
self._minlen = minlen
self._maxlen = maxlen
super(List, self).__init__(trait=trait, default_value=default_value,
- **kwargs)
+ **kwargs)
def length_error(self, obj, value):
e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
@@ -2693,7 +2693,7 @@ class Set(List):
maxlen : Int [ default sys.maxsize ]
The maximum length of the input list
"""
- super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
+ super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
def default_value_repr(self):
# Ensure default value is sorted for a reproducible build
@@ -2709,7 +2709,7 @@ class Tuple(Container):
klass = tuple
_cast_types = (list,)
- def __init__(self, *traits, **kwargs):
+ def __init__(self, *traits, **kwargs):
"""Create a tuple from a list, set, or tuple.
Create a fixed-type tuple with Traits:
@@ -2849,14 +2849,14 @@ class Dict(Instance):
_key_trait = None
def __init__(self, value_trait=None, per_key_traits=None, key_trait=None, default_value=Undefined,
- **kwargs):
- """Create a dict trait type from a Python dict.
+ **kwargs):
+ """Create a dict trait type from a Python dict.
The default value is created by doing ``dict(default_value)``,
which creates a copy of the ``default_value``.
- Parameters
- ----------
+ Parameters
+ ----------
value_trait : TraitType [ optional ]
The specified trait type to check and use to restrict the values of
the dict. If unspecified, values are not checked.
@@ -2871,7 +2871,7 @@ class Dict(Instance):
The default value for the Dict. Must be dict, tuple, or None, and
will be cast to a dict if not None. If any key or value traits are specified,
the `default_value` must conform to the constraints.
-
+
Examples
--------
>>> d = Dict(Unicode())
@@ -2934,8 +2934,8 @@ class Dict(Instance):
# Case where a type of TraitType is provided rather than an instance
if is_trait(value_trait):
if isinstance(value_trait, type):
- warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
- " Passing types is deprecated in traitlets 4.1.",
+ warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
+ " Passing types is deprecated in traitlets 4.1.",
DeprecationWarning, stacklevel=2)
value_trait = value_trait()
self._value_trait = value_trait
@@ -2954,7 +2954,7 @@ class Dict(Instance):
self._per_key_traits = per_key_traits
- super(Dict, self).__init__(klass=dict, args=args, **kwargs)
+ super(Dict, self).__init__(klass=dict, args=args, **kwargs)
def element_error(self, obj, element, validator, side='Values'):
e = side + " of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
@@ -2974,7 +2974,7 @@ class Dict(Instance):
value_trait = self._value_trait
if not (key_trait or value_trait or per_key_override):
return value
-
+
validated = {}
for key in value:
v = value[key]
@@ -2990,7 +2990,7 @@ class Dict(Instance):
except TraitError:
self.element_error(obj, v, active_value_trait, 'Values')
validated[key] = v
-
+
return self.klass(validated)
def class_init(self, cls, name):
@@ -3127,85 +3127,85 @@ class CRegExp(TraitType):
return re.compile(value)
except Exception:
self.error(obj, value)
-
-
-class UseEnum(TraitType):
- """Use a Enum class as model for the data type description.
- Note that if no default-value is provided, the first enum-value is used
- as default-value.
-
- .. sourcecode:: python
-
- # -- SINCE: Python 3.4 (or install backport: pip install enum34)
- import enum
- from traitlets import HasTraits, UseEnum
-
- class Color(enum.Enum):
- red = 1 # -- IMPLICIT: default_value
- blue = 2
- green = 3
-
- class MyEntity(HasTraits):
- color = UseEnum(Color, default_value=Color.blue)
-
- entity = MyEntity(color=Color.red)
- entity.color = Color.green # USE: Enum-value (preferred)
- entity.color = "green" # USE: name (as string)
- entity.color = "Color.green" # USE: scoped-name (as string)
- entity.color = 3 # USE: number (as int)
- assert entity.color is Color.green
- """
- default_value = None
- info_text = "Trait type adapter to a Enum class"
-
- def __init__(self, enum_class, default_value=None, **kwargs):
- assert issubclass(enum_class, enum.Enum), \
- "REQUIRE: enum.Enum, but was: %r" % enum_class
- allow_none = kwargs.get("allow_none", False)
- if default_value is None and not allow_none:
- default_value = list(enum_class.__members__.values())[0]
- super(UseEnum, self).__init__(default_value=default_value, **kwargs)
- self.enum_class = enum_class
- self.name_prefix = enum_class.__name__ + "."
-
- def select_by_number(self, value, default=Undefined):
- """Selects enum-value by using its number-constant."""
- assert isinstance(value, int)
- enum_members = self.enum_class.__members__
- for enum_item in enum_members.values():
- if enum_item.value == value:
- return enum_item
- # -- NOT FOUND:
- return default
-
- def select_by_name(self, value, default=Undefined):
- """Selects enum-value by using its name or scoped-name."""
+
+
+class UseEnum(TraitType):
+ """Use a Enum class as model for the data type description.
+ Note that if no default-value is provided, the first enum-value is used
+ as default-value.
+
+ .. sourcecode:: python
+
+ # -- SINCE: Python 3.4 (or install backport: pip install enum34)
+ import enum
+ from traitlets import HasTraits, UseEnum
+
+ class Color(enum.Enum):
+ red = 1 # -- IMPLICIT: default_value
+ blue = 2
+ green = 3
+
+ class MyEntity(HasTraits):
+ color = UseEnum(Color, default_value=Color.blue)
+
+ entity = MyEntity(color=Color.red)
+ entity.color = Color.green # USE: Enum-value (preferred)
+ entity.color = "green" # USE: name (as string)
+ entity.color = "Color.green" # USE: scoped-name (as string)
+ entity.color = 3 # USE: number (as int)
+ assert entity.color is Color.green
+ """
+ default_value = None
+ info_text = "Trait type adapter to a Enum class"
+
+ def __init__(self, enum_class, default_value=None, **kwargs):
+ assert issubclass(enum_class, enum.Enum), \
+ "REQUIRE: enum.Enum, but was: %r" % enum_class
+ allow_none = kwargs.get("allow_none", False)
+ if default_value is None and not allow_none:
+ default_value = list(enum_class.__members__.values())[0]
+ super(UseEnum, self).__init__(default_value=default_value, **kwargs)
+ self.enum_class = enum_class
+ self.name_prefix = enum_class.__name__ + "."
+
+ def select_by_number(self, value, default=Undefined):
+ """Selects enum-value by using its number-constant."""
+ assert isinstance(value, int)
+ enum_members = self.enum_class.__members__
+ for enum_item in enum_members.values():
+ if enum_item.value == value:
+ return enum_item
+ # -- NOT FOUND:
+ return default
+
+ def select_by_name(self, value, default=Undefined):
+ """Selects enum-value by using its name or scoped-name."""
assert isinstance(value, str)
- if value.startswith(self.name_prefix):
- # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
- value = value.replace(self.name_prefix, "", 1)
- return self.enum_class.__members__.get(value, default)
-
- def validate(self, obj, value):
- if isinstance(value, self.enum_class):
- return value
- elif isinstance(value, int):
- # -- CONVERT: number => enum_value (item)
- value2 = self.select_by_number(value)
- if value2 is not Undefined:
- return value2
+ if value.startswith(self.name_prefix):
+ # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
+ value = value.replace(self.name_prefix, "", 1)
+ return self.enum_class.__members__.get(value, default)
+
+ def validate(self, obj, value):
+ if isinstance(value, self.enum_class):
+ return value
+ elif isinstance(value, int):
+ # -- CONVERT: number => enum_value (item)
+ value2 = self.select_by_number(value)
+ if value2 is not Undefined:
+ return value2
elif isinstance(value, str):
- # -- CONVERT: name or scoped_name (as string) => enum_value (item)
- value2 = self.select_by_name(value)
- if value2 is not Undefined:
- return value2
- elif value is None:
- if self.allow_none:
- return None
- else:
- return self.default_value
- self.error(obj, value)
-
+ # -- CONVERT: name or scoped_name (as string) => enum_value (item)
+ value2 = self.select_by_name(value)
+ if value2 is not Undefined:
+ return value2
+ elif value is None:
+ if self.allow_none:
+ return None
+ else:
+ return self.default_value
+ self.error(obj, value)
+
def _choices_str(self, as_rst=False):
""" Returns a description of the trait choices (not none)."""
choices = self.enum_class.__members__.keys()
@@ -3221,7 +3221,7 @@ class UseEnum(TraitType):
'')
return 'any of %s%s' % (self._choices_str(as_rst), none)
- def info(self):
+ def info(self):
return self._info(as_rst=False)
def info_rst(self):
diff --git a/contrib/python/traitlets/py3/traitlets/utils/bunch.py b/contrib/python/traitlets/py3/traitlets/utils/bunch.py
index dc40b5df7d..2edb830ad6 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/bunch.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/bunch.py
@@ -1,25 +1,25 @@
-"""Yet another implementation of bunch
-
-attribute-access of items on a dict.
-"""
-
-# Copyright (c) Jupyter Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-class Bunch(dict):
- """A dict with attribute-access"""
- def __getattr__(self, key):
- try:
- return self.__getitem__(key)
- except KeyError:
- raise AttributeError(key)
-
- def __setattr__(self, key, value):
- self.__setitem__(key, value)
-
- def __dir__(self):
- # py2-compat: can't use super because dict doesn't have __dir__
- names = dir({})
- names.extend(self.keys())
- return names
-
+"""Yet another implementation of bunch
+
+attribute-access of items on a dict.
+"""
+
+# Copyright (c) Jupyter Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+class Bunch(dict):
+ """A dict with attribute-access"""
+ def __getattr__(self, key):
+ try:
+ return self.__getitem__(key)
+ except KeyError:
+ raise AttributeError(key)
+
+ def __setattr__(self, key, value):
+ self.__setitem__(key, value)
+
+ def __dir__(self):
+ # py2-compat: can't use super because dict doesn't have __dir__
+ names = dir({})
+ names.extend(self.keys())
+ return names
+
diff --git a/contrib/python/traitlets/py3/ya.make b/contrib/python/traitlets/py3/ya.make
index 99460fa8ed..46980f21b3 100644
--- a/contrib/python/traitlets/py3/ya.make
+++ b/contrib/python/traitlets/py3/ya.make
@@ -9,7 +9,7 @@ OWNER(borman nslus g:python-contrib)
VERSION(5.1.1)
LICENSE(BSD-3-Clause)
-
+
NO_LINT()
PY_SRCS(
@@ -28,7 +28,7 @@ PY_SRCS(
traitlets/tests/utils.py
traitlets/traitlets.py
traitlets/utils/__init__.py
- traitlets/utils/bunch.py
+ traitlets/utils/bunch.py
traitlets/utils/decorators.py
traitlets/utils/descriptions.py
traitlets/utils/getargspec.py
diff --git a/contrib/python/ya.make b/contrib/python/ya.make
index 9fefcae7a4..d01ced9f3a 100644
--- a/contrib/python/ya.make
+++ b/contrib/python/ya.make
@@ -124,7 +124,7 @@ RECURSE(
braceexpand
bravado
bravado-core
- bsddb3
+ bsddb3
bson
bz2file
cached-property
@@ -151,7 +151,7 @@ RECURSE(
clang
clang/example
cli-helpers
- click
+ click
click-didyoumean
click-plugins
click-repl
@@ -160,7 +160,7 @@ RECURSE(
clickhouse-sqlalchemy
cloudpickle
color
- colorama
+ colorama
coloredlogs
colorhash
colorlog
@@ -202,7 +202,7 @@ RECURSE(
DAWG-Python
dbf_light
debian-inspector
- decorator
+ decorator
deepdiff
deepmerge
defusedxml
@@ -210,7 +210,7 @@ RECURSE(
Deprecated
dictpath
diff-match-patch
- directio
+ directio
distro
django
django-admin-inline-paginator
@@ -315,7 +315,7 @@ RECURSE(
dm.xmlsec.binding
dnspython
docker
- docopt
+ docopt
docstring-parser
docutils
dohq-teamcity
@@ -405,7 +405,7 @@ RECURSE(
Flask-RESTful
flask-restplus
flask-restx
- Flask-Script
+ Flask-Script
flask-shell-ipython
Flask-Shelve
Flask-SQLAlchemy
@@ -425,7 +425,7 @@ RECURSE(
funcparserlib
funcsigs
functools32
- furl
+ furl
future
futures
gast
@@ -463,11 +463,11 @@ RECURSE(
graphql-relay
graphviz
greenify
- greenlet
+ greenlet
grequests
grpcio-opentracing
gspread
- gunicorn
+ gunicorn
h11
h2
h3
@@ -505,7 +505,7 @@ RECURSE(
icalendar
idna
idna-ssl
- ijson
+ ijson
imagesize
IMAPClient
imgkit
@@ -524,12 +524,12 @@ RECURSE(
intbitset
intspan
invoke
- ipaddr
+ ipaddr
ipaddress
ipadic
ipdb
ipykernel
- ipython
+ ipython
ipython-genutils
ipython-sql
ipywidgets
@@ -543,7 +543,7 @@ RECURSE(
jaraco.functools
javaproperties
jdcal
- jedi
+ jedi
Jinja2
jinja2-time
jmespath
@@ -604,7 +604,7 @@ RECURSE(
Mako
marisa_trie
markdown2
- Markdown
+ Markdown
MarkupSafe
marshmallow
marshmallow_dataclass
@@ -651,9 +651,9 @@ RECURSE(
mypy-extensions
mypy-protobuf
mypy-zope
- MySQL-python
+ MySQL-python
mysqlclient-python
- namedlist
+ namedlist
natsort
nbclient
nbconvert
@@ -670,7 +670,7 @@ RECURSE(
nose
notebook
num2words
- numpy
+ numpy
oauth2client
oauthlib
objgraph
@@ -692,7 +692,7 @@ RECURSE(
opt-einsum
option
ordered-set
- orderedmultidict
+ orderedmultidict
orderedset
os-fast-reservoir
packageurl-python
@@ -733,12 +733,12 @@ RECURSE(
peewee/playhouse
pefile
pem
- pexpect
+ pexpect
pgcli
PGPy
pgspecial
phonenumbers
- pickleshare
+ pickleshare
pika
Pillow
pip
@@ -758,7 +758,7 @@ RECURSE(
pq
pql
prance
- premailer
+ premailer
preshed
pretend
prettytable
@@ -774,14 +774,14 @@ RECURSE(
protobuf_to_dict
psutil
psycogreen
- psycopg2
- ptpython
- ptyprocess
+ psycopg2
+ ptpython
+ ptyprocess
publicsuffix2
pure-eval
pure-python-adb
pure-sasl
- py
+ py
py-asciimath
py-expression-eval
py-radix
@@ -799,7 +799,7 @@ RECURSE(
pycollada
pycountry
pycparser
- pycrypto
+ pycrypto
pycryptodome
pycurl
pycurl/example
@@ -831,7 +831,7 @@ RECURSE(
pylzma
pymaven-patch
PyMeeus
- pymongo
+ pymongo
pymorphy2
pymorphy2-dicts-ru
pymqi
@@ -922,7 +922,7 @@ RECURSE(
pyudev
pyusb
PyWavelets
- PyYAML
+ PyYAML
pyzmq
qemu
qrcode
@@ -983,7 +983,7 @@ RECURSE(
seaborn
selectors2
selenium
- semantic-version
+ semantic-version
semver
Send2Trash
sentinels
@@ -1081,7 +1081,7 @@ RECURSE(
tqdm
trace_event
traceback2
- traitlets
+ traitlets
transfer_manager_client
transitions
transliterate
@@ -1110,7 +1110,7 @@ RECURSE(
umongo
unicodecsv
Unidecode
- unidiff
+ unidiff
uplink
uritemplate
uritools
diff --git a/contrib/tools/bison/bison/arcadia_root.cpp.in b/contrib/tools/bison/bison/arcadia_root.cpp.in
index 00e7a4a164..f4e9dd9429 100644
--- a/contrib/tools/bison/bison/arcadia_root.cpp.in
+++ b/contrib/tools/bison/bison/arcadia_root.cpp.in
@@ -1,10 +1,10 @@
-#include "arcadia_root.h"
-
-extern "C" {
-
-const char* ArcadiaRoot() THROWING {
- return R"__weirdrawstr(@ARCADIA_ROOT@)__weirdrawstr";
-}
-
-}
-
+#include "arcadia_root.h"
+
+extern "C" {
+
+const char* ArcadiaRoot() THROWING {
+ return R"__weirdrawstr(@ARCADIA_ROOT@)__weirdrawstr";
+}
+
+}
+
diff --git a/contrib/tools/bison/bison/arcadia_root.h b/contrib/tools/bison/bison/arcadia_root.h
index f1600f614c..9c89539def 100644
--- a/contrib/tools/bison/bison/arcadia_root.h
+++ b/contrib/tools/bison/bison/arcadia_root.h
@@ -1,15 +1,15 @@
-#pragma once
-
-#define THROWING
-
-#ifdef __cplusplus
+#pragma once
+
+#define THROWING
+
+#ifdef __cplusplus
#define THROWING noexcept
-extern "C" {
-#endif
-
-const char* ArcadiaRoot() THROWING;
-
-#ifdef __cplusplus
-}
-#endif
-
+extern "C" {
+#endif
+
+const char* ArcadiaRoot() THROWING;
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/contrib/tools/bison/bison/src/output.c b/contrib/tools/bison/bison/src/output.c
index e0eb945814..61376ba390 100644
--- a/contrib/tools/bison/bison/src/output.c
+++ b/contrib/tools/bison/bison/src/output.c
@@ -44,8 +44,8 @@
#include "uniqstr.h"
-#include <contrib/tools/bison/bison/arcadia_root.h>
-
+#include <contrib/tools/bison/bison/arcadia_root.h>
+
#ifndef M4
#define M4 (m4_path)
#endif
@@ -59,7 +59,7 @@ default_pkgdatadir()
{
const char* arc_path = getenv("ARCADIA_ROOT_DISTBUILD");
if (arc_path == NULL)
- arc_path = ArcadiaRoot();
+ arc_path = ArcadiaRoot();
return uniqstr_vsprintf("%s/" STR(BISON_DATA_DIR), arc_path);
}
#define PKGDATADIR (default_pkgdatadir())
diff --git a/contrib/tools/bison/bison/ya.make b/contrib/tools/bison/bison/ya.make
index 44139ca6bf..04f8ae3758 100644
--- a/contrib/tools/bison/bison/ya.make
+++ b/contrib/tools/bison/bison/ya.make
@@ -15,7 +15,7 @@ ENDIF()
NO_COMPILER_WARNINGS()
-ADDINCLSELF()
+ADDINCLSELF()
SRCS(
src/AnnotationList.c
@@ -54,7 +54,7 @@ SRCS(
src/symtab.c
src/tables.c
src/uniqstr.c
- arcadia_root.cpp.in
+ arcadia_root.cpp.in
)
CFLAGS(
diff --git a/contrib/tools/bison/gnulib/platform/win64/config.h b/contrib/tools/bison/gnulib/platform/win64/config.h
index fe0c8e9e0a..cf3d366e18 100644
--- a/contrib/tools/bison/gnulib/platform/win64/config.h
+++ b/contrib/tools/bison/gnulib/platform/win64/config.h
@@ -1,8 +1,8 @@
/* lib/config.h. Generated from config.hin by configure. */
/* lib/config.hin. Generated from configure.ac by autoheader. */
-#include <contrib/tools/bison/gnulib/win_sdk10.h>
-
+#include <contrib/tools/bison/gnulib/win_sdk10.h>
+
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
@@ -1240,11 +1240,11 @@ char *strsignal (int signum);
#define PACKAGE_VERSION "3.0.0"
/* the number of pending output bytes on stream 'fp' */
-#if WIN_SDK10
-#define PENDING_OUTPUT_N_BYTES ((TWinSdk10File*)fp)->_ptr - ((TWinSdk10File*)fp)->_base
-#else
+#if WIN_SDK10
+#define PENDING_OUTPUT_N_BYTES ((TWinSdk10File*)fp)->_ptr - ((TWinSdk10File*)fp)->_base
+#else
#define PENDING_OUTPUT_N_BYTES fp->_ptr - fp->_base
-#endif
+#endif
/* Define if <inttypes.h> exists and defines unusable PRI* macros. */
/* #undef PRI_MACROS_BROKEN */
diff --git a/contrib/tools/bison/gnulib/platform/win64/fcntl.h b/contrib/tools/bison/gnulib/platform/win64/fcntl.h
index 11832d987e..dd3a1e5208 100644
--- a/contrib/tools/bison/gnulib/platform/win64/fcntl.h
+++ b/contrib/tools/bison/gnulib/platform/win64/fcntl.h
@@ -38,11 +38,11 @@
#if !(defined __GLIBC__ || defined __UCLIBC__) || (defined __cplusplus && defined GNULIB_NAMESPACE && !(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
# include <sys/stat.h>
#endif
-#if _MSC_VER >= 1900
-#include <../ucrt/fcntl.h>
-#else
-#include <../include/fcntl.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/fcntl.h>
+#else
+#include <../include/fcntl.h>
+#endif
#else
/* Normal invocation convention. */
@@ -62,11 +62,11 @@
# include <sys/stat.h>
#endif
/* The include_next requires a split double-inclusion guard. */
-#if _MSC_VER >= 1900
-#include <../ucrt/fcntl.h>
-#else
-#include <../include/fcntl.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/fcntl.h>
+#else
+#include <../include/fcntl.h>
+#endif
#ifndef _GL_M4_FCNTL_H
#define _GL_M4_FCNTL_H
diff --git a/contrib/tools/bison/gnulib/platform/win64/locale.h b/contrib/tools/bison/gnulib/platform/win64/locale.h
index 215996afd3..ddebf413d2 100644
--- a/contrib/tools/bison/gnulib/platform/win64/locale.h
+++ b/contrib/tools/bison/gnulib/platform/win64/locale.h
@@ -25,11 +25,11 @@
/* Special invocation conventions to handle Solaris header files
(through Solaris 10) when combined with gettext's libintl.h. */
-#if _MSC_VER >= 1900
-#include <../ucrt/locale.h>
-#else
-#include <../include/locale.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/locale.h>
+#else
+#include <../include/locale.h>
+#endif
#else
/* Normal invocation convention. */
@@ -39,11 +39,11 @@
#define _GL_ALREADY_INCLUDING_LOCALE_H
/* The include_next requires a split double-inclusion guard. */
-#if _MSC_VER >= 1900
-#include <../ucrt/locale.h>
-#else
-#include <../include/locale.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/locale.h>
+#else
+#include <../include/locale.h>
+#endif
#undef _GL_ALREADY_INCLUDING_LOCALE_H
diff --git a/contrib/tools/bison/gnulib/platform/win64/math.h b/contrib/tools/bison/gnulib/platform/win64/math.h
index a8caa9a729..b2a0023d11 100644
--- a/contrib/tools/bison/gnulib/platform/win64/math.h
+++ b/contrib/tools/bison/gnulib/platform/win64/math.h
@@ -24,11 +24,11 @@
/* The include_next requires a split double-inclusion guard. */
-#if _MSC_VER >= 1900
-#include <../ucrt/math.h>
-#else
-#include <../include/math.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/math.h>
+#else
+#include <../include/math.h>
+#endif
#ifndef _GL_M4_MATH_H
#define _GL_M4_MATH_H
diff --git a/contrib/tools/bison/gnulib/platform/win64/signal.h b/contrib/tools/bison/gnulib/platform/win64/signal.h
index c081ae87e2..11f3a81cf5 100644
--- a/contrib/tools/bison/gnulib/platform/win64/signal.h
+++ b/contrib/tools/bison/gnulib/platform/win64/signal.h
@@ -33,11 +33,11 @@
In this situation, some of the functions are not yet declared, therefore
we cannot provide the C++ aliases. */
-#if _MSC_VER >= 1900
-#include <../ucrt/signal.h>
-#else
-#include <../include/signal.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/signal.h>
+#else
+#include <../include/signal.h>
+#endif
#else
/* Normal invocation convention. */
@@ -53,11 +53,11 @@
#include <sys/types.h>
/* The include_next requires a split double-inclusion guard. */
-#if _MSC_VER >= 1900
-#include <../ucrt/signal.h>
-#else
-#include <../include/signal.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/signal.h>
+#else
+#include <../include/signal.h>
+#endif
#undef _GL_ALREADY_INCLUDING_SIGNAL_H
diff --git a/contrib/tools/bison/gnulib/platform/win64/sys/stat.h b/contrib/tools/bison/gnulib/platform/win64/sys/stat.h
index 0f18e52276..429d3886dc 100644
--- a/contrib/tools/bison/gnulib/platform/win64/sys/stat.h
+++ b/contrib/tools/bison/gnulib/platform/win64/sys/stat.h
@@ -29,11 +29,11 @@
#if defined __need_system_sys_stat_h
/* Special invocation convention. */
-#if _MSC_VER >= 1900
-#include <../ucrt/sys/stat.h>
-#else
-#include <../include/sys/stat.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/sys/stat.h>
+#else
+#include <../include/sys/stat.h>
+#endif
#else
/* Normal invocation convention. */
@@ -48,11 +48,11 @@
#include <time.h>
/* The include_next requires a split double-inclusion guard. */
-#if _MSC_VER >= 1900
-#include <../ucrt/sys/stat.h>
-#else
-#include <../include/sys/stat.h>
-#endif
+#if _MSC_VER >= 1900
+#include <../ucrt/sys/stat.h>
+#else
+#include <../include/sys/stat.h>
+#endif
#ifndef _GL_M4_SYS_STAT_H
#define _GL_M4_SYS_STAT_H
diff --git a/contrib/tools/bison/gnulib/src/fpurge.c b/contrib/tools/bison/gnulib/src/fpurge.c
index 21104cce3a..6c74355b71 100644
--- a/contrib/tools/bison/gnulib/src/fpurge.c
+++ b/contrib/tools/bison/gnulib/src/fpurge.c
@@ -101,11 +101,11 @@ fpurge (FILE *fp)
if (fp->_ptr != NULL)
fp->_cnt = 0;
return 0;
-# elif WIN_SDK10
- ((TWinSdk10File*)fp)->_ptr = ((TWinSdk10File*)fp)->_base;
- if (((TWinSdk10File*)fp)->_ptr != NULL)
- ((TWinSdk10File*)fp)->_cnt = 0;
- return 0;
+# elif WIN_SDK10
+ ((TWinSdk10File*)fp)->_ptr = ((TWinSdk10File*)fp)->_base;
+ if (((TWinSdk10File*)fp)->_ptr != NULL)
+ ((TWinSdk10File*)fp)->_cnt = 0;
+ return 0;
# elif defined __UCLIBC__ /* uClibc */
# ifdef __STDIO_BUFFERS
if (fp->__modeflags & __FLAG_WRITING)
diff --git a/contrib/tools/bison/gnulib/src/freadahead.c b/contrib/tools/bison/gnulib/src/freadahead.c
index d06ace35c3..bf53271fd2 100644
--- a/contrib/tools/bison/gnulib/src/freadahead.c
+++ b/contrib/tools/bison/gnulib/src/freadahead.c
@@ -56,10 +56,10 @@ freadahead (FILE *fp)
if ((fp_->_flag & _IOWRT) != 0)
return 0;
return fp_->_cnt;
-#elif WIN_SDK10
- if ((((TWinSdk10File*)fp)->_flags & WIN_SDK10_IOWRITE) != 0)
- return 0;
- return ((TWinSdk10File*)fp)->_cnt;
+#elif WIN_SDK10
+ if ((((TWinSdk10File*)fp)->_flags & WIN_SDK10_IOWRITE) != 0)
+ return 0;
+ return ((TWinSdk10File*)fp)->_cnt;
#elif defined __UCLIBC__ /* uClibc */
# ifdef __STDIO_BUFFERS
if (fp->__modeflags & __FLAG_WRITING)
diff --git a/contrib/tools/bison/gnulib/src/freading.c b/contrib/tools/bison/gnulib/src/freading.c
index 1ab8fb4aa1..3d7e4e56f0 100644
--- a/contrib/tools/bison/gnulib/src/freading.c
+++ b/contrib/tools/bison/gnulib/src/freading.c
@@ -47,8 +47,8 @@ freading (FILE *fp)
# else
return (fp->_flag & _IOREAD) != 0;
# endif
-# elif WIN_SDK10
- return (((TWinSdk10File*)fp)->_flags & WIN_SDK10_IOREAD) != 0;
+# elif WIN_SDK10
+ return (((TWinSdk10File*)fp)->_flags & WIN_SDK10_IOREAD) != 0;
# elif defined __UCLIBC__ /* uClibc */
return (fp->__modeflags & (__FLAG_READONLY | __FLAG_READING)) != 0;
# elif defined __QNX__ /* QNX */
diff --git a/contrib/tools/bison/gnulib/src/fseeko.c b/contrib/tools/bison/gnulib/src/fseeko.c
index de838f01a4..16404b71eb 100644
--- a/contrib/tools/bison/gnulib/src/fseeko.c
+++ b/contrib/tools/bison/gnulib/src/fseeko.c
@@ -82,9 +82,9 @@ fseeko (FILE *fp, off_t offset, int whence)
#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
if (fp_->_ptr == fp_->_base
&& (fp_->_ptr == NULL || fp_->_cnt == 0))
-#elif WIN_SDK10
- if (((TWinSdk10File*)fp)->_ptr == ((TWinSdk10File*)fp)->_base
- && (((TWinSdk10File*)fp)->_ptr == NULL || ((TWinSdk10File*)fp)->_cnt == 0))
+#elif WIN_SDK10
+ if (((TWinSdk10File*)fp)->_ptr == ((TWinSdk10File*)fp)->_base
+ && (((TWinSdk10File*)fp)->_ptr == NULL || ((TWinSdk10File*)fp)->_cnt == 0))
#elif defined __UCLIBC__ /* uClibc */
if (((fp->__modeflags & __FLAG_WRITING) == 0
|| fp->__bufpos == fp->__bufstart)
diff --git a/contrib/tools/bison/gnulib/src/fseterr.c b/contrib/tools/bison/gnulib/src/fseterr.c
index be36991486..9f7bea13b3 100644
--- a/contrib/tools/bison/gnulib/src/fseterr.c
+++ b/contrib/tools/bison/gnulib/src/fseterr.c
@@ -39,8 +39,8 @@ fseterr (FILE *fp)
fp->_flags |= _IOERR;
#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
fp_->_flag |= _IOERR;
-#elif WIN_SDK10
- ((TWinSdk10File*)fp)->_flags |= WIN_SDK10_IOERROR;
+#elif WIN_SDK10
+ ((TWinSdk10File*)fp)->_flags |= WIN_SDK10_IOERROR;
#elif defined __UCLIBC__ /* uClibc */
fp->__modeflags |= __FLAG_ERROR;
#elif defined __QNX__ /* QNX */
diff --git a/contrib/tools/bison/gnulib/src/snprintf.c b/contrib/tools/bison/gnulib/src/snprintf.c
index af0d87d673..9c34de3bb2 100644
--- a/contrib/tools/bison/gnulib/src/snprintf.c
+++ b/contrib/tools/bison/gnulib/src/snprintf.c
@@ -28,7 +28,7 @@
#include "vasnprintf.h"
-#if defined(_MSC_VER) && _MSC_VER < 1900
+#if defined(_MSC_VER) && _MSC_VER < 1900
/* Print formatted output to string STR. Similar to sprintf, but
additional length SIZE limit how much is written into STR. Returns
string length of formatted string (which may be larger than SIZE).
@@ -73,4 +73,4 @@ snprintf (char *str, size_t size, const char *format, ...)
return len;
}
-#endif
+#endif
diff --git a/contrib/tools/bison/gnulib/win_sdk10.h b/contrib/tools/bison/gnulib/win_sdk10.h
index fdf8dc9e20..76e5c86ccd 100644
--- a/contrib/tools/bison/gnulib/win_sdk10.h
+++ b/contrib/tools/bison/gnulib/win_sdk10.h
@@ -1,55 +1,55 @@
-#pragma once
-
-#if defined(_MSC_VER)
-
-#include <ntverp.h>
-
-// Check for Windows SDK 10+
-#if defined(VER_PRODUCTBUILD) && VER_PRODUCTBUILD >= 9600
-#define WIN_SDK10 1
-#else
-#define WIN_SDK10 0
-#endif
-
-// Since Windows SDK 10 FILE is an internal opaque structure with no backward compatibility.
-// This code has been transplanted from Windows SDK
-// corecrt_internal_stdio.h
-
-// __crt_stdio_stream_data
-#if WIN_SDK10
-typedef struct {
- union {
- void* _public_file;
- char* _ptr;
- };
-
- char* _base;
- int _cnt;
- long _flags;
- long _file;
- int _charbuf;
- int _bufsiz;
- char* _tmpfname;
- //CRITICAL_SECTION _lock;
-} TWinSdk10File;
-
-enum EWinSdk10ModeBits {
- WIN_SDK10_IOREAD = 0x0001,
- WIN_SDK10_IOWRITE = 0x0002,
- WIN_SDK10_IOUPDATE = 0x0004,
- WIN_SDK10_IOEOF = 0x0008,
- WIN_SDK10_IOERROR = 0x0010,
- WIN_SDK10_IOCTRLZ = 0x0020,
- WIN_SDK10_IOBUFFER_CRT = 0x0040,
- WIN_SDK10_IOBUFFER_USER = 0x0080,
- WIN_SDK10_IOBUFFER_SETVBUF = 0x0100,
- WIN_SDK10_IOBUFFER_STBUF = 0x0200,
- WIN_SDK10_IOBUFFER_NONE = 0x0400,
- WIN_SDK10_IOCOMMIT = 0x0800,
- WIN_SDK10_IOSTRING = 0x1000,
- WIN_SDK10_IOALLOCATED = 0x2000,
-};
-#endif
-
-#endif
-
+#pragma once
+
+#if defined(_MSC_VER)
+
+#include <ntverp.h>
+
+// Check for Windows SDK 10+
+#if defined(VER_PRODUCTBUILD) && VER_PRODUCTBUILD >= 9600
+#define WIN_SDK10 1
+#else
+#define WIN_SDK10 0
+#endif
+
+// Since Windows SDK 10 FILE is an internal opaque structure with no backward compatibility.
+// This code has been transplanted from Windows SDK
+// corecrt_internal_stdio.h
+
+// __crt_stdio_stream_data
+#if WIN_SDK10
+typedef struct {
+ union {
+ void* _public_file;
+ char* _ptr;
+ };
+
+ char* _base;
+ int _cnt;
+ long _flags;
+ long _file;
+ int _charbuf;
+ int _bufsiz;
+ char* _tmpfname;
+ //CRITICAL_SECTION _lock;
+} TWinSdk10File;
+
+enum EWinSdk10ModeBits {
+ WIN_SDK10_IOREAD = 0x0001,
+ WIN_SDK10_IOWRITE = 0x0002,
+ WIN_SDK10_IOUPDATE = 0x0004,
+ WIN_SDK10_IOEOF = 0x0008,
+ WIN_SDK10_IOERROR = 0x0010,
+ WIN_SDK10_IOCTRLZ = 0x0020,
+ WIN_SDK10_IOBUFFER_CRT = 0x0040,
+ WIN_SDK10_IOBUFFER_USER = 0x0080,
+ WIN_SDK10_IOBUFFER_SETVBUF = 0x0100,
+ WIN_SDK10_IOBUFFER_STBUF = 0x0200,
+ WIN_SDK10_IOBUFFER_NONE = 0x0400,
+ WIN_SDK10_IOCOMMIT = 0x0800,
+ WIN_SDK10_IOSTRING = 0x1000,
+ WIN_SDK10_IOALLOCATED = 0x2000,
+};
+#endif
+
+#endif
+
diff --git a/contrib/tools/python/ya.make b/contrib/tools/python/ya.make
index 79ec90aff2..fc95aaca64 100644
--- a/contrib/tools/python/ya.make
+++ b/contrib/tools/python/ya.make
@@ -4,8 +4,8 @@ OWNER(g:contrib orivej)
LICENSE(PSF-2.0)
-VERSION(2.7.16)
-
+VERSION(2.7.16)
+
ORIGINAL_SOURCE(https://github.com/python/cpython)
PEERDIR(
diff --git a/library/cpp/accurate_accumulate/benchmark/metrics/ya.make b/library/cpp/accurate_accumulate/benchmark/metrics/ya.make
index 724d942956..5d532e1479 100644
--- a/library/cpp/accurate_accumulate/benchmark/metrics/ya.make
+++ b/library/cpp/accurate_accumulate/benchmark/metrics/ya.make
@@ -1,4 +1,4 @@
-OWNER(yazevnul)
+OWNER(yazevnul)
PY2TEST()
@@ -10,7 +10,7 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
DEPENDS(library/cpp/accurate_accumulate/benchmark)
diff --git a/library/cpp/accurate_accumulate/benchmark/ya.make b/library/cpp/accurate_accumulate/benchmark/ya.make
index 07832861b3..20fd877389 100644
--- a/library/cpp/accurate_accumulate/benchmark/ya.make
+++ b/library/cpp/accurate_accumulate/benchmark/ya.make
@@ -1,4 +1,4 @@
-OWNER(yazevnul)
+OWNER(yazevnul)
Y_BENCHMARK()
diff --git a/library/cpp/actors/core/ut/ya.make b/library/cpp/actors/core/ut/ya.make
index 0badab9fc4..3ee28d5850 100644
--- a/library/cpp/actors/core/ut/ya.make
+++ b/library/cpp/actors/core/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/actors/core)
-OWNER(
- alexvru
- g:kikimr
-)
+OWNER(
+ alexvru
+ g:kikimr
+)
FORK_SUBTESTS()
IF (SANITIZER_TYPE)
@@ -21,7 +21,7 @@ ELSE()
ram:16
)
ENDIF()
-
+
PEERDIR(
library/cpp/actors/interconnect
diff --git a/library/cpp/actors/core/ya.make b/library/cpp/actors/core/ya.make
index 92d6456e0b..880a9d00db 100644
--- a/library/cpp/actors/core/ya.make
+++ b/library/cpp/actors/core/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- ddoarn
- g:kikimr
-)
+OWNER(
+ ddoarn
+ g:kikimr
+)
NO_WSHADOW()
@@ -12,10 +12,10 @@ IF (PROFILE_MEMORY_ALLOCATIONS)
ENDIF()
IF (ALLOCATOR == "B" OR ALLOCATOR == "BS" OR ALLOCATOR == "C")
- CXXFLAGS(-DBALLOC)
- PEERDIR(
+ CXXFLAGS(-DBALLOC)
+ PEERDIR(
library/cpp/balloc/optional
- )
+ )
ENDIF()
SRCS(
diff --git a/library/cpp/actors/helpers/ya.make b/library/cpp/actors/helpers/ya.make
index 9cf85b3641..d8771179de 100644
--- a/library/cpp/actors/helpers/ya.make
+++ b/library/cpp/actors/helpers/ya.make
@@ -1,6 +1,6 @@
LIBRARY()
-OWNER(g:kikimr)
+OWNER(g:kikimr)
SRCS(
activeactors.cpp
diff --git a/library/cpp/actors/interconnect/ut/ya.make b/library/cpp/actors/interconnect/ut/ya.make
index bd912e9822..2f5b13352e 100644
--- a/library/cpp/actors/interconnect/ut/ya.make
+++ b/library/cpp/actors/interconnect/ut/ya.make
@@ -2,7 +2,7 @@ UNITTEST()
OWNER(
alexvru
- g:kikimr
+ g:kikimr
)
IF (SANITIZER_TYPE == "thread")
diff --git a/library/cpp/actors/memory_log/ya.make b/library/cpp/actors/memory_log/ya.make
index 3808dde443..d89d5db4d7 100644
--- a/library/cpp/actors/memory_log/ya.make
+++ b/library/cpp/actors/memory_log/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- agri
- g:kikimr
-)
+OWNER(
+ agri
+ g:kikimr
+)
SRCS(
memlog.cpp
diff --git a/library/cpp/actors/prof/ut/ya.make b/library/cpp/actors/prof/ut/ya.make
index 9db075103c..47c58a8fb7 100644
--- a/library/cpp/actors/prof/ut/ya.make
+++ b/library/cpp/actors/prof/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/actors/prof)
-OWNER(
- agri
- g:kikimr
-)
+OWNER(
+ agri
+ g:kikimr
+)
SRCS(
tag_ut.cpp
diff --git a/library/cpp/actors/prof/ya.make b/library/cpp/actors/prof/ya.make
index e6bec000d0..b5e2497563 100644
--- a/library/cpp/actors/prof/ya.make
+++ b/library/cpp/actors/prof/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- agri
- g:kikimr
-)
+OWNER(
+ agri
+ g:kikimr
+)
SRCS(
tag.cpp
@@ -15,7 +15,7 @@ PEERDIR(
)
IF (PROFILE_MEMORY_ALLOCATIONS)
- CFLAGS(-DPROFILE_MEMORY_ALLOCATIONS)
+ CFLAGS(-DPROFILE_MEMORY_ALLOCATIONS)
PEERDIR(
library/cpp/malloc/api
library/cpp/lfalloc/dbg_info
diff --git a/library/cpp/actors/util/ut/ya.make b/library/cpp/actors/util/ut/ya.make
index bccb98d794..3b08b77984 100644
--- a/library/cpp/actors/util/ut/ya.make
+++ b/library/cpp/actors/util/ut/ya.make
@@ -5,10 +5,10 @@ IF (WITH_VALGRIND)
SIZE(MEDIUM)
ENDIF()
-OWNER(
- alexvru
- g:kikimr
-)
+OWNER(
+ alexvru
+ g:kikimr
+)
SRCS(
rope_ut.cpp
diff --git a/library/cpp/actors/wilson/ya.make b/library/cpp/actors/wilson/ya.make
index 21be05f5b7..e371f5061d 100644
--- a/library/cpp/actors/wilson/ya.make
+++ b/library/cpp/actors/wilson/ya.make
@@ -1,14 +1,14 @@
LIBRARY()
-PEERDIR(
+PEERDIR(
library/cpp/string_utils/base64
-)
-
-OWNER(alexvru)
-
-SRCS(
- wilson_event.h
- wilson_trace.h
-)
-
+)
+
+OWNER(alexvru)
+
+SRCS(
+ wilson_event.h
+ wilson_trace.h
+)
+
END()
diff --git a/library/cpp/blockcodecs/fuzz/ya.make b/library/cpp/blockcodecs/fuzz/ya.make
index ebcf569bb7..bc8becc9e1 100644
--- a/library/cpp/blockcodecs/fuzz/ya.make
+++ b/library/cpp/blockcodecs/fuzz/ya.make
@@ -1,7 +1,7 @@
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
IF (NOT MSVC)
FUZZ()
diff --git a/library/cpp/blockcodecs/ut/ya.make b/library/cpp/blockcodecs/ut/ya.make
index 136fdcb187..25b882c15b 100644
--- a/library/cpp/blockcodecs/ut/ya.make
+++ b/library/cpp/blockcodecs/ut/ya.make
@@ -3,11 +3,11 @@ UNITTEST_FOR(library/cpp/blockcodecs)
OWNER(pg)
FORK_TESTS()
-
+
FORK_SUBTESTS()
-
+
SPLIT_FACTOR(40)
-
+
TIMEOUT(300)
SIZE(MEDIUM)
diff --git a/library/cpp/build_info/ya.make b/library/cpp/build_info/ya.make
index 0c0f9d50b0..99886a8893 100644
--- a/library/cpp/build_info/ya.make
+++ b/library/cpp/build_info/ya.make
@@ -9,7 +9,7 @@ OWNER(
DEFAULT(SANDBOX_TASK_ID 0)
DEFAULT(KOSHER_SVN_VERSION "")
-CREATE_BUILDINFO_FOR(buildinfo_data.h)
+CREATE_BUILDINFO_FOR(buildinfo_data.h)
PEERDIR(
library/cpp/string_utils/base64
diff --git a/library/cpp/cgiparam/fuzz/ya.make b/library/cpp/cgiparam/fuzz/ya.make
index ab634f4844..8fb9d50d3b 100644
--- a/library/cpp/cgiparam/fuzz/ya.make
+++ b/library/cpp/cgiparam/fuzz/ya.make
@@ -1,9 +1,9 @@
FUZZ()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
main.cpp
diff --git a/library/cpp/codecs/static/example/ya.make b/library/cpp/codecs/static/example/ya.make
index 67342d3083..ca6c5fd900 100644
--- a/library/cpp/codecs/static/example/ya.make
+++ b/library/cpp/codecs/static/example/ya.make
@@ -12,13 +12,13 @@ PEERDIR(
)
ARCHIVE_ASM(
- "solar-8k-a.huffman.1467494385.codec_info"
- NAME codec_info_sa_huff_20160707
+ "solar-8k-a.huffman.1467494385.codec_info"
+ NAME codec_info_sa_huff_20160707
)
ARCHIVE_ASM(
- "huffman.1467494385.codec_info"
- NAME codec_info_huff_20160707
+ "huffman.1467494385.codec_info"
+ NAME codec_info_huff_20160707
)
END()
diff --git a/library/cpp/codecs/static/tools/common/ya.make b/library/cpp/codecs/static/tools/common/ya.make
index 3381c4b896..d624222dad 100644
--- a/library/cpp/codecs/static/tools/common/ya.make
+++ b/library/cpp/codecs/static/tools/common/ya.make
@@ -1,6 +1,6 @@
LIBRARY()
-OWNER(velavokr)
+OWNER(velavokr)
SRCS(
ct_common.cpp
@@ -14,6 +14,6 @@ PEERDIR(
util/draft
)
-GENERATE_ENUM_SERIALIZATION(ct_common.h)
+GENERATE_ENUM_SERIALIZATION(ct_common.h)
END()
diff --git a/library/cpp/codecs/static/tools/static_codec_checker/ya.make b/library/cpp/codecs/static/tools/static_codec_checker/ya.make
index 968880a781..90e06ca448 100644
--- a/library/cpp/codecs/static/tools/static_codec_checker/ya.make
+++ b/library/cpp/codecs/static/tools/static_codec_checker/ya.make
@@ -1,6 +1,6 @@
PROGRAM()
-OWNER(velavokr)
+OWNER(velavokr)
SRCS(
static_codec_checker.cpp
diff --git a/library/cpp/codecs/static/tools/static_codec_generator/ya.make b/library/cpp/codecs/static/tools/static_codec_generator/ya.make
index aa786f8886..efbc440dd1 100644
--- a/library/cpp/codecs/static/tools/static_codec_generator/ya.make
+++ b/library/cpp/codecs/static/tools/static_codec_generator/ya.make
@@ -1,6 +1,6 @@
PROGRAM()
-OWNER(velavokr)
+OWNER(velavokr)
SRCS(
static_codec_generator.cpp
diff --git a/library/cpp/comptable/usage/ya.make b/library/cpp/comptable/usage/ya.make
index 909e21d17c..ab31e7528c 100644
--- a/library/cpp/comptable/usage/ya.make
+++ b/library/cpp/comptable/usage/ya.make
@@ -2,12 +2,12 @@ PROGRAM()
OWNER(ironpeter)
-SRCS(
- usage.cpp
-)
+SRCS(
+ usage.cpp
+)
-PEERDIR(
+PEERDIR(
library/cpp/comptable
-)
+)
END()
diff --git a/library/cpp/comptable/ut/ya.make b/library/cpp/comptable/ut/ya.make
index ae777d6b6b..d0a49793a5 100644
--- a/library/cpp/comptable/ut/ya.make
+++ b/library/cpp/comptable/ut/ya.make
@@ -2,8 +2,8 @@ UNITTEST_FOR(library/cpp/comptable)
OWNER(ironpeter)
-SRCS(
- comptable_ut.cpp
-)
+SRCS(
+ comptable_ut.cpp
+)
END()
diff --git a/library/cpp/comptable/ya.make b/library/cpp/comptable/ya.make
index 270f086d30..314603c62a 100644
--- a/library/cpp/comptable/ya.make
+++ b/library/cpp/comptable/ya.make
@@ -2,12 +2,12 @@ LIBRARY()
OWNER(ironpeter)
-SRCS(
- comptable.cpp
-)
+SRCS(
+ comptable.cpp
+)
-PEERDIR(
+PEERDIR(
library/cpp/compproto
-)
+)
END()
diff --git a/library/cpp/containers/comptrie/loader/ut/ya.make b/library/cpp/containers/comptrie/loader/ut/ya.make
index 4b57a4f10e..6c0334d3ea 100644
--- a/library/cpp/containers/comptrie/loader/ut/ya.make
+++ b/library/cpp/containers/comptrie/loader/ut/ya.make
@@ -1,6 +1,6 @@
UNITTEST_FOR(library/cpp/containers/comptrie/loader)
-OWNER(my34)
+OWNER(my34)
ARCHIVE(
NAME data.inc
diff --git a/library/cpp/containers/intrusive_avl_tree/ut/ya.make b/library/cpp/containers/intrusive_avl_tree/ut/ya.make
index 0d9c8732f6..87920306d7 100644
--- a/library/cpp/containers/intrusive_avl_tree/ut/ya.make
+++ b/library/cpp/containers/intrusive_avl_tree/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/containers/intrusive_avl_tree)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
avltree_ut.cpp
diff --git a/library/cpp/containers/intrusive_avl_tree/ya.make b/library/cpp/containers/intrusive_avl_tree/ya.make
index 502848a8a9..6b061f2760 100644
--- a/library/cpp/containers/intrusive_avl_tree/ya.make
+++ b/library/cpp/containers/intrusive_avl_tree/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
avltree.cpp
diff --git a/library/cpp/containers/intrusive_rb_tree/fuzz/ya.make b/library/cpp/containers/intrusive_rb_tree/fuzz/ya.make
index ed6ed129a0..61be9919e6 100644
--- a/library/cpp/containers/intrusive_rb_tree/fuzz/ya.make
+++ b/library/cpp/containers/intrusive_rb_tree/fuzz/ya.make
@@ -1,12 +1,12 @@
FUZZ()
-OWNER(
- g:util
- mikari
-)
+OWNER(
+ g:util
+ mikari
+)
SIZE(LARGE)
-
+
TAG(ya:fat)
PEERDIR(
diff --git a/library/cpp/containers/intrusive_rb_tree/ut/ya.make b/library/cpp/containers/intrusive_rb_tree/ut/ya.make
index 05dd5121ba..6f1e3b38ee 100644
--- a/library/cpp/containers/intrusive_rb_tree/ut/ya.make
+++ b/library/cpp/containers/intrusive_rb_tree/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/containers/intrusive_rb_tree)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
rb_tree_ut.cpp
diff --git a/library/cpp/containers/intrusive_rb_tree/ya.make b/library/cpp/containers/intrusive_rb_tree/ya.make
index 31cd275585..2e5eddcfbe 100644
--- a/library/cpp/containers/intrusive_rb_tree/ya.make
+++ b/library/cpp/containers/intrusive_rb_tree/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
rb_tree.cpp
diff --git a/library/cpp/containers/ring_buffer/ya.make b/library/cpp/containers/ring_buffer/ya.make
index 7d8c0f8fa1..51333978f7 100644
--- a/library/cpp/containers/ring_buffer/ya.make
+++ b/library/cpp/containers/ring_buffer/ya.make
@@ -1,4 +1,4 @@
-OWNER(mowgli)
+OWNER(mowgli)
LIBRARY()
diff --git a/library/cpp/coroutine/engine/ya.make b/library/cpp/coroutine/engine/ya.make
index ce6c48fe19..8c20b9afc3 100644
--- a/library/cpp/coroutine/engine/ya.make
+++ b/library/cpp/coroutine/engine/ya.make
@@ -5,7 +5,7 @@ OWNER(
g:balancer
)
-GENERATE_ENUM_SERIALIZATION(poller.h)
+GENERATE_ENUM_SERIALIZATION(poller.h)
GENERATE_ENUM_SERIALIZATION(stack/stack_common.h)
PEERDIR(
diff --git a/library/cpp/deprecated/enum_codegen/ut/ya.make b/library/cpp/deprecated/enum_codegen/ut/ya.make
index 8f0c08a35c..32e7ad77a2 100644
--- a/library/cpp/deprecated/enum_codegen/ut/ya.make
+++ b/library/cpp/deprecated/enum_codegen/ut/ya.make
@@ -4,10 +4,10 @@ OWNER(g:util)
SRCDIR(library/cpp/deprecated/enum_codegen)
-PEERDIR(
+PEERDIR(
library/cpp/deprecated/enum_codegen
-)
-
+)
+
SRCS(
enum_codegen_ut.cpp
)
diff --git a/library/cpp/diff/ya.make b/library/cpp/diff/ya.make
index 5230cad6e9..a05b7ccbbc 100644
--- a/library/cpp/diff/ya.make
+++ b/library/cpp/diff/ya.make
@@ -2,12 +2,12 @@ LIBRARY()
OWNER(antonovvk)
-PEERDIR(
+PEERDIR(
library/cpp/lcs
library/cpp/containers/stack_array
)
-SRCS(
+SRCS(
diff.cpp
)
diff --git a/library/cpp/digest/argonish/benchmark/ya.make b/library/cpp/digest/argonish/benchmark/ya.make
index a36422e05c..5aad1b238f 100644
--- a/library/cpp/digest/argonish/benchmark/ya.make
+++ b/library/cpp/digest/argonish/benchmark/ya.make
@@ -2,12 +2,12 @@ OWNER(e-sidorov)
Y_BENCHMARK()
-PEERDIR(
+PEERDIR(
library/cpp/digest/argonish
-)
+)
-SRCS(
- mbench.cpp
-)
+SRCS(
+ mbench.cpp
+)
END()
diff --git a/library/cpp/digest/argonish/internal/blake2b/ya.make b/library/cpp/digest/argonish/internal/blake2b/ya.make
index 9f9a73ee3c..0aa6806b31 100644
--- a/library/cpp/digest/argonish/internal/blake2b/ya.make
+++ b/library/cpp/digest/argonish/internal/blake2b/ya.make
@@ -2,8 +2,8 @@ LIBRARY()
OWNER(e-sidorov)
-PEERDIR(
+PEERDIR(
library/cpp/digest/argonish/internal/rotations
-)
+)
END()
diff --git a/library/cpp/digest/argonish/internal/blamka/ya.make b/library/cpp/digest/argonish/internal/blamka/ya.make
index 9f9a73ee3c..0aa6806b31 100644
--- a/library/cpp/digest/argonish/internal/blamka/ya.make
+++ b/library/cpp/digest/argonish/internal/blamka/ya.make
@@ -2,8 +2,8 @@ LIBRARY()
OWNER(e-sidorov)
-PEERDIR(
+PEERDIR(
library/cpp/digest/argonish/internal/rotations
-)
+)
END()
diff --git a/library/cpp/digest/argonish/ut/ya.make b/library/cpp/digest/argonish/ut/ya.make
index 9889c297de..3440908799 100644
--- a/library/cpp/digest/argonish/ut/ya.make
+++ b/library/cpp/digest/argonish/ut/ya.make
@@ -2,12 +2,12 @@ UNITTEST_FOR(library/cpp/digest/argonish)
OWNER(e-sidorov)
-PEERDIR(
+PEERDIR(
library/cpp/digest/argonish
-)
+)
-SRCS(
- ut.cpp
-)
+SRCS(
+ ut.cpp
+)
END()
diff --git a/library/cpp/digest/argonish/ut_fat/ya.make b/library/cpp/digest/argonish/ut_fat/ya.make
index c2a67352a0..94ebda9225 100644
--- a/library/cpp/digest/argonish/ut_fat/ya.make
+++ b/library/cpp/digest/argonish/ut_fat/ya.make
@@ -2,20 +2,20 @@ UNITTEST_FOR(library/cpp/digest/argonish)
OWNER(e-sidorov)
-PEERDIR(
+PEERDIR(
library/cpp/digest/argonish
-)
+)
SRCS(
ut.cpp
)
-TAG(
- sb:intel_e5_2660v4
- ya:fat
- ya:force_sandbox
-)
-
+TAG(
+ sb:intel_e5_2660v4
+ ya:fat
+ ya:force_sandbox
+)
+
SIZE(LARGE)
END()
diff --git a/library/cpp/digest/lower_case/ut/ya.make b/library/cpp/digest/lower_case/ut/ya.make
index b1fb7a6145..f083257b3d 100644
--- a/library/cpp/digest/lower_case/ut/ya.make
+++ b/library/cpp/digest/lower_case/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/digest/lower_case)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
lchash_ut.cpp
diff --git a/library/cpp/digest/md5/bench/ya.make b/library/cpp/digest/md5/bench/ya.make
index 00099ab126..5c3e3c1c42 100644
--- a/library/cpp/digest/md5/bench/ya.make
+++ b/library/cpp/digest/md5/bench/ya.make
@@ -1,9 +1,9 @@
G_BENCHMARK()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
PEERDIR(
library/cpp/digest/md5
diff --git a/library/cpp/digest/md5/medium_ut/ya.make b/library/cpp/digest/md5/medium_ut/ya.make
index 65fad6b606..418c57f086 100644
--- a/library/cpp/digest/md5/medium_ut/ya.make
+++ b/library/cpp/digest/md5/medium_ut/ya.make
@@ -1,13 +1,13 @@
UNITTEST_FOR(library/cpp/digest/md5)
SIZE(MEDIUM)
-
+
TIMEOUT(120)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
md5_medium_ut.cpp
diff --git a/library/cpp/digest/md5/ut/ya.make b/library/cpp/digest/md5/ut/ya.make
index 32b80ca1c1..ad1eddbff2 100644
--- a/library/cpp/digest/md5/ut/ya.make
+++ b/library/cpp/digest/md5/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/digest/md5)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
md5_ut.cpp
diff --git a/library/cpp/digest/md5/ya.make b/library/cpp/digest/md5/ya.make
index cec46c2aba..c09ec1c326 100644
--- a/library/cpp/digest/md5/ya.make
+++ b/library/cpp/digest/md5/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
md5.cpp
diff --git a/library/cpp/digest/old_crc/crc.cpp b/library/cpp/digest/old_crc/crc.cpp
index 3d3f17142a..994755f34d 100644
--- a/library/cpp/digest/old_crc/crc.cpp
+++ b/library/cpp/digest/old_crc/crc.cpp
@@ -1,7 +1,7 @@
#include "crc.h"
#include <library/cpp/digest/old_crc/crc.inc>
-
+
#include <util/system/defaults.h>
static const ui64 CRCTAB64[256] = {
diff --git a/library/cpp/digest/old_crc/ut/ya.make b/library/cpp/digest/old_crc/ut/ya.make
index 7bc044fb34..a783bbae5b 100644
--- a/library/cpp/digest/old_crc/ut/ya.make
+++ b/library/cpp/digest/old_crc/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/digest/old_crc)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
crc_ut.cpp
diff --git a/library/cpp/digest/old_crc/ya.make b/library/cpp/digest/old_crc/ya.make
index 737390600a..aa6ea8f6c5 100644
--- a/library/cpp/digest/old_crc/ya.make
+++ b/library/cpp/digest/old_crc/ya.make
@@ -1,17 +1,17 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
crc.cpp
)
-RUN_PROGRAM(
+RUN_PROGRAM(
library/cpp/digest/old_crc/gencrc
- STDOUT crc.inc
-)
+ STDOUT crc.inc
+)
END()
diff --git a/library/cpp/digest/sfh/ut/ya.make b/library/cpp/digest/sfh/ut/ya.make
index 09e358e746..256a66295a 100644
--- a/library/cpp/digest/sfh/ut/ya.make
+++ b/library/cpp/digest/sfh/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/digest/sfh)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
sfh_ut.cpp
diff --git a/library/cpp/digest/sfh/ya.make b/library/cpp/digest/sfh/ya.make
index 8b711eed21..b906cd1577 100644
--- a/library/cpp/digest/sfh/ya.make
+++ b/library/cpp/digest/sfh/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
sfh.cpp
diff --git a/library/cpp/histogram/adaptive/protos/python/ya.make b/library/cpp/histogram/adaptive/protos/python/ya.make
index 403d3f56d0..3328c27965 100644
--- a/library/cpp/histogram/adaptive/protos/python/ya.make
+++ b/library/cpp/histogram/adaptive/protos/python/ya.make
@@ -1,3 +1,3 @@
-OWNER(abogutskiy)
+OWNER(abogutskiy)
PY_PROTOS_FOR(library/cpp/histogram/adaptive/protos)
diff --git a/library/cpp/histogram/hdr/ut/ya.make b/library/cpp/histogram/hdr/ut/ya.make
index de6788a95a..13ceb143c8 100644
--- a/library/cpp/histogram/hdr/ut/ya.make
+++ b/library/cpp/histogram/hdr/ut/ya.make
@@ -1,7 +1,7 @@
-OWNER(
- g:util
- jamel
-)
+OWNER(
+ g:util
+ jamel
+)
UNITTEST_FOR(library/cpp/histogram/hdr)
diff --git a/library/cpp/histogram/hdr/ya.make b/library/cpp/histogram/hdr/ya.make
index 81a2efd033..885099608d 100644
--- a/library/cpp/histogram/hdr/ya.make
+++ b/library/cpp/histogram/hdr/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:util
- jamel
-)
+OWNER(
+ g:util
+ jamel
+)
SRCS(
histogram.cpp
diff --git a/library/cpp/html/escape/ut/ya.make b/library/cpp/html/escape/ut/ya.make
index c854d6d1ce..27d3a3d65a 100644
--- a/library/cpp/html/escape/ut/ya.make
+++ b/library/cpp/html/escape/ut/ya.make
@@ -1,5 +1,5 @@
UNITTEST()
-
+
OWNER(stanly)
SRCS(
diff --git a/library/cpp/html/escape/ya.make b/library/cpp/html/escape/ya.make
index b075e7acd4..93a31e33d6 100644
--- a/library/cpp/html/escape/ya.make
+++ b/library/cpp/html/escape/ya.make
@@ -1,5 +1,5 @@
LIBRARY()
-
+
OWNER(stanly)
SRCS(
diff --git a/library/cpp/http/fetch/ya.make b/library/cpp/http/fetch/ya.make
index e0de1e8bc2..7737127463 100644
--- a/library/cpp/http/fetch/ya.make
+++ b/library/cpp/http/fetch/ya.make
@@ -34,5 +34,5 @@ GENERATE_ENUM_SERIALIZATION(httpheader.h)
SET(RAGEL6_FLAGS -CF1)
END()
-
+
RECURSE_FOR_TESTS(ut)
diff --git a/library/cpp/http/io/fuzz/ya.make b/library/cpp/http/io/fuzz/ya.make
index e480f7f2ef..8b3ccb1969 100644
--- a/library/cpp/http/io/fuzz/ya.make
+++ b/library/cpp/http/io/fuzz/ya.make
@@ -1,9 +1,9 @@
FUZZ()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
PEERDIR(
library/cpp/http/io
diff --git a/library/cpp/int128/ya.make b/library/cpp/int128/ya.make
index 2a29f01143..95e453e6f1 100644
--- a/library/cpp/int128/ya.make
+++ b/library/cpp/int128/ya.make
@@ -2,7 +2,7 @@ LIBRARY()
OWNER(
vladon
- # g:zora
+ # g:zora
)
SRCS(
diff --git a/library/cpp/json/fast_sax/ya.make b/library/cpp/json/fast_sax/ya.make
index 2419d1a935..c6447ab6ac 100644
--- a/library/cpp/json/fast_sax/ya.make
+++ b/library/cpp/json/fast_sax/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- velavokr
-)
+OWNER(
+ pg
+ velavokr
+)
PEERDIR(
library/cpp/json/common
diff --git a/library/cpp/json/flex_buffers/ya.make b/library/cpp/json/flex_buffers/ya.make
index fa00f73ca9..3ece5e3703 100644
--- a/library/cpp/json/flex_buffers/ya.make
+++ b/library/cpp/json/flex_buffers/ya.make
@@ -2,7 +2,7 @@ LIBRARY()
OWNER(pg)
-ADDINCL(contrib/libs/flatbuffers/include)
+ADDINCL(contrib/libs/flatbuffers/include)
PEERDIR(
library/cpp/json
diff --git a/library/cpp/json/ut/json_reader_ut.cpp b/library/cpp/json/ut/json_reader_ut.cpp
index 932793d9b5..cd31afa0b8 100644
--- a/library/cpp/json/ut/json_reader_ut.cpp
+++ b/library/cpp/json/ut/json_reader_ut.cpp
@@ -354,24 +354,24 @@ Y_UNIT_TEST_SUITE(TJsonReaderTest) {
UNIT_ASSERT_EQUAL(value["test"].GetDoubleRobust(), static_cast<double>(Max<ui64>()));
} // Max<ui64>()
} // TJsonDoubleTest
-
+
Y_UNIT_TEST(TJsonInvalidTest) {
- {
- // No exceptions mode.
- TStringStream in;
- in << "{ \"test\" : }";
- TJsonValue value;
- UNIT_ASSERT(!ReadJsonTree(&in, &value));
- }
-
- {
- // Exception throwing mode.
- TStringStream in;
- in << "{ \"test\" : }";
- TJsonValue value;
- UNIT_ASSERT_EXCEPTION(ReadJsonTree(&in, &value, true), TJsonException);
- }
- }
+ {
+ // No exceptions mode.
+ TStringStream in;
+ in << "{ \"test\" : }";
+ TJsonValue value;
+ UNIT_ASSERT(!ReadJsonTree(&in, &value));
+ }
+
+ {
+ // Exception throwing mode.
+ TStringStream in;
+ in << "{ \"test\" : }";
+ TJsonValue value;
+ UNIT_ASSERT_EXCEPTION(ReadJsonTree(&in, &value, true), TJsonException);
+ }
+ }
Y_UNIT_TEST(TJsonMemoryLeakTest) {
// after https://clubs.at.yandex-team.ru/stackoverflow/3691
diff --git a/library/cpp/json/writer/ya.make b/library/cpp/json/writer/ya.make
index 47999a85c1..3989ff3504 100644
--- a/library/cpp/json/writer/ya.make
+++ b/library/cpp/json/writer/ya.make
@@ -1,10 +1,10 @@
LIBRARY()
-OWNER(
- mvel
- myltsev
- pg
-)
+OWNER(
+ mvel
+ myltsev
+ pg
+)
PEERDIR(
library/cpp/json/common
diff --git a/library/cpp/json/ya.make b/library/cpp/json/ya.make
index 7add7496b7..d58eead8ec 100644
--- a/library/cpp/json/ya.make
+++ b/library/cpp/json/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- velavokr
-)
+OWNER(
+ pg
+ velavokr
+)
SRCS(
json_writer.cpp
diff --git a/library/cpp/json/yson/ut/ya.make b/library/cpp/json/yson/ut/ya.make
index f372b26558..4ceb65b279 100644
--- a/library/cpp/json/yson/ut/ya.make
+++ b/library/cpp/json/yson/ut/ya.make
@@ -7,7 +7,7 @@ UNITTEST_FOR(library/cpp/json/yson)
ALLOCATOR(LF)
-DATA(sbr://363537653)
+DATA(sbr://363537653)
PEERDIR(
library/cpp/blockcodecs
diff --git a/library/cpp/lfalloc/dbg/ya.make b/library/cpp/lfalloc/dbg/ya.make
index 41817661a1..3dce653a8c 100644
--- a/library/cpp/lfalloc/dbg/ya.make
+++ b/library/cpp/lfalloc/dbg/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-
+
OWNER(vskipin)
NO_UTIL()
-
+
NO_COMPILER_WARNINGS()
IF (ARCH_AARCH64)
@@ -14,10 +14,10 @@ ELSE()
IF ("${YMAKE}" MATCHES "devtools")
CFLAGS(-DYMAKE=1)
ENDIF()
- CXXFLAGS(
- -DLFALLOC_DBG
- -DLFALLOC_YT
- )
+ CXXFLAGS(
+ -DLFALLOC_DBG
+ -DLFALLOC_YT
+ )
SRCS(
../lf_allocX64.cpp
)
diff --git a/library/cpp/lfalloc/dbg_info/ya.make b/library/cpp/lfalloc/dbg_info/ya.make
index 6a87d86955..efecba5993 100644
--- a/library/cpp/lfalloc/dbg_info/ya.make
+++ b/library/cpp/lfalloc/dbg_info/ya.make
@@ -1,5 +1,5 @@
LIBRARY()
-
+
OWNER(vskipin)
PEERDIR(
diff --git a/library/cpp/lfalloc/ya.make b/library/cpp/lfalloc/ya.make
index 932dad551d..cace05f9d8 100644
--- a/library/cpp/lfalloc/ya.make
+++ b/library/cpp/lfalloc/ya.make
@@ -3,7 +3,7 @@ LIBRARY()
OWNER(gulin)
NO_UTIL()
-
+
NO_COMPILER_WARNINGS()
IF (ARCH_AARCH64)
diff --git a/library/cpp/lfalloc/yt/ya.make b/library/cpp/lfalloc/yt/ya.make
index 18bccb90ae..8c1a4f8a72 100644
--- a/library/cpp/lfalloc/yt/ya.make
+++ b/library/cpp/lfalloc/yt/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-
+
OWNER(a-romanov)
NO_UTIL()
-
+
NO_COMPILER_WARNINGS()
IF (ARCH_AARCH64)
diff --git a/library/cpp/linear_regression/benchmark/ya.make b/library/cpp/linear_regression/benchmark/ya.make
index f029ff2348..bbc4f2683a 100644
--- a/library/cpp/linear_regression/benchmark/ya.make
+++ b/library/cpp/linear_regression/benchmark/ya.make
@@ -1,6 +1,6 @@
PROGRAM(linear_regression_benchmark)
-OWNER(alex-sh)
+OWNER(alex-sh)
SRCS(
pool.h
diff --git a/library/cpp/linear_regression/ut/ya.make b/library/cpp/linear_regression/ut/ya.make
index 32bade0995..f410410673 100644
--- a/library/cpp/linear_regression/ut/ya.make
+++ b/library/cpp/linear_regression/ut/ya.make
@@ -1,6 +1,6 @@
UNITTEST()
-OWNER(alex-sh)
+OWNER(alex-sh)
PEERDIR(
ADDINCL library/cpp/linear_regression
diff --git a/library/cpp/linear_regression/ya.make b/library/cpp/linear_regression/ya.make
index 6d152c0dd4..4cfcc3d673 100644
--- a/library/cpp/linear_regression/ya.make
+++ b/library/cpp/linear_regression/ya.make
@@ -1,6 +1,6 @@
LIBRARY()
-OWNER(alex-sh)
+OWNER(alex-sh)
SRCS(
linear_regression.cpp
diff --git a/library/cpp/malloc/ya.make b/library/cpp/malloc/ya.make
index fb846ee3b4..0ec9db71d2 100644
--- a/library/cpp/malloc/ya.make
+++ b/library/cpp/malloc/ya.make
@@ -23,4 +23,4 @@ IF (NOT OS_WINDOWS)
calloc/calloc_profile_scan
calloc/calloc_profile_scan/ut
)
-ENDIF()
+ENDIF()
diff --git a/library/cpp/messagebus/remote_connection_status.cpp b/library/cpp/messagebus/remote_connection_status.cpp
index 920ff802cd..2c48b2a287 100644
--- a/library/cpp/messagebus/remote_connection_status.cpp
+++ b/library/cpp/messagebus/remote_connection_status.cpp
@@ -3,7 +3,7 @@
#include "key_value_printer.h"
#include <library/cpp/messagebus/monitoring/mon_proto.pb.h>
-
+
#include <util/stream/format.h>
#include <util/stream/output.h>
#include <util/system/yassert.h>
diff --git a/library/cpp/messagebus/test/perftest/perftest.cpp b/library/cpp/messagebus/test/perftest/perftest.cpp
index 2b1ff05b3e..8489319278 100644
--- a/library/cpp/messagebus/test/perftest/perftest.cpp
+++ b/library/cpp/messagebus/test/perftest/perftest.cpp
@@ -1,7 +1,7 @@
#include "simple_proto.h"
#include <library/cpp/messagebus/test/perftest/messages.pb.h>
-
+
#include <library/cpp/messagebus/text_utils.h>
#include <library/cpp/messagebus/thread_extra.h>
#include <library/cpp/messagebus/ybus.h>
diff --git a/library/cpp/messagebus/test/ut/ya.make b/library/cpp/messagebus/test/ut/ya.make
index 30dae27f89..fe1b4961d6 100644
--- a/library/cpp/messagebus/test/ut/ya.make
+++ b/library/cpp/messagebus/test/ut/ya.make
@@ -3,14 +3,14 @@ OWNER(g:messagebus)
UNITTEST_FOR(library/cpp/messagebus)
TIMEOUT(1200)
-
+
SIZE(LARGE)
-TAG(
- ya:not_autocheck
- ya:fat
-)
-
+TAG(
+ ya:not_autocheck
+ ya:fat
+)
+
FORK_SUBTESTS()
PEERDIR(
diff --git a/library/cpp/monlib/deprecated/json/ut/ya.make b/library/cpp/monlib/deprecated/json/ut/ya.make
index 36c8baa9d5..18315993b5 100644
--- a/library/cpp/monlib/deprecated/json/ut/ya.make
+++ b/library/cpp/monlib/deprecated/json/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/deprecated/json)
-OWNER(
- jamel
- g:solomon
-)
+OWNER(
+ jamel
+ g:solomon
+)
SRCS(
writer_ut.cpp
diff --git a/library/cpp/monlib/deprecated/json/ya.make b/library/cpp/monlib/deprecated/json/ya.make
index 5a7914d1c2..0ca903ee62 100644
--- a/library/cpp/monlib/deprecated/json/ya.make
+++ b/library/cpp/monlib/deprecated/json/ya.make
@@ -7,10 +7,10 @@ LIBRARY()
# high level library library/cpp/monlib/encode which is decoupled from the
# particular format.
-OWNER(
- jamel
- g:solomon
-)
+OWNER(
+ jamel
+ g:solomon
+)
SRCS(
writer.h
diff --git a/library/cpp/monlib/dynamic_counters/ya.make b/library/cpp/monlib/dynamic_counters/ya.make
index 975dc81781..aafe1c34be 100644
--- a/library/cpp/monlib/dynamic_counters/ya.make
+++ b/library/cpp/monlib/dynamic_counters/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
NO_WSHADOW()
diff --git a/library/cpp/monlib/encode/buffered/ut/ya.make b/library/cpp/monlib/encode/buffered/ut/ya.make
index c81020f5d3..2157ac1490 100644
--- a/library/cpp/monlib/encode/buffered/ut/ya.make
+++ b/library/cpp/monlib/encode/buffered/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/encode/buffered)
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
string_pool_ut.cpp
diff --git a/library/cpp/monlib/encode/buffered/ya.make b/library/cpp/monlib/encode/buffered/ya.make
index 3892cd5455..81b6a78b93 100644
--- a/library/cpp/monlib/encode/buffered/ya.make
+++ b/library/cpp/monlib/encode/buffered/ya.make
@@ -1,10 +1,10 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
- msherbakov
-)
+OWNER(
+ g:solomon
+ jamel
+ msherbakov
+)
SRCS(
buffered_encoder_base.cpp
diff --git a/library/cpp/monlib/encode/fake/ya.make b/library/cpp/monlib/encode/fake/ya.make
index 61ca7b951c..ae96f45782 100644
--- a/library/cpp/monlib/encode/fake/ya.make
+++ b/library/cpp/monlib/encode/fake/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- msherbakov
-)
+OWNER(
+ g:solomon
+ msherbakov
+)
SRCS(
fake.cpp
diff --git a/library/cpp/monlib/encode/json/fuzz/ya.make b/library/cpp/monlib/encode/json/fuzz/ya.make
index 79631841e5..75baa77716 100644
--- a/library/cpp/monlib/encode/json/fuzz/ya.make
+++ b/library/cpp/monlib/encode/json/fuzz/ya.make
@@ -1,9 +1,9 @@
FUZZ()
-OWNER(
- g:solomon
- msherbakov
-)
+OWNER(
+ g:solomon
+ msherbakov
+)
PEERDIR(
library/cpp/monlib/encode/json
@@ -12,8 +12,8 @@ PEERDIR(
SIZE(MEDIUM)
-SRCS(
- main.cpp
-)
+SRCS(
+ main.cpp
+)
END()
diff --git a/library/cpp/monlib/encode/json/ut/ya.make b/library/cpp/monlib/encode/json/ut/ya.make
index 841ae044ba..e50c4f4903 100644
--- a/library/cpp/monlib/encode/json/ut/ya.make
+++ b/library/cpp/monlib/encode/json/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/encode/json)
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
json_decoder_ut.cpp
diff --git a/library/cpp/monlib/encode/json/ya.make b/library/cpp/monlib/encode/json/ya.make
index 7bbeab83bc..a50fc412a9 100644
--- a/library/cpp/monlib/encode/json/ya.make
+++ b/library/cpp/monlib/encode/json/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
json_decoder.cpp
diff --git a/library/cpp/monlib/encode/legacy_protobuf/ut/ya.make b/library/cpp/monlib/encode/legacy_protobuf/ut/ya.make
index f06592f7c6..479a0c46c9 100644
--- a/library/cpp/monlib/encode/legacy_protobuf/ut/ya.make
+++ b/library/cpp/monlib/encode/legacy_protobuf/ut/ya.make
@@ -1,18 +1,18 @@
UNITTEST_FOR(library/cpp/monlib/encode/legacy_protobuf)
-OWNER(
- g:solomon
- msherbakov
-)
+OWNER(
+ g:solomon
+ msherbakov
+)
SRCS(
legacy_protobuf_ut.cpp
test_cases.proto
)
-PEERDIR(
+PEERDIR(
library/cpp/monlib/encode/protobuf
library/cpp/monlib/encode/text
-)
+)
END()
diff --git a/library/cpp/monlib/encode/legacy_protobuf/ya.make b/library/cpp/monlib/encode/legacy_protobuf/ya.make
index ce6253fdd9..74c82aac93 100644
--- a/library/cpp/monlib/encode/legacy_protobuf/ya.make
+++ b/library/cpp/monlib/encode/legacy_protobuf/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- msherbakov
-)
+OWNER(
+ g:solomon
+ msherbakov
+)
SRCS(
legacy_proto_decoder.cpp
diff --git a/library/cpp/monlib/encode/protobuf/protos/ya.make b/library/cpp/monlib/encode/protobuf/protos/ya.make
index 724cf3168b..88ff3ddf88 100644
--- a/library/cpp/monlib/encode/protobuf/protos/ya.make
+++ b/library/cpp/monlib/encode/protobuf/protos/ya.make
@@ -1,9 +1,9 @@
PROTO_LIBRARY()
-OWNER(
- jamel
- g:solomon
-)
+OWNER(
+ jamel
+ g:solomon
+)
SRCS(
samples.proto
diff --git a/library/cpp/monlib/encode/protobuf/ya.make b/library/cpp/monlib/encode/protobuf/ya.make
index 0cdab38a6a..9354958b6f 100644
--- a/library/cpp/monlib/encode/protobuf/ya.make
+++ b/library/cpp/monlib/encode/protobuf/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- jamel
- g:solomon
-)
+OWNER(
+ jamel
+ g:solomon
+)
SRCS(
protobuf_encoder.cpp
diff --git a/library/cpp/monlib/encode/spack/fuzz/ya.make b/library/cpp/monlib/encode/spack/fuzz/ya.make
index f94adf967c..99b63eadd5 100644
--- a/library/cpp/monlib/encode/spack/fuzz/ya.make
+++ b/library/cpp/monlib/encode/spack/fuzz/ya.make
@@ -1,12 +1,12 @@
FUZZ()
-OWNER(
- g:solomon
- msherbakov
+OWNER(
+ g:solomon
+ msherbakov
)
-FUZZ_OPTS(-rss_limit_mb=1024)
-
+FUZZ_OPTS(-rss_limit_mb=1024)
+
SIZE(MEDIUM)
PEERDIR(
@@ -14,8 +14,8 @@ PEERDIR(
library/cpp/monlib/encode/fake
)
-SRCS(
- main.cpp
-)
+SRCS(
+ main.cpp
+)
END()
diff --git a/library/cpp/monlib/encode/spack/ut/ya.make b/library/cpp/monlib/encode/spack/ut/ya.make
index ab09999c2d..980bf54667 100644
--- a/library/cpp/monlib/encode/spack/ut/ya.make
+++ b/library/cpp/monlib/encode/spack/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/encode/spack)
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
spack_v1_ut.cpp
diff --git a/library/cpp/monlib/encode/spack/ya.make b/library/cpp/monlib/encode/spack/ya.make
index 2de5771477..78d3061291 100644
--- a/library/cpp/monlib/encode/spack/ya.make
+++ b/library/cpp/monlib/encode/spack/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
spack_v1_decoder.cpp
diff --git a/library/cpp/monlib/encode/text/ut/ya.make b/library/cpp/monlib/encode/text/ut/ya.make
index 49124cf977..df23a252d1 100644
--- a/library/cpp/monlib/encode/text/ut/ya.make
+++ b/library/cpp/monlib/encode/text/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/encode/text)
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
text_encoder_ut.cpp
diff --git a/library/cpp/monlib/encode/text/ya.make b/library/cpp/monlib/encode/text/ya.make
index c0a51d4126..d296c78c1b 100644
--- a/library/cpp/monlib/encode/text/ya.make
+++ b/library/cpp/monlib/encode/text/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
text_encoder.cpp
diff --git a/library/cpp/monlib/encode/ut/ya.make b/library/cpp/monlib/encode/ut/ya.make
index 57c474e9ac..1990386d76 100644
--- a/library/cpp/monlib/encode/ut/ya.make
+++ b/library/cpp/monlib/encode/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/encode)
-OWNER(
- jamel
- g:solomon
-)
+OWNER(
+ jamel
+ g:solomon
+)
SRCS(
format_ut.cpp
diff --git a/library/cpp/monlib/encode/ya.make b/library/cpp/monlib/encode/ya.make
index 0eecb4feb3..d1bb09f07b 100644
--- a/library/cpp/monlib/encode/ya.make
+++ b/library/cpp/monlib/encode/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
SRCS(
encoder.cpp
diff --git a/library/cpp/monlib/metrics/ut/ya.make b/library/cpp/monlib/metrics/ut/ya.make
index 267e6a3bdf..aec9974fbd 100644
--- a/library/cpp/monlib/metrics/ut/ya.make
+++ b/library/cpp/monlib/metrics/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/monlib/metrics)
-OWNER(
- jamel
- g:solomon
-)
+OWNER(
+ jamel
+ g:solomon
+)
SRCS(
ewma_ut.cpp
diff --git a/library/cpp/monlib/metrics/ya.make b/library/cpp/monlib/metrics/ya.make
index d2c51ec443..0e1fa143f9 100644
--- a/library/cpp/monlib/metrics/ya.make
+++ b/library/cpp/monlib/metrics/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
GENERATE_ENUM_SERIALIZATION_WITH_HEADER(metric_value_type.h)
diff --git a/library/cpp/monlib/ya.make b/library/cpp/monlib/ya.make
index fc6b4bcef2..9bd236d6fd 100644
--- a/library/cpp/monlib/ya.make
+++ b/library/cpp/monlib/ya.make
@@ -1,7 +1,7 @@
-OWNER(
- g:solomon
- jamel
-)
+OWNER(
+ g:solomon
+ jamel
+)
RECURSE(
consumers
diff --git a/library/cpp/openssl/io/ut/ya.make b/library/cpp/openssl/io/ut/ya.make
index de5fedcb05..b978a6c046 100644
--- a/library/cpp/openssl/io/ut/ya.make
+++ b/library/cpp/openssl/io/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/openssl/io)
-OWNER(
- pg
- cerevra
-)
+OWNER(
+ pg
+ cerevra
+)
SRCS(
builtin_ut.cpp
diff --git a/library/cpp/protobuf/json/ut/inline_ut.cpp b/library/cpp/protobuf/json/ut/inline_ut.cpp
index 3a867c35b4..c29ad32e7d 100644
--- a/library/cpp/protobuf/json/ut/inline_ut.cpp
+++ b/library/cpp/protobuf/json/ut/inline_ut.cpp
@@ -1,5 +1,5 @@
#include <library/cpp/protobuf/json/ut/inline_ut.pb.h>
-
+
#include <library/cpp/protobuf/json/inline.h>
#include <library/cpp/protobuf/json/field_option.h>
#include <library/cpp/protobuf/json/proto2json.h>
diff --git a/library/cpp/protobuf/json/ut/json2proto_ut.cpp b/library/cpp/protobuf/json/ut/json2proto_ut.cpp
index b5c7409487..0dfe57bc7a 100644
--- a/library/cpp/protobuf/json/ut/json2proto_ut.cpp
+++ b/library/cpp/protobuf/json/ut/json2proto_ut.cpp
@@ -3,7 +3,7 @@
#include "proto2json.h"
#include <library/cpp/protobuf/json/ut/test.pb.h>
-
+
#include <library/cpp/json/json_value.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_writer.h>
diff --git a/library/cpp/protobuf/json/ut/proto2json_ut.cpp b/library/cpp/protobuf/json/ut/proto2json_ut.cpp
index 04ee4389ee..07e52d7f2f 100644
--- a/library/cpp/protobuf/json/ut/proto2json_ut.cpp
+++ b/library/cpp/protobuf/json/ut/proto2json_ut.cpp
@@ -2,7 +2,7 @@
#include "proto.h"
#include <library/cpp/protobuf/json/ut/test.pb.h>
-
+
#include <library/cpp/json/json_value.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_writer.h>
diff --git a/library/cpp/protobuf/json/ut/ya.make b/library/cpp/protobuf/json/ut/ya.make
index 649f4c56a5..b60a6d3c17 100644
--- a/library/cpp/protobuf/json/ut/ya.make
+++ b/library/cpp/protobuf/json/ut/ya.make
@@ -16,8 +16,8 @@ SRCS(
GENERATE_ENUM_SERIALIZATION(test.pb.h)
-PEERDIR(
+PEERDIR(
library/cpp/protobuf/json
-)
+)
END()
diff --git a/library/cpp/random_provider/ya.make b/library/cpp/random_provider/ya.make
index 2104e81b6e..38d1f070e8 100644
--- a/library/cpp/random_provider/ya.make
+++ b/library/cpp/random_provider/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:kikimr
- g:yql
-)
+OWNER(
+ g:kikimr
+ g:yql
+)
SRCS(
random_provider.cpp
diff --git a/library/cpp/regex/hyperscan/ut/ya.make b/library/cpp/regex/hyperscan/ut/ya.make
index cf0378f4b3..da67b88672 100644
--- a/library/cpp/regex/hyperscan/ut/ya.make
+++ b/library/cpp/regex/hyperscan/ut/ya.make
@@ -4,7 +4,7 @@ PEERDIR(
library/cpp/regex/hyperscan
)
-OWNER(g:antiinfra)
+OWNER(g:antiinfra)
SRCS(
hyperscan_ut.cpp
diff --git a/library/cpp/regex/hyperscan/ya.make b/library/cpp/regex/hyperscan/ya.make
index cf14c98ea3..e99130ae18 100644
--- a/library/cpp/regex/hyperscan/ya.make
+++ b/library/cpp/regex/hyperscan/ya.make
@@ -1,6 +1,6 @@
LIBRARY()
-OWNER(g:antiinfra)
+OWNER(g:antiinfra)
PEERDIR(
contrib/libs/hyperscan
diff --git a/library/cpp/regex/pire/inline/ya.make b/library/cpp/regex/pire/inline/ya.make
index a922cca871..d4850f7b45 100644
--- a/library/cpp/regex/pire/inline/ya.make
+++ b/library/cpp/regex/pire/inline/ya.make
@@ -2,18 +2,18 @@ PROGRAM(pire_inline)
CFLAGS(-DPIRE_NO_CONFIG)
-OWNER(
- g:util
- davenger
-)
+OWNER(
+ g:util
+ davenger
+)
PEERDIR(
ADDINCL library/cpp/regex/pire
)
-SRCDIR(
- contrib/libs/pire/pire
-)
+SRCDIR(
+ contrib/libs/pire/pire
+)
SRCS(
inline.l
diff --git a/library/cpp/regex/pire/ut/ya.make b/library/cpp/regex/pire/ut/ya.make
index 97adb509b4..8776695f40 100644
--- a/library/cpp/regex/pire/ut/ya.make
+++ b/library/cpp/regex/pire/ut/ya.make
@@ -2,10 +2,10 @@
UNITTEST()
-OWNER(
- g:util
- davenger
-)
+OWNER(
+ g:util
+ davenger
+)
SET(PIRETESTSDIR contrib/libs/pire/ut)
diff --git a/library/cpp/regex/pire/ya.make b/library/cpp/regex/pire/ya.make
index c36fef6454..c857e6d18b 100644
--- a/library/cpp/regex/pire/ya.make
+++ b/library/cpp/regex/pire/ya.make
@@ -1,15 +1,15 @@
LIBRARY()
-OWNER(
- g:util
- g:antiinfra
- davenger
- pg
-)
+OWNER(
+ g:util
+ g:antiinfra
+ davenger
+ pg
+)
CFLAGS(-DPIRE_NO_CONFIG)
-SRCDIR(contrib/libs/pire/pire)
+SRCDIR(contrib/libs/pire/pire)
SRCS(
pcre2pire.cpp
diff --git a/library/cpp/retry/ut/ya.make b/library/cpp/retry/ut/ya.make
index ec46544bc6..ff8259bfdb 100644
--- a/library/cpp/retry/ut/ya.make
+++ b/library/cpp/retry/ut/ya.make
@@ -1,10 +1,10 @@
UNITTEST_FOR(library/cpp/retry)
-OWNER(
- salmin
- osado
- g:yabs-small
-)
+OWNER(
+ salmin
+ osado
+ g:yabs-small
+)
SRCS(
retry_ut.cpp
diff --git a/library/cpp/retry/ya.make b/library/cpp/retry/ya.make
index 66906ca5e8..31e0c6a259 100644
--- a/library/cpp/retry/ya.make
+++ b/library/cpp/retry/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- osado
- g:yabs-small
-)
+OWNER(
+ osado
+ g:yabs-small
+)
SRCS(
retry.cpp
diff --git a/library/cpp/scheme/ya.make b/library/cpp/scheme/ya.make
index e23eb90c5e..bac08ba5a4 100644
--- a/library/cpp/scheme/ya.make
+++ b/library/cpp/scheme/ya.make
@@ -20,6 +20,6 @@ PEERDIR(
library/cpp/string_utils/relaxed_escaper
)
-GENERATE_ENUM_SERIALIZATION(scheme.h)
+GENERATE_ENUM_SERIALIZATION(scheme.h)
END()
diff --git a/library/cpp/streams/brotli/ut/ya.make b/library/cpp/streams/brotli/ut/ya.make
index d78b53a86f..243462f1b2 100644
--- a/library/cpp/streams/brotli/ut/ya.make
+++ b/library/cpp/streams/brotli/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/streams/brotli)
-OWNER(
- levysotsky
- g:util
-)
+OWNER(
+ levysotsky
+ g:util
+)
SRCS(
brotli_ut.cpp
diff --git a/library/cpp/streams/brotli/ya.make b/library/cpp/streams/brotli/ya.make
index ac0c06b544..fa2bfec9cc 100644
--- a/library/cpp/streams/brotli/ya.make
+++ b/library/cpp/streams/brotli/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- levysotsky
- g:util
-)
+OWNER(
+ levysotsky
+ g:util
+)
PEERDIR(
contrib/libs/brotli/enc
diff --git a/library/cpp/streams/bzip2/ut/ya.make b/library/cpp/streams/bzip2/ut/ya.make
index 15643501f5..5ef91498ca 100644
--- a/library/cpp/streams/bzip2/ut/ya.make
+++ b/library/cpp/streams/bzip2/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/streams/bzip2)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
bzip2_ut.cpp
diff --git a/library/cpp/streams/bzip2/ya.make b/library/cpp/streams/bzip2/ya.make
index 9e140d618b..122a35837c 100644
--- a/library/cpp/streams/bzip2/ya.make
+++ b/library/cpp/streams/bzip2/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
PEERDIR(
contrib/libs/libbz2
diff --git a/library/cpp/streams/lz/ut/ya.make b/library/cpp/streams/lz/ut/ya.make
index 1fdb6708af..18288c8ac9 100644
--- a/library/cpp/streams/lz/ut/ya.make
+++ b/library/cpp/streams/lz/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/streams/lz)
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
RESOURCE(
random.data /random.data
diff --git a/library/cpp/streams/lz/ya.make b/library/cpp/streams/lz/ya.make
index f178a45385..e5eea0b096 100644
--- a/library/cpp/streams/lz/ya.make
+++ b/library/cpp/streams/lz/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
PEERDIR(
contrib/libs/fastlz
diff --git a/library/cpp/streams/zc_memory_input/ya.make b/library/cpp/streams/zc_memory_input/ya.make
index 2e4138acc4..bc94d6f1ed 100644
--- a/library/cpp/streams/zc_memory_input/ya.make
+++ b/library/cpp/streams/zc_memory_input/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SRCS(
zc_memory_input.cpp
diff --git a/library/cpp/string_utils/base64/bench/metrics/ya.make b/library/cpp/string_utils/base64/bench/metrics/ya.make
index 579ca453ac..b0406516c3 100644
--- a/library/cpp/string_utils/base64/bench/metrics/ya.make
+++ b/library/cpp/string_utils/base64/bench/metrics/ya.make
@@ -13,7 +13,7 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
DEPENDS(library/cpp/string_utils/base64/bench)
diff --git a/library/cpp/string_utils/levenshtein_diff/ut/ya.make b/library/cpp/string_utils/levenshtein_diff/ut/ya.make
index f4cd2d8319..a3b9b8fea5 100644
--- a/library/cpp/string_utils/levenshtein_diff/ut/ya.make
+++ b/library/cpp/string_utils/levenshtein_diff/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/string_utils/levenshtein_diff)
-
+
OWNER(myltsev)
-SRCS(
+SRCS(
levenshtein_diff_ut.cpp
-)
+)
END()
diff --git a/library/cpp/testing/benchmark/examples/metrics/ya.make b/library/cpp/testing/benchmark/examples/metrics/ya.make
index 3d59b660b0..a9dbdca9fa 100644
--- a/library/cpp/testing/benchmark/examples/metrics/ya.make
+++ b/library/cpp/testing/benchmark/examples/metrics/ya.make
@@ -13,7 +13,7 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
DEPENDS(library/cpp/testing/benchmark/examples)
diff --git a/library/cpp/testing/benchmark/main/ya.make b/library/cpp/testing/benchmark/main/ya.make
index 0cf231bee2..d00cdcf9fc 100644
--- a/library/cpp/testing/benchmark/main/ya.make
+++ b/library/cpp/testing/benchmark/main/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- yazevnul
-)
+OWNER(
+ pg
+ yazevnul
+)
SRCS(
GLOBAL main.cpp
diff --git a/library/cpp/testing/benchmark/ya.make b/library/cpp/testing/benchmark/ya.make
index 16bc28837d..f42be80698 100644
--- a/library/cpp/testing/benchmark/ya.make
+++ b/library/cpp/testing/benchmark/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- yazevnul
-)
+OWNER(
+ pg
+ yazevnul
+)
SRCS(
bench.cpp
diff --git a/library/cpp/testing/unittest/fat/ya.make b/library/cpp/testing/unittest/fat/ya.make
index 10846454de..d405e599ee 100644
--- a/library/cpp/testing/unittest/fat/ya.make
+++ b/library/cpp/testing/unittest/fat/ya.make
@@ -11,9 +11,9 @@ SIZE(LARGE)
# We need to run tests at the same time on the single machine
FORK_SUBTESTS()
-TAG(
- ya:fat
- ya:force_sandbox
-)
-
+TAG(
+ ya:fat
+ ya:force_sandbox
+)
+
END()
diff --git a/library/cpp/threading/future/perf/ya.make b/library/cpp/threading/future/perf/ya.make
index a3cfbfb0c7..943d585d4b 100644
--- a/library/cpp/threading/future/perf/ya.make
+++ b/library/cpp/threading/future/perf/ya.make
@@ -1,9 +1,9 @@
Y_BENCHMARK(library-threading-future-perf)
-OWNER(
- g:rtmr
- ishfb
-)
+OWNER(
+ g:rtmr
+ ishfb
+)
SRCS(
main.cpp
diff --git a/library/cpp/threading/future/ut/ya.make b/library/cpp/threading/future/ut/ya.make
index 9de072c5cf..566b622370 100644
--- a/library/cpp/threading/future/ut/ya.make
+++ b/library/cpp/threading/future/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/threading/future)
-OWNER(
- g:rtmr
- ishfb
-)
+OWNER(
+ g:rtmr
+ ishfb
+)
SRCS(
async_ut.cpp
diff --git a/library/cpp/threading/light_rw_lock/ut/ya.make b/library/cpp/threading/light_rw_lock/ut/ya.make
index a75dd6d5eb..92928b837c 100644
--- a/library/cpp/threading/light_rw_lock/ut/ya.make
+++ b/library/cpp/threading/light_rw_lock/ut/ya.make
@@ -1,6 +1,6 @@
UNITTEST_FOR(library/cpp/threading/light_rw_lock)
-OWNER(agri)
+OWNER(agri)
SRCS(
rwlock_ut.cpp
diff --git a/library/cpp/threading/poor_man_openmp/ut/ya.make b/library/cpp/threading/poor_man_openmp/ut/ya.make
index 57f21db4f0..6d7aa123ed 100644
--- a/library/cpp/threading/poor_man_openmp/ut/ya.make
+++ b/library/cpp/threading/poor_man_openmp/ut/ya.make
@@ -1,9 +1,9 @@
UNITTEST_FOR(library/cpp/threading/poor_man_openmp)
-OWNER(
- pg
- agorodilov
-)
+OWNER(
+ pg
+ agorodilov
+)
SRCS(
thread_helper_ut.cpp
diff --git a/library/cpp/threading/queue/ut/ya.make b/library/cpp/threading/queue/ut/ya.make
index 1798215c5a..8883d9bf69 100644
--- a/library/cpp/threading/queue/ut/ya.make
+++ b/library/cpp/threading/queue/ut/ya.make
@@ -1,6 +1,6 @@
UNITTEST_FOR(library/cpp/threading/queue)
-OWNER(agri)
+OWNER(agri)
ALLOCATOR(B)
diff --git a/library/cpp/time_provider/ya.make b/library/cpp/time_provider/ya.make
index 1e59682bb1..cf3995b2a4 100644
--- a/library/cpp/time_provider/ya.make
+++ b/library/cpp/time_provider/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- g:kikimr
- g:yql
-)
+OWNER(
+ g:kikimr
+ g:yql
+)
SRCS(
time_provider.cpp
diff --git a/library/cpp/timezone_conversion/ya.make b/library/cpp/timezone_conversion/ya.make
index 8de5ed17a9..f99ebe73ee 100644
--- a/library/cpp/timezone_conversion/ya.make
+++ b/library/cpp/timezone_conversion/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- dfyz
- petrk
-)
+OWNER(
+ dfyz
+ petrk
+)
PEERDIR(
contrib/libs/cctz/tzdata
diff --git a/library/cpp/tld/ya.make b/library/cpp/tld/ya.make
index 7b36e6b0eb..aeabbfeebf 100644
--- a/library/cpp/tld/ya.make
+++ b/library/cpp/tld/ya.make
@@ -3,10 +3,10 @@ LIBRARY()
OWNER(abolkhovityanov)
PYTHON(
- gen_tld.py tlds-alpha-by-domain.txt
- IN tlds-alpha-by-domain.txt
- STDOUT tld.inc
-)
+ gen_tld.py tlds-alpha-by-domain.txt
+ IN tlds-alpha-by-domain.txt
+ STDOUT tld.inc
+)
SRCS(
tld.cpp
diff --git a/library/cpp/tvmauth/src/rw/ut_large/ya.make b/library/cpp/tvmauth/src/rw/ut_large/ya.make
index f33e33a786..54f82065e7 100644
--- a/library/cpp/tvmauth/src/rw/ut_large/ya.make
+++ b/library/cpp/tvmauth/src/rw/ut_large/ya.make
@@ -2,16 +2,16 @@ PY2TEST()
OWNER(g:passport_infra)
-TEST_SRCS(test.py)
+TEST_SRCS(test.py)
DEPENDS(library/cpp/tvmauth/src/rw/ut_large/gen)
TAG(ya:fat)
-
+
SIZE(LARGE)
END()
-RECURSE(
- gen
-)
+RECURSE(
+ gen
+)
diff --git a/library/cpp/unicode/normalization/generated/decomposition.cpp b/library/cpp/unicode/normalization/generated/decomposition.cpp
index 2d6cf6583b..9ac6a5f92a 100644
--- a/library/cpp/unicode/normalization/generated/decomposition.cpp
+++ b/library/cpp/unicode/normalization/generated/decomposition.cpp
@@ -42207,7 +42207,7 @@ namespace { namespace NCannonDecompositionTableGenerated {
}, // P[475]
}; // static const NUnicode::NPrivate::TDecompositionTable::TValuePtr P[][32]
- static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[] = {
+ static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[] = {
P[0], P[0], P[0], P[0], P[0], P[0], P[1], P[2], P[3], P[4], P[5], P[6], P[0], P[7], P[8], P[9],
P[10], P[11], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[12], P[13], P[14], P[15], P[16], P[0],
P[17], P[18], P[19], P[20], P[0], P[0], P[21], P[22], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0],
@@ -42590,7 +42590,7 @@ namespace { namespace NCannonDecompositionTableGenerated {
P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0],
P[459], P[460], P[461], P[462], P[463], P[464], P[465], P[466], P[467], P[468], P[469], P[470], P[471], P[472], P[473], P[474],
P[475],
- }; // static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[]
+ }; // static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[]
static const size_t Size = 195102;
}} // namespace NCannonDecompositionTableGenerated
@@ -90733,7 +90733,7 @@ namespace { namespace NCompatDecompositionTableGenerated {
}, // P[623]
}; // static const NUnicode::NPrivate::TDecompositionTable::TValuePtr P[][32]
- static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[] = {
+ static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[] = {
P[0], P[0], P[0], P[0], P[0], P[1], P[2], P[3], P[4], P[5], P[6], P[7], P[0], P[8], P[9], P[10],
P[11], P[12], P[0], P[0], P[0], P[13], P[14], P[15], P[0], P[0], P[16], P[17], P[18], P[19], P[20], P[21],
P[22], P[23], P[24], P[25], P[0], P[0], P[26], P[27], P[0], P[0], P[0], P[0], P[28], P[0], P[0], P[0],
@@ -91116,7 +91116,7 @@ namespace { namespace NCompatDecompositionTableGenerated {
P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0], P[0],
P[607], P[608], P[609], P[610], P[611], P[612], P[613], P[614], P[615], P[616], P[617], P[618], P[619], P[620], P[621], P[622],
P[623],
- }; // static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[]
+ }; // static const NUnicode::NPrivate::TDecompositionTable::TValuePtr* const Indexes[]
static const size_t Size = 195102;
}} // namespace NCompatDecompositionTableGenerated
diff --git a/library/cpp/unicode/ya.make b/library/cpp/unicode/ya.make
index 048d69b297..4fcd9caacc 100644
--- a/library/cpp/unicode/ya.make
+++ b/library/cpp/unicode/ya.make
@@ -5,8 +5,8 @@ RECURSE(
normalization/ut
punycode
punycode/ut
- set
- set/ut
+ set
+ set/ut
utf8_char
utf8_char/ut
utf8_iter
diff --git a/library/cpp/uri/ut/ya.make b/library/cpp/uri/ut/ya.make
index af67f59197..b2b2c1291a 100644
--- a/library/cpp/uri/ut/ya.make
+++ b/library/cpp/uri/ut/ya.make
@@ -3,7 +3,7 @@ UNITTEST_FOR(library/cpp/uri)
OWNER(leo)
NO_OPTIMIZE()
-
+
NO_WSHADOW()
PEERDIR(
diff --git a/library/cpp/yson_pull/ya.make b/library/cpp/yson_pull/ya.make
index 7a384eed29..a373e0a6ba 100644
--- a/library/cpp/yson_pull/ya.make
+++ b/library/cpp/yson_pull/ya.make
@@ -15,7 +15,7 @@ SRCS(
)
GENERATE_ENUM_SERIALIZATION(event.h)
-
+
GENERATE_ENUM_SERIALIZATION(scalar.h)
END()
diff --git a/library/python/cores/ya.make b/library/python/cores/ya.make
index 58463feb7e..76264e9cce 100644
--- a/library/python/cores/ya.make
+++ b/library/python/cores/ya.make
@@ -5,7 +5,7 @@ OWNER(
PY23_LIBRARY()
-PY_SRCS(__init__.py)
+PY_SRCS(__init__.py)
PEERDIR(
contrib/python/six
diff --git a/library/python/filelock/__init__.py b/library/python/filelock/__init__.py
index cdf2ee4f68..f81ff67f37 100644
--- a/library/python/filelock/__init__.py
+++ b/library/python/filelock/__init__.py
@@ -1,12 +1,12 @@
-import errno
-import logging
-import os
+import errno
+import logging
+import os
import sys
import library.python.windows
logger = logging.getLogger(__name__)
-
+
def set_close_on_exec(stream):
if library.python.windows.on_win():
@@ -74,19 +74,19 @@ class _WinFileLock(AbstractFileLock):
def __init__(self, path):
super(_WinFileLock, self).__init__(path)
self._lock = None
- try:
- with file(path, 'w') as lock_file:
- lock_file.write(" " * self._LOCKED_BYTES_NUM)
- except IOError as e:
- if e.errno != errno.EACCES or not os.path.isfile(path):
- raise
+ try:
+ with file(path, 'w') as lock_file:
+ lock_file.write(" " * self._LOCKED_BYTES_NUM)
+ except IOError as e:
+ if e.errno != errno.EACCES or not os.path.isfile(path):
+ raise
def acquire(self, blocking=True):
self._lock = open(self.path)
set_close_on_exec(self._lock)
import time
- locked = False
+ locked = False
while not locked:
locked = library.python.windows.lock_file(self._lock, 0, self._LOCKED_BYTES_NUM, raises=False)
if locked:
@@ -97,7 +97,7 @@ class _WinFileLock(AbstractFileLock):
return False
def release(self):
- if self._lock:
+ if self._lock:
library.python.windows.unlock_file(self._lock, 0, self._LOCKED_BYTES_NUM, raises=False)
self._lock.close()
self._lock = None
diff --git a/library/python/filelock/ut/lib/test_filelock.py b/library/python/filelock/ut/lib/test_filelock.py
index 5c2e0181ff..1b11d89123 100644
--- a/library/python/filelock/ut/lib/test_filelock.py
+++ b/library/python/filelock/ut/lib/test_filelock.py
@@ -8,13 +8,13 @@ import threading
import library.python.filelock
-def _acquire_lock(lock_path, out_file_path):
+def _acquire_lock(lock_path, out_file_path):
with library.python.filelock.FileLock(lock_path):
- with open(out_file_path, "a") as out:
- out.write("{}:{}\n".format(os.getpid(), time.time()))
- time.sleep(2)
-
-
+ with open(out_file_path, "a") as out:
+ out.write("{}:{}\n".format(os.getpid(), time.time()))
+ time.sleep(2)
+
+
def test_filelock():
temp_dir = tempfile.mkdtemp()
lock_path = os.path.join(temp_dir, "file.lock")
@@ -46,12 +46,12 @@ def test_filelock():
time2 = times.pop()
assert int(time1) - int(time2) >= 2
time1 = time2
-
-
+
+
def test_filelock_init_acquired():
temp_dir = tempfile.mkdtemp()
lock_path = os.path.join(temp_dir, "file.lock")
-
+
with library.python.filelock.FileLock(lock_path):
sublock = library.python.filelock.FileLock(lock_path)
del sublock
diff --git a/library/python/filelock/ut/lib/ya.make b/library/python/filelock/ut/lib/ya.make
index 291f8a32ba..f3f9da5a67 100644
--- a/library/python/filelock/ut/lib/ya.make
+++ b/library/python/filelock/ut/lib/ya.make
@@ -2,7 +2,7 @@ OWNER(g:yatool)
PY23_LIBRARY()
-TEST_SRCS(test_filelock.py)
+TEST_SRCS(test_filelock.py)
PEERDIR(
library/python/filelock
diff --git a/library/python/filelock/ya.make b/library/python/filelock/ya.make
index d67540b8f7..958cc1866f 100644
--- a/library/python/filelock/ya.make
+++ b/library/python/filelock/ya.make
@@ -4,8 +4,8 @@ PY23_LIBRARY()
PY_SRCS(__init__.py)
-PEERDIR(
- library/python/windows
-)
+PEERDIR(
+ library/python/windows
+)
END()
diff --git a/library/python/find_root/ya.make b/library/python/find_root/ya.make
index 1f22e4a5f8..beaa8e3c52 100644
--- a/library/python/find_root/ya.make
+++ b/library/python/find_root/ya.make
@@ -2,6 +2,6 @@ PY23_LIBRARY()
OWNER(g:yatool)
-PY_SRCS(__init__.py)
+PY_SRCS(__init__.py)
END()
diff --git a/library/python/fs/__init__.py b/library/python/fs/__init__.py
index 2bc368f43f..b1b7cde079 100644
--- a/library/python/fs/__init__.py
+++ b/library/python/fs/__init__.py
@@ -1,13 +1,13 @@
# coding: utf-8
-import codecs
+import codecs
import errno
import logging
import os
import random
import shutil
import six
-import stat
+import stat
import sys
import library.python.func
@@ -23,179 +23,179 @@ except NameError:
WindowsError = None
-_diehard_win_tries = 10
+_diehard_win_tries = 10
errorfix_win = library.python.windows.errorfix
-
-
-class CustomFsError(OSError):
- def __init__(self, errno, message='', filename=None):
- super(CustomFsError, self).__init__(message)
- self.errno = errno
- self.strerror = os.strerror(errno)
- self.filename = filename
-
-
-# Directories creation
-# If dst is already exists and is a directory - does nothing
-# Throws OSError
-@errorfix_win
-def ensure_dir(path):
+
+
+class CustomFsError(OSError):
+ def __init__(self, errno, message='', filename=None):
+ super(CustomFsError, self).__init__(message)
+ self.errno = errno
+ self.strerror = os.strerror(errno)
+ self.filename = filename
+
+
+# Directories creation
+# If dst is already exists and is a directory - does nothing
+# Throws OSError
+@errorfix_win
+def ensure_dir(path):
try:
os.makedirs(path)
except OSError as e:
- if e.errno != errno.EEXIST or not os.path.isdir(path):
+ if e.errno != errno.EEXIST or not os.path.isdir(path):
raise
-
-# Directories creation
-# If dst is already exists and is a directory - does nothing
-# Returns path
-# Throws OSError
-@errorfix_win
-def create_dirs(path):
- ensure_dir(path)
+
+# Directories creation
+# If dst is already exists and is a directory - does nothing
+# Returns path
+# Throws OSError
+@errorfix_win
+def create_dirs(path):
+ ensure_dir(path)
return path
-# Atomic file/directory move (rename)
-# Doesn't guarantee dst replacement
-# Atomic if no device boundaries are crossed
-# Depends on ctypes on Windows
-# Throws OSError
-# On Unix, if dst exists:
-# if dst is file or empty dir - replaces it
-# if src is dir and dst is not dir - throws OSError (errno ENOTDIR)
-# if src is dir and dst is non-empty dir - throws OSError (errno ENOTEMPTY)
-# if src is file and dst is dir - throws OSError (errno EISDIR)
-# On Windows, if dst exists - throws OSError (errno EEXIST)
-@errorfix_win
+# Atomic file/directory move (rename)
+# Doesn't guarantee dst replacement
+# Atomic if no device boundaries are crossed
+# Depends on ctypes on Windows
+# Throws OSError
+# On Unix, if dst exists:
+# if dst is file or empty dir - replaces it
+# if src is dir and dst is not dir - throws OSError (errno ENOTDIR)
+# if src is dir and dst is non-empty dir - throws OSError (errno ENOTEMPTY)
+# if src is file and dst is dir - throws OSError (errno EISDIR)
+# On Windows, if dst exists - throws OSError (errno EEXIST)
+@errorfix_win
@library.python.windows.diehard(library.python.windows.RETRIABLE_FILE_ERRORS, tries=_diehard_win_tries)
-def move(src, dst):
- os.rename(src, dst)
-
-
-# Atomic replacing file move (rename)
-# Replaces dst if exists and not a dir
-# Doesn't guarantee dst dir replacement
-# Atomic if no device boundaries are crossed
-# Depends on ctypes on Windows
-# Throws OSError
-# On Unix, if dst exists:
-# if dst is file - replaces it
-# if dst is dir - throws OSError (errno EISDIR)
-# On Windows, if dst exists:
-# if dst is file - replaces it
-# if dst is dir - throws OSError (errno EACCES)
-@errorfix_win
+def move(src, dst):
+ os.rename(src, dst)
+
+
+# Atomic replacing file move (rename)
+# Replaces dst if exists and not a dir
+# Doesn't guarantee dst dir replacement
+# Atomic if no device boundaries are crossed
+# Depends on ctypes on Windows
+# Throws OSError
+# On Unix, if dst exists:
+# if dst is file - replaces it
+# if dst is dir - throws OSError (errno EISDIR)
+# On Windows, if dst exists:
+# if dst is file - replaces it
+# if dst is dir - throws OSError (errno EACCES)
+@errorfix_win
@library.python.windows.diehard(library.python.windows.RETRIABLE_FILE_ERRORS, tries=_diehard_win_tries)
-def replace_file(src, dst):
+def replace_file(src, dst):
if library.python.windows.on_win():
library.python.windows.replace_file(src, dst)
- else:
- os.rename(src, dst)
-
-
-# File/directory replacing move (rename)
-# Removes dst if exists
-# Non-atomic
-# Depends on ctypes on Windows
-# Throws OSError
-@errorfix_win
-def replace(src, dst):
- try:
- move(src, dst)
- except OSError as e:
- if e.errno not in (errno.EEXIST, errno.EISDIR, errno.ENOTDIR, errno.ENOTEMPTY):
- raise
- remove_tree(dst)
- move(src, dst)
-
-
-# Atomic file remove
-# Throws OSError
-@errorfix_win
+ else:
+ os.rename(src, dst)
+
+
+# File/directory replacing move (rename)
+# Removes dst if exists
+# Non-atomic
+# Depends on ctypes on Windows
+# Throws OSError
+@errorfix_win
+def replace(src, dst):
+ try:
+ move(src, dst)
+ except OSError as e:
+ if e.errno not in (errno.EEXIST, errno.EISDIR, errno.ENOTDIR, errno.ENOTEMPTY):
+ raise
+ remove_tree(dst)
+ move(src, dst)
+
+
+# Atomic file remove
+# Throws OSError
+@errorfix_win
@library.python.windows.diehard(library.python.windows.RETRIABLE_FILE_ERRORS, tries=_diehard_win_tries)
-def remove_file(path):
- os.remove(path)
-
-
-# Atomic empty directory remove
-# Throws OSError
-@errorfix_win
+def remove_file(path):
+ os.remove(path)
+
+
+# Atomic empty directory remove
+# Throws OSError
+@errorfix_win
@library.python.windows.diehard(library.python.windows.RETRIABLE_DIR_ERRORS, tries=_diehard_win_tries)
-def remove_dir(path):
- os.rmdir(path)
-
-
+def remove_dir(path):
+ os.rmdir(path)
+
+
def fix_path_encoding(path):
return library.python.strings.to_str(path, library.python.strings.fs_encoding())
-# File/directory remove
-# Non-atomic
-# Throws OSError, AssertionError
-@errorfix_win
-def remove_tree(path):
+# File/directory remove
+# Non-atomic
+# Throws OSError, AssertionError
+@errorfix_win
+def remove_tree(path):
@library.python.windows.diehard(library.python.windows.RETRIABLE_DIR_ERRORS, tries=_diehard_win_tries)
- def rmtree(path):
+ def rmtree(path):
if library.python.windows.on_win():
library.python.windows.rmtree(path)
else:
shutil.rmtree(fix_path_encoding(path))
-
- st = os.lstat(path)
- if stat.S_ISLNK(st.st_mode) or stat.S_ISREG(st.st_mode):
- remove_file(path)
- elif stat.S_ISDIR(st.st_mode):
- rmtree(path)
- else:
- assert False
-
-
-# File/directory remove ignoring errors
-# Non-atomic
-@errorfix_win
-def remove_tree_safe(path):
- try:
- st = os.lstat(path)
- if stat.S_ISLNK(st.st_mode) or stat.S_ISREG(st.st_mode):
- os.remove(path)
- elif stat.S_ISDIR(st.st_mode):
+
+ st = os.lstat(path)
+ if stat.S_ISLNK(st.st_mode) or stat.S_ISREG(st.st_mode):
+ remove_file(path)
+ elif stat.S_ISDIR(st.st_mode):
+ rmtree(path)
+ else:
+ assert False
+
+
+# File/directory remove ignoring errors
+# Non-atomic
+@errorfix_win
+def remove_tree_safe(path):
+ try:
+ st = os.lstat(path)
+ if stat.S_ISLNK(st.st_mode) or stat.S_ISREG(st.st_mode):
+ os.remove(path)
+ elif stat.S_ISDIR(st.st_mode):
shutil.rmtree(fix_path_encoding(path), ignore_errors=True)
# XXX
except UnicodeDecodeError as e:
logging.exception(u'remove_tree_safe with argument %s raise exception: %s', path, e)
raise
- except OSError:
- pass
-
-
-# File/directory remove
-# If path doesn't exist - does nothing
-# Non-atomic
-# Throws OSError, AssertionError
-@errorfix_win
-def ensure_removed(path):
- try:
- remove_tree(path)
- except OSError as e:
- if e.errno != errno.ENOENT:
- raise
-
-
-# Atomic file hardlink
-# Dst must not exist
-# Depends on ctypes on Windows
-# Throws OSError
-# If dst exists - throws OSError (errno EEXIST)
-@errorfix_win
-def hardlink(src, lnk):
+ except OSError:
+ pass
+
+
+# File/directory remove
+# If path doesn't exist - does nothing
+# Non-atomic
+# Throws OSError, AssertionError
+@errorfix_win
+def ensure_removed(path):
+ try:
+ remove_tree(path)
+ except OSError as e:
+ if e.errno != errno.ENOENT:
+ raise
+
+
+# Atomic file hardlink
+# Dst must not exist
+# Depends on ctypes on Windows
+# Throws OSError
+# If dst exists - throws OSError (errno EEXIST)
+@errorfix_win
+def hardlink(src, lnk):
if library.python.windows.on_win():
library.python.windows.hardlink(src, lnk)
- else:
- os.link(src, lnk)
-
-
+ else:
+ os.link(src, lnk)
+
+
@errorfix_win
def hardlink_or_copy(src, lnk):
def should_fallback_to_copy(exc):
@@ -222,18 +222,18 @@ def hardlink_or_copy(src, lnk):
raise
-# Atomic file/directory symlink (Unix only)
-# Dst must not exist
-# Throws OSError
-# If dst exists - throws OSError (errno EEXIST)
-@errorfix_win
-def symlink(src, lnk):
+# Atomic file/directory symlink (Unix only)
+# Dst must not exist
+# Throws OSError
+# If dst exists - throws OSError (errno EEXIST)
+@errorfix_win
+def symlink(src, lnk):
if library.python.windows.on_win():
library.python.windows.run_disabled(src, lnk)
- else:
- os.symlink(src, lnk)
-
-
+ else:
+ os.symlink(src, lnk)
+
+
# shutil.copy2 with follow_symlinks=False parameter (Unix only)
def copy2(src, lnk, follow_symlinks=True):
if six.PY3:
@@ -247,69 +247,69 @@ def copy2(src, lnk, follow_symlinks=True):
symlink(os.readlink(src), lnk)
-# Recursively hardlink directory
-# Uses plain hardlink for files
-# Dst must not exist
-# Non-atomic
-# Throws OSError
-@errorfix_win
-def hardlink_tree(src, dst):
- if not os.path.exists(src):
- raise CustomFsError(errno.ENOENT, filename=src)
- if os.path.isfile(src):
- hardlink(src, dst)
- return
+# Recursively hardlink directory
+# Uses plain hardlink for files
+# Dst must not exist
+# Non-atomic
+# Throws OSError
+@errorfix_win
+def hardlink_tree(src, dst):
+ if not os.path.exists(src):
+ raise CustomFsError(errno.ENOENT, filename=src)
+ if os.path.isfile(src):
+ hardlink(src, dst)
+ return
for dirpath, _, filenames in walk_relative(src):
- src_dirpath = os.path.join(src, dirpath) if dirpath != '.' else src
- dst_dirpath = os.path.join(dst, dirpath) if dirpath != '.' else dst
- os.mkdir(dst_dirpath)
- for filename in filenames:
- hardlink(os.path.join(src_dirpath, filename), os.path.join(dst_dirpath, filename))
-
-
-# File copy
-# throws EnvironmentError (OSError, IOError)
-@errorfix_win
+ src_dirpath = os.path.join(src, dirpath) if dirpath != '.' else src
+ dst_dirpath = os.path.join(dst, dirpath) if dirpath != '.' else dst
+ os.mkdir(dst_dirpath)
+ for filename in filenames:
+ hardlink(os.path.join(src_dirpath, filename), os.path.join(dst_dirpath, filename))
+
+
+# File copy
+# throws EnvironmentError (OSError, IOError)
+@errorfix_win
def copy_file(src, dst, copy_function=shutil.copy2):
- if os.path.isdir(dst):
- raise CustomFsError(errno.EISDIR, filename=dst)
+ if os.path.isdir(dst):
+ raise CustomFsError(errno.EISDIR, filename=dst)
copy_function(src, dst)
-
-
-# File/directory copy
-# throws EnvironmentError (OSError, IOError, shutil.Error)
-@errorfix_win
+
+
+# File/directory copy
+# throws EnvironmentError (OSError, IOError, shutil.Error)
+@errorfix_win
def copy_tree(src, dst, copy_function=shutil.copy2):
- if os.path.isfile(src):
+ if os.path.isfile(src):
copy_file(src, dst, copy_function=copy_function)
- return
+ return
copytree3(src, dst, copy_function=copy_function)
-
-
-# File read
-# Throws OSError
-@errorfix_win
-def read_file(path, binary=True):
- with open(path, 'r' + ('b' if binary else '')) as f:
- return f.read()
-
-
-# Decoding file read
-# Throws OSError
-@errorfix_win
-def read_file_unicode(path, binary=True, enc='utf-8'):
- if not binary:
+
+
+# File read
+# Throws OSError
+@errorfix_win
+def read_file(path, binary=True):
+ with open(path, 'r' + ('b' if binary else '')) as f:
+ return f.read()
+
+
+# Decoding file read
+# Throws OSError
+@errorfix_win
+def read_file_unicode(path, binary=True, enc='utf-8'):
+ if not binary:
if six.PY2:
with open(path, 'r') as f:
return library.python.strings.to_unicode(f.read(), enc)
else:
with open(path, 'r', encoding=enc) as f:
return f.read()
- # codecs.open is always binary
+ # codecs.open is always binary
with codecs.open(path, 'r', encoding=enc, errors=library.python.strings.ENCODING_ERRORS_POLICY) as f:
- return f.read()
-
-
+ return f.read()
+
+
@errorfix_win
def open_file(*args, **kwargs):
return (
@@ -317,52 +317,52 @@ def open_file(*args, **kwargs):
)
-# Atomic file write
-# Throws OSError
-@errorfix_win
-def write_file(path, data, binary=True):
- dir_path = os.path.dirname(path)
- if dir_path:
- ensure_dir(dir_path)
- tmp_path = path + '.tmp.' + str(random.random())
+# Atomic file write
+# Throws OSError
+@errorfix_win
+def write_file(path, data, binary=True):
+ dir_path = os.path.dirname(path)
+ if dir_path:
+ ensure_dir(dir_path)
+ tmp_path = path + '.tmp.' + str(random.random())
with open_file(tmp_path, 'w' + ('b' if binary else '')) as f:
if not isinstance(data, bytes) and binary:
data = data.encode('UTF-8')
- f.write(data)
- replace_file(tmp_path, path)
-
-
-# File size
-# Throws OSError
-@errorfix_win
-def get_file_size(path):
- return os.path.getsize(path)
-
-
-# File/directory size
-# Non-recursive mode for directory counts size for immediates
-# While raise_all_errors is set to False, file size fallbacks to zero in case of getsize errors
-# Throws OSError
-@errorfix_win
-def get_tree_size(path, recursive=False, raise_all_errors=False):
- if os.path.isfile(path):
- return get_file_size(path)
- total_size = 0
- for dir_path, _, files in os.walk(path):
- for f in files:
- fp = os.path.join(dir_path, f)
- try:
- total_size += get_file_size(fp)
- except OSError as e:
- if raise_all_errors:
- raise
+ f.write(data)
+ replace_file(tmp_path, path)
+
+
+# File size
+# Throws OSError
+@errorfix_win
+def get_file_size(path):
+ return os.path.getsize(path)
+
+
+# File/directory size
+# Non-recursive mode for directory counts size for immediates
+# While raise_all_errors is set to False, file size fallbacks to zero in case of getsize errors
+# Throws OSError
+@errorfix_win
+def get_tree_size(path, recursive=False, raise_all_errors=False):
+ if os.path.isfile(path):
+ return get_file_size(path)
+ total_size = 0
+ for dir_path, _, files in os.walk(path):
+ for f in files:
+ fp = os.path.join(dir_path, f)
+ try:
+ total_size += get_file_size(fp)
+ except OSError as e:
+ if raise_all_errors:
+ raise
logger.debug("Cannot calculate file size: %s", e)
- if not recursive:
- break
- return total_size
-
-
-# Directory copy ported from Python 3
+ if not recursive:
+ break
+ return total_size
+
+
+# Directory copy ported from Python 3
def copytree3(
src,
dst,
diff --git a/library/python/fs/test/test_fs.py b/library/python/fs/test/test_fs.py
index 3aaebd2643..9e2c70c069 100644
--- a/library/python/fs/test/test_fs.py
+++ b/library/python/fs/test/test_fs.py
@@ -1,961 +1,961 @@
-# coding=utf-8
-
-import errno
-import os
-import pytest
+# coding=utf-8
+
+import errno
+import os
+import pytest
import shutil
import six
-
+
import library.python.fs
import library.python.strings
import library.python.tmp
import library.python.windows
-
+
import yatest.common
-
-def in_env(case):
- def wrapped_case(*args, **kwargs):
+
+def in_env(case):
+ def wrapped_case(*args, **kwargs):
with library.python.tmp.temp_dir() as temp_dir:
- case(lambda path: os.path.join(temp_dir, path))
+ case(lambda path: os.path.join(temp_dir, path))
- return wrapped_case
-
-
-def mkfile(path, data=''):
+ return wrapped_case
+
+
+def mkfile(path, data=''):
with open(path, 'wb') as f:
- if data:
+ if data:
f.write(data) if isinstance(data, six.binary_type) else f.write(
data.encode(library.python.strings.fs_encoding())
)
-
-
-def mktree_example(path, name):
- os.mkdir(path(name))
- mkfile(path(name + '/file1'), 'FILE1')
- os.mkdir(path(name + '/dir1'))
- os.mkdir(path(name + '/dir2'))
- mkfile(path(name + '/dir2/file2'), 'FILE2')
- mkfile(path(name + '/dir2/file3'), 'FILE3')
-
-
-def file_data(path):
+
+
+def mktree_example(path, name):
+ os.mkdir(path(name))
+ mkfile(path(name + '/file1'), 'FILE1')
+ os.mkdir(path(name + '/dir1'))
+ os.mkdir(path(name + '/dir2'))
+ mkfile(path(name + '/dir2/file2'), 'FILE2')
+ mkfile(path(name + '/dir2/file3'), 'FILE3')
+
+
+def file_data(path):
with open(path, 'rb') as f:
return f.read().decode('utf-8')
-
-
-def serialize_tree(path):
- if os.path.isfile(path):
- return file_data(path)
- data = {'dirs': set(), 'files': {}}
- for dirpath, dirnames, filenames in os.walk(path):
- dirpath_rel = os.path.relpath(dirpath, path)
- if dirpath_rel == '.':
- dirpath_rel = ''
- data['dirs'].update(set(os.path.join(dirpath_rel, x) for x in dirnames))
- data['files'].update({os.path.join(dirpath_rel, x): file_data(os.path.join(dirpath, x)) for x in filenames})
- return data
-
-
-def trees_equal(dir1, dir2):
- return serialize_tree(dir1) == serialize_tree(dir2)
-
-
-def inodes_unsupported():
+
+
+def serialize_tree(path):
+ if os.path.isfile(path):
+ return file_data(path)
+ data = {'dirs': set(), 'files': {}}
+ for dirpath, dirnames, filenames in os.walk(path):
+ dirpath_rel = os.path.relpath(dirpath, path)
+ if dirpath_rel == '.':
+ dirpath_rel = ''
+ data['dirs'].update(set(os.path.join(dirpath_rel, x) for x in dirnames))
+ data['files'].update({os.path.join(dirpath_rel, x): file_data(os.path.join(dirpath, x)) for x in filenames})
+ return data
+
+
+def trees_equal(dir1, dir2):
+ return serialize_tree(dir1) == serialize_tree(dir2)
+
+
+def inodes_unsupported():
return library.python.windows.on_win()
-
-
-def inodes_equal(path1, path2):
- return os.stat(path1).st_ino == os.stat(path2).st_ino
-
-
-def gen_error_access_denied():
+
+
+def inodes_equal(path1, path2):
+ return os.stat(path1).st_ino == os.stat(path2).st_ino
+
+
+def gen_error_access_denied():
if library.python.windows.on_win():
- err = WindowsError()
- err.errno = errno.EACCES
- err.strerror = ''
+ err = WindowsError()
+ err.errno = errno.EACCES
+ err.strerror = ''
err.winerror = library.python.windows.ERRORS['ACCESS_DENIED']
- else:
- err = OSError()
- err.errno = errno.EACCES
- err.strerror = os.strerror(err.errno)
- err.filename = 'unknown/file'
- raise err
-
-
-def test_errorfix_win():
+ else:
+ err = OSError()
+ err.errno = errno.EACCES
+ err.strerror = os.strerror(err.errno)
+ err.filename = 'unknown/file'
+ raise err
+
+
+def test_errorfix_win():
@library.python.fs.errorfix_win
- def erroneous_func():
- gen_error_access_denied()
-
- with pytest.raises(OSError) as errinfo:
- erroneous_func()
- assert errinfo.value.errno == errno.EACCES
- assert errinfo.value.filename == 'unknown/file'
+ def erroneous_func():
+ gen_error_access_denied()
+
+ with pytest.raises(OSError) as errinfo:
+ erroneous_func()
+ assert errinfo.value.errno == errno.EACCES
+ assert errinfo.value.filename == 'unknown/file'
# See transcode_error, which encodes strerror, in library/python/windows/__init__.py
assert isinstance(errinfo.value.strerror, (six.binary_type, six.text_type))
- assert errinfo.value.strerror
-
-
-def test_custom_fs_error():
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.strerror
+
+
+def test_custom_fs_error():
+ with pytest.raises(OSError) as errinfo:
raise library.python.fs.CustomFsError(errno.EACCES, filename='some/file')
- assert errinfo.value.errno == errno.EACCES
+ assert errinfo.value.errno == errno.EACCES
# See transcode_error, which encodes strerror, in library/python/windows/__init__.py
assert isinstance(errinfo.value.strerror, (six.binary_type, six.text_type))
- assert errinfo.value.filename == 'some/file'
-
-
-@in_env
-def test_ensure_dir(path):
+ assert errinfo.value.filename == 'some/file'
+
+
+@in_env
+def test_ensure_dir(path):
library.python.fs.ensure_dir(path('dir/subdir'))
- assert os.path.isdir(path('dir'))
- assert os.path.isdir(path('dir/subdir'))
-
-
-@in_env
-def test_ensure_dir_exists(path):
- os.makedirs(path('dir/subdir'))
+ assert os.path.isdir(path('dir'))
+ assert os.path.isdir(path('dir/subdir'))
+
+
+@in_env
+def test_ensure_dir_exists(path):
+ os.makedirs(path('dir/subdir'))
library.python.fs.ensure_dir(path('dir/subdir'))
- assert os.path.isdir(path('dir'))
- assert os.path.isdir(path('dir/subdir'))
-
-
-@in_env
-def test_ensure_dir_exists_partly(path):
- os.mkdir(path('dir'))
+ assert os.path.isdir(path('dir'))
+ assert os.path.isdir(path('dir/subdir'))
+
+
+@in_env
+def test_ensure_dir_exists_partly(path):
+ os.mkdir(path('dir'))
library.python.fs.ensure_dir(path('dir/subdir'))
- assert os.path.isdir(path('dir'))
- assert os.path.isdir(path('dir/subdir'))
-
-
-@in_env
-def test_ensure_dir_exists_file(path):
- mkfile(path('dir'))
- with pytest.raises(OSError) as errinfo:
+ assert os.path.isdir(path('dir'))
+ assert os.path.isdir(path('dir/subdir'))
+
+
+@in_env
+def test_ensure_dir_exists_file(path):
+ mkfile(path('dir'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.ensure_dir(path('dir/subdir'))
- # ENOENT on Windows!
- assert errinfo.value.errno in (errno.ENOTDIR, errno.ENOENT)
- assert os.path.isfile(path('dir'))
-
-
-@in_env
-def test_create_dirs(path):
+ # ENOENT on Windows!
+ assert errinfo.value.errno in (errno.ENOTDIR, errno.ENOENT)
+ assert os.path.isfile(path('dir'))
+
+
+@in_env
+def test_create_dirs(path):
assert library.python.fs.create_dirs(path('dir/subdir')) == path('dir/subdir')
- assert os.path.isdir(path('dir'))
- assert os.path.isdir(path('dir/subdir'))
-
-
-@in_env
-def test_move_file(path):
- mkfile(path('src'), 'SRC')
+ assert os.path.isdir(path('dir'))
+ assert os.path.isdir(path('dir/subdir'))
+
+
+@in_env
+def test_move_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.move(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
-@in_env
-def test_move_file_no_src(path):
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
+@in_env
+def test_move_file_no_src(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno == errno.ENOENT
-
-
-@in_env
-def test_move_file_exists(path):
- mkfile(path('src'), 'SRC')
- mkfile(path('dst'), 'DST')
+ assert errinfo.value.errno == errno.ENOENT
+
+
+@in_env
+def test_move_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ mkfile(path('dst'), 'DST')
if library.python.windows.on_win():
- # move is platform-dependent, use replace_file for dst replacement on all platforms
- with pytest.raises(OSError) as errinfo:
+ # move is platform-dependent, use replace_file for dst replacement on all platforms
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'DST'
- else:
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'DST'
+ else:
library.python.fs.move(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
-@in_env
-def test_move_file_exists_dir_empty(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
+@in_env
+def test_move_file_exists_dir_empty(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EEXIST, errno.EISDIR)
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_move_file_exists_dir_nonempty(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- mkfile(path('dst/dst_file'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno in (errno.EEXIST, errno.EISDIR)
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_move_file_exists_dir_nonempty(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ mkfile(path('dst/dst_file'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EEXIST, errno.EISDIR)
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/dst_file'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_move_dir(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
+ assert errinfo.value.errno in (errno.EEXIST, errno.EISDIR)
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/dst_file'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_move_dir(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
library.python.fs.move(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
-
-
-@in_env
-def test_move_dir_exists_empty(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- os.mkdir(path('dst'))
+ assert not os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+
+
+@in_env
+def test_move_dir_exists_empty(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ os.mkdir(path('dst'))
if library.python.windows.on_win():
- # move is platform-dependent, use non-atomic replace for directory replacement
- with pytest.raises(OSError) as errinfo:
+ # move is platform-dependent, use non-atomic replace for directory replacement
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.isfile(path('dst/src_file'))
- else:
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.isfile(path('dst/src_file'))
+ else:
library.python.fs.move(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
-
-
-@in_env
-def test_move_dir_exists_nonempty(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- os.mkdir(path('dst'))
- mkfile(path('dst/dst_file'))
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+
+
+@in_env
+def test_move_dir_exists_nonempty(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ os.mkdir(path('dst'))
+ mkfile(path('dst/dst_file'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EEXIST, errno.ENOTEMPTY)
- assert os.path.isdir(path('src'))
- assert os.path.isfile(path('src/src_file'))
- assert os.path.isdir(path('dst'))
- assert not os.path.isfile(path('dst/src_file'))
- assert os.path.isfile(path('dst/dst_file'))
-
-
-@in_env
-def test_move_dir_exists_file(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- mkfile(path('dst'), 'DST')
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno in (errno.EEXIST, errno.ENOTEMPTY)
+ assert os.path.isdir(path('src'))
+ assert os.path.isfile(path('src/src_file'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.isfile(path('dst/src_file'))
+ assert os.path.isfile(path('dst/dst_file'))
+
+
+@in_env
+def test_move_dir_exists_file(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ mkfile(path('dst'), 'DST')
+ with pytest.raises(OSError) as errinfo:
library.python.fs.move(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EEXIST, errno.ENOTDIR)
- assert os.path.isdir(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'DST'
-
-
-@in_env
-def test_replace_file(path):
- mkfile(path('src'), 'SRC')
+ assert errinfo.value.errno in (errno.EEXIST, errno.ENOTDIR)
+ assert os.path.isdir(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'DST'
+
+
+@in_env
+def test_replace_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.replace_file(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
- mkfile(path('src'), 'SRC')
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+ mkfile(path('src'), 'SRC')
library.python.fs.replace(path('src'), path('dst2'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst2'))
- assert file_data(path('dst2')) == 'SRC'
-
-
-@in_env
-def test_replace_file_no_src(path):
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst2'))
+ assert file_data(path('dst2')) == 'SRC'
+
+
+@in_env
+def test_replace_file_no_src(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.replace_file(path('src'), path('dst'))
- assert errinfo.value.errno == errno.ENOENT
-
- with pytest.raises(OSError) as errinfo2:
+ assert errinfo.value.errno == errno.ENOENT
+
+ with pytest.raises(OSError) as errinfo2:
library.python.fs.replace(path('src'), path('dst2'))
- assert errinfo2.value.errno == errno.ENOENT
-
-
-@in_env
-def test_replace_file_exists(path):
- mkfile(path('src'), 'SRC')
- mkfile(path('dst'), 'DST')
+ assert errinfo2.value.errno == errno.ENOENT
+
+
+@in_env
+def test_replace_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ mkfile(path('dst'), 'DST')
library.python.fs.replace_file(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
- mkfile(path('src'), 'SRC')
- mkfile(path('dst2'), 'DST')
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+ mkfile(path('src'), 'SRC')
+ mkfile(path('dst2'), 'DST')
library.python.fs.replace(path('src'), path('dst2'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst2'))
- assert file_data(path('dst2')) == 'SRC'
-
-
-@in_env
-def test_replace_file_exists_dir_empty(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst2'))
+ assert file_data(path('dst2')) == 'SRC'
+
+
+@in_env
+def test_replace_file_exists_dir_empty(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.replace_file(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EISDIR, errno.EACCES)
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_replace_file_exists_dir_empty_overwrite(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
+ assert errinfo.value.errno in (errno.EISDIR, errno.EACCES)
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_replace_file_exists_dir_empty_overwrite(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
library.python.fs.replace(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
-@in_env
-def test_replace_file_exists_dir_nonempty(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- mkfile(path('dst/dst_file'))
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
+@in_env
+def test_replace_file_exists_dir_nonempty(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ mkfile(path('dst/dst_file'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.replace_file(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EISDIR, errno.EACCES)
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/dst_file'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_replace_file_exists_dir_nonempty_overwrite(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- mkfile(path('dst/dst_file'))
+ assert errinfo.value.errno in (errno.EISDIR, errno.EACCES)
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/dst_file'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_replace_file_exists_dir_nonempty_overwrite(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ mkfile(path('dst/dst_file'))
library.python.fs.replace(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
-@in_env
-def test_replace_dir(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
+ assert not os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
+@in_env
+def test_replace_dir(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
library.python.fs.replace(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
-
-
-@in_env
-def test_replace_dir_exists_empty(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- os.mkdir(path('dst'))
+ assert not os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+
+
+@in_env
+def test_replace_dir_exists_empty(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ os.mkdir(path('dst'))
library.python.fs.replace(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
-
-
-@in_env
-def test_replace_dir_exists_nonempty(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- os.mkdir(path('dst'))
- mkfile(path('dst/dst_file'))
+ assert not os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+
+
+@in_env
+def test_replace_dir_exists_nonempty(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ os.mkdir(path('dst'))
+ mkfile(path('dst/dst_file'))
library.python.fs.replace(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
- assert not os.path.isfile(path('dst/dst_file'))
-
-
-@in_env
-def test_replace_dir_exists_file(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- mkfile(path('dst'), 'DST')
+ assert not os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+ assert not os.path.isfile(path('dst/dst_file'))
+
+
+@in_env
+def test_replace_dir_exists_file(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ mkfile(path('dst'), 'DST')
library.python.fs.replace(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
-
-
-@in_env
-def test_remove_file(path):
- mkfile(path('path'))
+ assert not os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+
+
+@in_env
+def test_remove_file(path):
+ mkfile(path('path'))
library.python.fs.remove_file(path('path'))
- assert not os.path.exists(path('path'))
-
-
-@in_env
-def test_remove_file_no(path):
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.exists(path('path'))
+
+
+@in_env
+def test_remove_file_no(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.remove_file(path('path'))
- assert errinfo.value.errno == errno.ENOENT
-
-
-@in_env
-def test_remove_file_exists_dir(path):
- os.mkdir(path('path'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.ENOENT
+
+
+@in_env
+def test_remove_file_exists_dir(path):
+ os.mkdir(path('path'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.remove_file(path('path'))
- assert errinfo.value.errno in (errno.EISDIR, errno.EACCES)
- assert os.path.isdir(path('path'))
-
-
-@in_env
-def test_remove_dir(path):
- os.mkdir(path('path'))
+ assert errinfo.value.errno in (errno.EISDIR, errno.EACCES)
+ assert os.path.isdir(path('path'))
+
+
+@in_env
+def test_remove_dir(path):
+ os.mkdir(path('path'))
library.python.fs.remove_dir(path('path'))
- assert not os.path.exists(path('path'))
-
-
-@in_env
-def test_remove_dir_no(path):
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.exists(path('path'))
+
+
+@in_env
+def test_remove_dir_no(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.remove_dir(path('path'))
- assert errinfo.value.errno == errno.ENOENT
-
-
-@in_env
-def test_remove_dir_exists_file(path):
- mkfile(path('path'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.ENOENT
+
+
+@in_env
+def test_remove_dir_exists_file(path):
+ mkfile(path('path'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.remove_dir(path('path'))
- assert errinfo.value.errno in (errno.ENOTDIR, errno.EINVAL)
- assert os.path.isfile(path('path'))
-
-
-@in_env
-def test_remove_tree(path):
- mktree_example(path, 'path')
+ assert errinfo.value.errno in (errno.ENOTDIR, errno.EINVAL)
+ assert os.path.isfile(path('path'))
+
+
+@in_env
+def test_remove_tree(path):
+ mktree_example(path, 'path')
library.python.fs.remove_tree(path('path'))
- assert not os.path.exists(path('path'))
-
-
-@in_env
-def test_remove_tree_empty(path):
- os.mkdir(path('path'))
+ assert not os.path.exists(path('path'))
+
+
+@in_env
+def test_remove_tree_empty(path):
+ os.mkdir(path('path'))
library.python.fs.remove_tree(path('path'))
- assert not os.path.exists(path('path'))
-
-
-@in_env
-def test_remove_tree_file(path):
- mkfile(path('path'))
+ assert not os.path.exists(path('path'))
+
+
+@in_env
+def test_remove_tree_file(path):
+ mkfile(path('path'))
library.python.fs.remove_tree(path('path'))
- assert not os.path.exists(path('path'))
-
-
-@in_env
-def test_remove_tree_no(path):
- with pytest.raises(OSError) as errinfo:
+ assert not os.path.exists(path('path'))
+
+
+@in_env
+def test_remove_tree_no(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.remove_tree(path('path'))
- assert errinfo.value.errno == errno.ENOENT
-
-
-@in_env
-def test_remove_tree_safe(path):
+ assert errinfo.value.errno == errno.ENOENT
+
+
+@in_env
+def test_remove_tree_safe(path):
library.python.fs.remove_tree_safe(path('path'))
-
-
-@in_env
-def test_ensure_removed(path):
+
+
+@in_env
+def test_ensure_removed(path):
library.python.fs.ensure_removed(path('path'))
-
-
-@in_env
-def test_ensure_removed_exists(path):
- os.makedirs(path('dir/subdir'))
+
+
+@in_env
+def test_ensure_removed_exists(path):
+ os.makedirs(path('dir/subdir'))
library.python.fs.ensure_removed(path('dir'))
- assert not os.path.exists(path('dir'))
-
-
-@in_env
-def test_ensure_removed_exists_precise(path):
- os.makedirs(path('dir/subdir'))
+ assert not os.path.exists(path('dir'))
+
+
+@in_env
+def test_ensure_removed_exists_precise(path):
+ os.makedirs(path('dir/subdir'))
library.python.fs.ensure_removed(path('dir/subdir'))
- assert os.path.exists(path('dir'))
- assert not os.path.exists(path('dir/subdir'))
-
-
-@in_env
-def test_hardlink_file(path):
- mkfile(path('src'), 'SRC')
+ assert os.path.exists(path('dir'))
+ assert not os.path.exists(path('dir/subdir'))
+
+
+@in_env
+def test_hardlink_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.hardlink(path('src'), path('dst'))
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
- assert inodes_unsupported() or inodes_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_hardlink_file_no_src(path):
- with pytest.raises(OSError) as errinfo:
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+ assert inodes_unsupported() or inodes_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_hardlink_file_no_src(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.ENOENT
-
-
-@in_env
-def test_hardlink_file_exists(path):
- mkfile(path('src'), 'SRC')
- mkfile(path('dst'), 'DST')
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.ENOENT
+
+
+@in_env
+def test_hardlink_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ mkfile(path('dst'), 'DST')
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'DST'
- assert inodes_unsupported() or not inodes_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_hardlink_file_exists_dir(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'DST'
+ assert inodes_unsupported() or not inodes_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_hardlink_file_exists_dir(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_hardlink_dir(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_hardlink_dir(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink(path('src'), path('dst'))
- assert errinfo.value.errno in (errno.EPERM, errno.EACCES)
- assert os.path.isdir(path('src'))
- assert not os.path.isdir(path('dst'))
-
-
+ assert errinfo.value.errno in (errno.EPERM, errno.EACCES)
+ assert os.path.isdir(path('src'))
+ assert not os.path.isdir(path('dst'))
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_file(path):
- mkfile(path('src'), 'SRC')
+@in_env
+def test_symlink_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.symlink(path('src'), path('dst'))
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert os.path.islink(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert os.path.islink(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_file_no_src(path):
+@in_env
+def test_symlink_file_no_src(path):
library.python.fs.symlink(path('src'), path('dst'))
- assert not os.path.isfile(path('src'))
- assert not os.path.isfile(path('dst'))
- assert os.path.islink(path('dst'))
-
-
+ assert not os.path.isfile(path('src'))
+ assert not os.path.isfile(path('dst'))
+ assert os.path.islink(path('dst'))
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_file_exists(path):
- mkfile(path('src'), 'SRC')
- mkfile(path('dst'), 'DST')
- with pytest.raises(OSError) as errinfo:
+@in_env
+def test_symlink_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ mkfile(path('dst'), 'DST')
+ with pytest.raises(OSError) as errinfo:
library.python.fs.symlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert not os.path.islink(path('dst'))
- assert file_data(path('dst')) == 'DST'
-
-
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert not os.path.islink(path('dst'))
+ assert file_data(path('dst')) == 'DST'
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_file_exists_dir(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- with pytest.raises(OSError) as errinfo:
+@in_env
+def test_symlink_file_exists_dir(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.symlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.islink(path('dst'))
- assert not os.path.isfile(path('dst/src'))
-
-
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.islink(path('dst'))
+ assert not os.path.isfile(path('dst/src'))
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_dir(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
+@in_env
+def test_symlink_dir(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
library.python.fs.symlink(path('src'), path('dst'))
- assert os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.islink(path('dst'))
- assert os.path.isfile(path('dst/src_file'))
-
-
+ assert os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.islink(path('dst'))
+ assert os.path.isfile(path('dst/src_file'))
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_dir_no_src(path):
+@in_env
+def test_symlink_dir_no_src(path):
library.python.fs.symlink(path('src'), path('dst'))
- assert not os.path.isdir(path('src'))
- assert not os.path.isdir(path('dst'))
- assert os.path.islink(path('dst'))
-
-
+ assert not os.path.isdir(path('src'))
+ assert not os.path.isdir(path('dst'))
+ assert os.path.islink(path('dst'))
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_dir_exists(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- os.mkdir(path('dst'))
- with pytest.raises(OSError) as errinfo:
+@in_env
+def test_symlink_dir_exists(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ os.mkdir(path('dst'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.symlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isdir(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.islink(path('dst'))
- assert not os.path.isfile(path('dst/src_file'))
-
-
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isdir(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.islink(path('dst'))
+ assert not os.path.isfile(path('dst/src_file'))
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_symlink_dir_exists_file(path):
- os.mkdir(path('src'))
- mkfile(path('src/src_file'))
- mkfile(path('dst'), 'DST')
- with pytest.raises(OSError) as errinfo:
+@in_env
+def test_symlink_dir_exists_file(path):
+ os.mkdir(path('src'))
+ mkfile(path('src/src_file'))
+ mkfile(path('dst'), 'DST')
+ with pytest.raises(OSError) as errinfo:
library.python.fs.symlink(path('src'), path('dst'))
- assert errinfo.value.errno == errno.EEXIST
- assert os.path.isdir(path('src'))
- assert os.path.isfile(path('dst'))
- assert not os.path.islink(path('dst'))
-
-
-@in_env
-def test_hardlink_tree(path):
- mktree_example(path, 'src')
+ assert errinfo.value.errno == errno.EEXIST
+ assert os.path.isdir(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert not os.path.islink(path('dst'))
+
+
+@in_env
+def test_hardlink_tree(path):
+ mktree_example(path, 'src')
library.python.fs.hardlink_tree(path('src'), path('dst'))
- assert trees_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_hardlink_tree_empty(path):
- os.mkdir(path('src'))
+ assert trees_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_hardlink_tree_empty(path):
+ os.mkdir(path('src'))
library.python.fs.hardlink_tree(path('src'), path('dst'))
- assert trees_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_hardlink_tree_file(path):
- mkfile(path('src'), 'SRC')
+ assert trees_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_hardlink_tree_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.hardlink_tree(path('src'), path('dst'))
- assert trees_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_hardlink_tree_no_src(path):
- with pytest.raises(OSError) as errinfo:
+ assert trees_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_hardlink_tree_no_src(path):
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink_tree(path('src'), path('dst'))
- assert errinfo.value.errno == errno.ENOENT
-
-
-@in_env
-def test_hardlink_tree_exists(path):
- mktree_example(path, 'src')
- os.mkdir(path('dst_dir'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.ENOENT
+
+
+@in_env
+def test_hardlink_tree_exists(path):
+ mktree_example(path, 'src')
+ os.mkdir(path('dst_dir'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink_tree(path('src'), path('dst_dir'))
- assert errinfo.value.errno == errno.EEXIST
- mkfile(path('dst_file'), 'DST')
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.EEXIST
+ mkfile(path('dst_file'), 'DST')
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink_tree(path('src'), path('dst_file'))
- assert errinfo.value.errno == errno.EEXIST
-
-
-@in_env
-def test_hardlink_tree_file_exists(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst_dir'))
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.EEXIST
+
+
+@in_env
+def test_hardlink_tree_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst_dir'))
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink_tree(path('src'), path('dst_dir'))
- assert errinfo.value.errno == errno.EEXIST
- mkfile(path('dst_file'), 'DST')
- with pytest.raises(OSError) as errinfo:
+ assert errinfo.value.errno == errno.EEXIST
+ mkfile(path('dst_file'), 'DST')
+ with pytest.raises(OSError) as errinfo:
library.python.fs.hardlink_tree(path('src'), path('dst_file'))
- assert errinfo.value.errno == errno.EEXIST
-
-
-@in_env
-def test_copy_file(path):
- mkfile(path('src'), 'SRC')
+ assert errinfo.value.errno == errno.EEXIST
+
+
+@in_env
+def test_copy_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.copy_file(path('src'), path('dst'))
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
-@in_env
-def test_copy_file_no_src(path):
- with pytest.raises(EnvironmentError):
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
+@in_env
+def test_copy_file_no_src(path):
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_file(path('src'), path('dst'))
-
-
-@in_env
-def test_copy_file_exists(path):
- mkfile(path('src'), 'SRC')
- mkfile(path('dst'), 'DST')
+
+
+@in_env
+def test_copy_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ mkfile(path('dst'), 'DST')
library.python.fs.copy_file(path('src'), path('dst'))
- assert os.path.isfile(path('src'))
- assert os.path.isfile(path('dst'))
- assert file_data(path('dst')) == 'SRC'
-
-
-@in_env
-def test_copy_file_exists_dir_empty(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- with pytest.raises(EnvironmentError):
+ assert os.path.isfile(path('src'))
+ assert os.path.isfile(path('dst'))
+ assert file_data(path('dst')) == 'SRC'
+
+
+@in_env
+def test_copy_file_exists_dir_empty(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_file(path('src'), path('dst'))
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_copy_file_exists_dir_nonempty(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst'))
- mkfile(path('dst/dst_file'))
- with pytest.raises(EnvironmentError):
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_copy_file_exists_dir_nonempty(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst'))
+ mkfile(path('dst/dst_file'))
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_file(path('src'), path('dst'))
- assert os.path.isfile(path('src'))
- assert os.path.isdir(path('dst'))
- assert os.path.isfile(path('dst/dst_file'))
- assert not os.path.isfile(path('dst/src'))
-
-
-@in_env
-def test_copy_tree(path):
- mktree_example(path, 'src')
+ assert os.path.isfile(path('src'))
+ assert os.path.isdir(path('dst'))
+ assert os.path.isfile(path('dst/dst_file'))
+ assert not os.path.isfile(path('dst/src'))
+
+
+@in_env
+def test_copy_tree(path):
+ mktree_example(path, 'src')
library.python.fs.copy_tree(path('src'), path('dst'))
- assert trees_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_copy_tree_empty(path):
- os.mkdir(path('src'))
+ assert trees_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_copy_tree_empty(path):
+ os.mkdir(path('src'))
library.python.fs.copy_tree(path('src'), path('dst'))
- assert trees_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_copy_tree_file(path):
- mkfile(path('src'), 'SRC')
+ assert trees_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_copy_tree_file(path):
+ mkfile(path('src'), 'SRC')
library.python.fs.copy_tree(path('src'), path('dst'))
- assert trees_equal(path('src'), path('dst'))
-
-
-@in_env
-def test_copy_tree_no_src(path):
- with pytest.raises(EnvironmentError):
+ assert trees_equal(path('src'), path('dst'))
+
+
+@in_env
+def test_copy_tree_no_src(path):
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_tree(path('src'), path('dst'))
-
-
-@in_env
-def test_copy_tree_exists(path):
- mktree_example(path, 'src')
- os.mkdir(path('dst_dir'))
- with pytest.raises(EnvironmentError):
+
+
+@in_env
+def test_copy_tree_exists(path):
+ mktree_example(path, 'src')
+ os.mkdir(path('dst_dir'))
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_tree(path('src'), path('dst_dir'))
- mkfile(path('dst_file'), 'DST')
- with pytest.raises(EnvironmentError):
+ mkfile(path('dst_file'), 'DST')
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_tree(path('src'), path('dst_file'))
-
-
-@in_env
-def test_copy_tree_file_exists(path):
- mkfile(path('src'), 'SRC')
- os.mkdir(path('dst_dir'))
- with pytest.raises(EnvironmentError):
+
+
+@in_env
+def test_copy_tree_file_exists(path):
+ mkfile(path('src'), 'SRC')
+ os.mkdir(path('dst_dir'))
+ with pytest.raises(EnvironmentError):
library.python.fs.copy_tree(path('src'), path('dst_dir'))
- mkfile(path('dst_file'), 'DST')
+ mkfile(path('dst_file'), 'DST')
library.python.fs.copy_tree(path('src'), path('dst_file'))
- assert trees_equal(path('src'), path('dst_file'))
-
-
-@in_env
-def test_read_file(path):
- mkfile(path('src'), 'SRC')
+ assert trees_equal(path('src'), path('dst_file'))
+
+
+@in_env
+def test_read_file(path):
+ mkfile(path('src'), 'SRC')
assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == 'SRC'
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC'
-
-
-@in_env
-def test_read_file_empty(path):
- mkfile(path('src'))
+
+
+@in_env
+def test_read_file_empty(path):
+ mkfile(path('src'))
assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == ''
assert library.python.fs.read_file(path('src'), binary=False) == ''
-
-
-@in_env
-def test_read_file_multiline(path):
- mkfile(path('src'), 'SRC line 1\nSRC line 2\n')
+
+
+@in_env
+def test_read_file_multiline(path):
+ mkfile(path('src'), 'SRC line 1\nSRC line 2\n')
assert (
library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding())
== 'SRC line 1\nSRC line 2\n'
)
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC line 1\nSRC line 2\n'
-
-
-@in_env
-def test_read_file_multiline_crlf(path):
- mkfile(path('src'), 'SRC line 1\r\nSRC line 2\r\n')
+
+
+@in_env
+def test_read_file_multiline_crlf(path):
+ mkfile(path('src'), 'SRC line 1\r\nSRC line 2\r\n')
assert (
library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding())
== 'SRC line 1\r\nSRC line 2\r\n'
)
if library.python.windows.on_win() or six.PY3: # universal newlines are by default in text mode in python3
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC line 1\nSRC line 2\n'
- else:
+ else:
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC line 1\r\nSRC line 2\r\n'
-
-
-@in_env
-def test_read_file_unicode(path):
- s = u'АБВ'
- mkfile(path('src'), s.encode('utf-8'))
- mkfile(path('src_cp1251'), s.encode('cp1251'))
+
+
+@in_env
+def test_read_file_unicode(path):
+ s = u'АБВ'
+ mkfile(path('src'), s.encode('utf-8'))
+ mkfile(path('src_cp1251'), s.encode('cp1251'))
assert library.python.fs.read_file_unicode(path('src')) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), enc='cp1251') == s
assert library.python.fs.read_file_unicode(path('src'), binary=False) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), binary=False, enc='cp1251') == s
-
-
-@in_env
-def test_read_file_unicode_empty(path):
- mkfile(path('src'))
- mkfile(path('src_cp1251'))
+
+
+@in_env
+def test_read_file_unicode_empty(path):
+ mkfile(path('src'))
+ mkfile(path('src_cp1251'))
assert library.python.fs.read_file_unicode(path('src')) == ''
assert library.python.fs.read_file_unicode(path('src_cp1251'), enc='cp1251') == ''
assert library.python.fs.read_file_unicode(path('src'), binary=False) == ''
assert library.python.fs.read_file_unicode(path('src_cp1251'), binary=False, enc='cp1251') == ''
-
-
-@in_env
-def test_read_file_unicode_multiline(path):
- s = u'АБВ\nИ еще\n'
- mkfile(path('src'), s.encode('utf-8'))
- mkfile(path('src_cp1251'), s.encode('cp1251'))
+
+
+@in_env
+def test_read_file_unicode_multiline(path):
+ s = u'АБВ\nИ еще\n'
+ mkfile(path('src'), s.encode('utf-8'))
+ mkfile(path('src_cp1251'), s.encode('cp1251'))
assert library.python.fs.read_file_unicode(path('src')) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), enc='cp1251') == s
assert library.python.fs.read_file_unicode(path('src'), binary=False) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), binary=False, enc='cp1251') == s
-
-
-@in_env
-def test_read_file_unicode_multiline_crlf(path):
- s = u'АБВ\r\nИ еще\r\n'
- mkfile(path('src'), s.encode('utf-8'))
- mkfile(path('src_cp1251'), s.encode('cp1251'))
+
+
+@in_env
+def test_read_file_unicode_multiline_crlf(path):
+ s = u'АБВ\r\nИ еще\r\n'
+ mkfile(path('src'), s.encode('utf-8'))
+ mkfile(path('src_cp1251'), s.encode('cp1251'))
assert library.python.fs.read_file_unicode(path('src')) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), enc='cp1251') == s
if library.python.windows.on_win() or six.PY3: # universal newlines are by default in text mode in python3
assert library.python.fs.read_file_unicode(path('src'), binary=False) == u'АБВ\nИ еще\n'
assert library.python.fs.read_file_unicode(path('src_cp1251'), binary=False, enc='cp1251') == u'АБВ\nИ еще\n'
- else:
+ else:
assert library.python.fs.read_file_unicode(path('src'), binary=False) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), binary=False, enc='cp1251') == s
-
-
-@in_env
-def test_write_file(path):
+
+
+@in_env
+def test_write_file(path):
library.python.fs.write_file(path('src'), 'SRC')
- assert file_data(path('src')) == 'SRC'
+ assert file_data(path('src')) == 'SRC'
library.python.fs.write_file(path('src2'), 'SRC', binary=False)
- assert file_data(path('src2')) == 'SRC'
-
-
-@in_env
-def test_write_file_empty(path):
+ assert file_data(path('src2')) == 'SRC'
+
+
+@in_env
+def test_write_file_empty(path):
library.python.fs.write_file(path('src'), '')
- assert file_data(path('src')) == ''
+ assert file_data(path('src')) == ''
library.python.fs.write_file(path('src2'), '', binary=False)
- assert file_data(path('src2')) == ''
-
-
-@in_env
-def test_write_file_multiline(path):
+ assert file_data(path('src2')) == ''
+
+
+@in_env
+def test_write_file_multiline(path):
library.python.fs.write_file(path('src'), 'SRC line 1\nSRC line 2\n')
- assert file_data(path('src')) == 'SRC line 1\nSRC line 2\n'
+ assert file_data(path('src')) == 'SRC line 1\nSRC line 2\n'
library.python.fs.write_file(path('src2'), 'SRC line 1\nSRC line 2\n', binary=False)
if library.python.windows.on_win():
- assert file_data(path('src2')) == 'SRC line 1\r\nSRC line 2\r\n'
- else:
- assert file_data(path('src2')) == 'SRC line 1\nSRC line 2\n'
-
-
-@in_env
-def test_write_file_multiline_crlf(path):
+ assert file_data(path('src2')) == 'SRC line 1\r\nSRC line 2\r\n'
+ else:
+ assert file_data(path('src2')) == 'SRC line 1\nSRC line 2\n'
+
+
+@in_env
+def test_write_file_multiline_crlf(path):
library.python.fs.write_file(path('src'), 'SRC line 1\r\nSRC line 2\r\n')
- assert file_data(path('src')) == 'SRC line 1\r\nSRC line 2\r\n'
+ assert file_data(path('src')) == 'SRC line 1\r\nSRC line 2\r\n'
library.python.fs.write_file(path('src2'), 'SRC line 1\r\nSRC line 2\r\n', binary=False)
if library.python.windows.on_win():
- assert file_data(path('src2')) == 'SRC line 1\r\r\nSRC line 2\r\r\n'
- else:
- assert file_data(path('src2')) == 'SRC line 1\r\nSRC line 2\r\n'
-
-
-@in_env
-def test_get_file_size(path):
- mkfile(path('one.txt'), '22')
+ assert file_data(path('src2')) == 'SRC line 1\r\r\nSRC line 2\r\r\n'
+ else:
+ assert file_data(path('src2')) == 'SRC line 1\r\nSRC line 2\r\n'
+
+
+@in_env
+def test_get_file_size(path):
+ mkfile(path('one.txt'), '22')
assert library.python.fs.get_file_size(path('one.txt')) == 2
-@in_env
-def test_get_file_size_empty(path):
- mkfile(path('one.txt'))
+@in_env
+def test_get_file_size_empty(path):
+ mkfile(path('one.txt'))
assert library.python.fs.get_file_size(path('one.txt')) == 0
-
-
-@in_env
-def test_get_tree_size(path):
- os.makedirs(path('deeper'))
- mkfile(path('one.txt'), '1')
- mkfile(path('deeper/two.txt'), '22')
+
+
+@in_env
+def test_get_tree_size(path):
+ os.makedirs(path('deeper'))
+ mkfile(path('one.txt'), '1')
+ mkfile(path('deeper/two.txt'), '22')
assert library.python.fs.get_tree_size(path('one.txt')) == 1
assert library.python.fs.get_tree_size(path('')) == 1
assert library.python.fs.get_tree_size(path(''), recursive=True) == 3
-
-
+
+
@pytest.mark.skipif(library.python.windows.on_win(), reason='Symlinks disabled on Windows')
-@in_env
-def test_get_tree_size_dangling_symlink(path):
- os.makedirs(path('deeper'))
- mkfile(path('one.txt'), '1')
- mkfile(path('deeper/two.txt'), '22')
- os.symlink(path('deeper/two.txt'), path("deeper/link.txt"))
- os.remove(path('deeper/two.txt'))
- # does not fail
+@in_env
+def test_get_tree_size_dangling_symlink(path):
+ os.makedirs(path('deeper'))
+ mkfile(path('one.txt'), '1')
+ mkfile(path('deeper/two.txt'), '22')
+ os.symlink(path('deeper/two.txt'), path("deeper/link.txt"))
+ os.remove(path('deeper/two.txt'))
+ # does not fail
assert library.python.fs.get_tree_size(path(''), recursive=True) == 1
diff --git a/library/python/pytest/allure/ya.make b/library/python/pytest/allure/ya.make
index cd1517f45d..ab3f449c7f 100644
--- a/library/python/pytest/allure/ya.make
+++ b/library/python/pytest/allure/ya.make
@@ -2,10 +2,10 @@ PY23_LIBRARY()
OWNER(exprmntr)
-PY_SRCS(conftest.py)
-
-PEERDIR(
- contrib/python/pytest-allure-adaptor
+PY_SRCS(conftest.py)
+
+PEERDIR(
+ contrib/python/pytest-allure-adaptor
)
END()
diff --git a/library/python/pytest/empty/ya.make b/library/python/pytest/empty/ya.make
index 5d9e5771f7..8f0fa37e2a 100644
--- a/library/python/pytest/empty/ya.make
+++ b/library/python/pytest/empty/ya.make
@@ -1,12 +1,12 @@
LIBRARY()
-OWNER(
- g:yatool
- dmitko
-)
+OWNER(
+ g:yatool
+ dmitko
+)
-SRCS(
- main.c
-)
+SRCS(
+ main.c
+)
END()
diff --git a/library/python/pytest/ya.make b/library/python/pytest/ya.make
index d74715d981..060c92c313 100644
--- a/library/python/pytest/ya.make
+++ b/library/python/pytest/ya.make
@@ -1,9 +1,9 @@
PY23_LIBRARY()
-OWNER(
- g:yatool
- dmitko
-)
+OWNER(
+ g:yatool
+ dmitko
+)
PY_SRCS(
__init__.py
diff --git a/library/python/pytest/yatest_tools.py b/library/python/pytest/yatest_tools.py
index 9dc1ed6943..6b8b896394 100644
--- a/library/python/pytest/yatest_tools.py
+++ b/library/python/pytest/yatest_tools.py
@@ -233,10 +233,10 @@ def get_python_cmd(opts=None, use_huge=True, suite=None):
return ["python"]
if suite and not suite._use_arcadia_python:
return ["python"]
- if use_huge:
- return ["$(PYTHON)/python"]
- ymake_path = opts.ymake_bin if opts and getattr(opts, 'ymake_bin', None) else "$(YMAKE)/ymake"
- return [ymake_path, "--python"]
+ if use_huge:
+ return ["$(PYTHON)/python"]
+ ymake_path = opts.ymake_bin if opts and getattr(opts, 'ymake_bin', None) else "$(YMAKE)/ymake"
+ return [ymake_path, "--python"]
def normalize_name(name):
diff --git a/library/python/reservoir_sampling/ya.make b/library/python/reservoir_sampling/ya.make
index 12867ce8b1..24cac20157 100644
--- a/library/python/reservoir_sampling/ya.make
+++ b/library/python/reservoir_sampling/ya.make
@@ -5,6 +5,6 @@ OWNER(
PY23_LIBRARY()
-PY_SRCS(__init__.py)
+PY_SRCS(__init__.py)
END()
diff --git a/library/python/resource/ut/lib/ya.make b/library/python/resource/ut/lib/ya.make
index a0d7697e8d..693e388878 100644
--- a/library/python/resource/ut/lib/ya.make
+++ b/library/python/resource/ut/lib/ya.make
@@ -2,7 +2,7 @@ PY23_LIBRARY()
OWNER(pg)
-TEST_SRCS(test_simple.py)
+TEST_SRCS(test_simple.py)
PEERDIR(
library/python/resource
diff --git a/library/python/resource/ya.make b/library/python/resource/ya.make
index 7306bd4c1b..989329fa4b 100644
--- a/library/python/resource/ya.make
+++ b/library/python/resource/ya.make
@@ -6,8 +6,8 @@ PEERDIR(
contrib/python/six
)
-PY_SRCS(__init__.py)
+PY_SRCS(__init__.py)
END()
-
-RECURSE_FOR_TESTS(ut)
+
+RECURSE_FOR_TESTS(ut)
diff --git a/library/python/runtime_py3/main/ya.make b/library/python/runtime_py3/main/ya.make
index 9ddf6cf912..f308a93b28 100644
--- a/library/python/runtime_py3/main/ya.make
+++ b/library/python/runtime_py3/main/ya.make
@@ -1,9 +1,9 @@
LIBRARY()
-OWNER(
- pg
- orivej
-)
+OWNER(
+ pg
+ orivej
+)
PEERDIR(
contrib/tools/python3/src
diff --git a/library/python/runtime_py3/test/traceback/ya.make b/library/python/runtime_py3/test/traceback/ya.make
index bf269bb447..b61fe9550b 100644
--- a/library/python/runtime_py3/test/traceback/ya.make
+++ b/library/python/runtime_py3/test/traceback/ya.make
@@ -1,17 +1,17 @@
PY3_PROGRAM()
-OWNER(
- abodrov
- borman
-)
+OWNER(
+ abodrov
+ borman
+)
PEERDIR(
contrib/python/ipython
)
PY_SRCS(
- MAIN
- __main__.py=main
+ MAIN
+ __main__.py=main
crash.py
mod/__init__.py
)
diff --git a/library/python/runtime_py3/test/ya.make b/library/python/runtime_py3/test/ya.make
index 5c0197e99c..4ec3db74f5 100644
--- a/library/python/runtime_py3/test/ya.make
+++ b/library/python/runtime_py3/test/ya.make
@@ -1,11 +1,11 @@
PY3TEST()
-OWNER(
- abodrov
- borman
+OWNER(
+ abodrov
+ borman
)
-DEPENDS(library/python/runtime_py3/test/traceback)
+DEPENDS(library/python/runtime_py3/test/traceback)
PEERDIR(
contrib/python/parameterized
@@ -17,7 +17,7 @@ PY_SRCS(
resources/__init__.py
resources/submodule/__init__.py
)
-
+
TEST_SRCS(
test_metadata.py
test_resources.py
diff --git a/library/python/runtime_py3/ya.make b/library/python/runtime_py3/ya.make
index 507ad14c40..fa5c11341a 100644
--- a/library/python/runtime_py3/ya.make
+++ b/library/python/runtime_py3/ya.make
@@ -1,10 +1,10 @@
PY3_LIBRARY()
-OWNER(
- borman
- orivej
- pg
-)
+OWNER(
+ borman
+ orivej
+ pg
+)
NO_WSHADOW()
@@ -14,7 +14,7 @@ PEERDIR(
library/cpp/resource
)
-CFLAGS(-DCYTHON_REGISTER_ABCS=0)
+CFLAGS(-DCYTHON_REGISTER_ABCS=0)
NO_PYTHON_INCLUDES()
diff --git a/library/python/strings/strings.py b/library/python/strings/strings.py
index cb903be611..5bfddfe78a 100644
--- a/library/python/strings/strings.py
+++ b/library/python/strings/strings.py
@@ -1,17 +1,17 @@
-import locale
-import logging
+import locale
+import logging
import six
-import sys
+import sys
import codecs
-
+
import library.python.func
-
+
logger = logging.getLogger(__name__)
-
+
DEFAULT_ENCODING = 'utf-8'
-ENCODING_ERRORS_POLICY = 'replace'
-
+ENCODING_ERRORS_POLICY = 'replace'
+
def left_strip(el, prefix):
"""
@@ -20,29 +20,29 @@ def left_strip(el, prefix):
if el.startswith(prefix):
return el[len(prefix):]
return el
-
-
-# Explicit to-text conversion
+
+
+# Explicit to-text conversion
# Chooses between str/unicode, i.e. six.binary_type/six.text_type
-def to_basestring(value):
+def to_basestring(value):
if isinstance(value, (six.binary_type, six.text_type)):
- return value
- try:
+ return value
+ try:
if six.PY2:
return unicode(value)
else:
return str(value)
- except UnicodeDecodeError:
- try:
- return str(value)
- except UnicodeEncodeError:
- return repr(value)
-to_text = to_basestring
-
-
+ except UnicodeDecodeError:
+ try:
+ return str(value)
+ except UnicodeEncodeError:
+ return repr(value)
+to_text = to_basestring
+
+
def to_unicode(value, from_enc=DEFAULT_ENCODING):
if isinstance(value, six.text_type):
- return value
+ return value
if isinstance(value, six.binary_type):
if six.PY2:
return unicode(value, from_enc, ENCODING_ERRORS_POLICY)
@@ -51,23 +51,23 @@ def to_unicode(value, from_enc=DEFAULT_ENCODING):
return six.text_type(value)
-# Optional from_enc enables transcoding
+# Optional from_enc enables transcoding
def to_str(value, to_enc=DEFAULT_ENCODING, from_enc=None):
if isinstance(value, six.binary_type):
- if from_enc is None or to_enc == from_enc:
- # Unknown input encoding or input and output encoding are the same
- return value
- value = to_unicode(value, from_enc=from_enc)
+ if from_enc is None or to_enc == from_enc:
+ # Unknown input encoding or input and output encoding are the same
+ return value
+ value = to_unicode(value, from_enc=from_enc)
if isinstance(value, six.text_type):
- return value.encode(to_enc, ENCODING_ERRORS_POLICY)
+ return value.encode(to_enc, ENCODING_ERRORS_POLICY)
return six.binary_type(value)
-
-
+
+
def _convert_deep(x, enc, convert, relaxed=True):
- if x is None:
- return None
+ if x is None:
+ return None
if isinstance(x, (six.text_type, six.binary_type)):
- return convert(x, enc)
+ return convert(x, enc)
if isinstance(x, dict):
return {convert(k, enc): _convert_deep(v, enc, convert, relaxed) for k, v in six.iteritems(x)}
if isinstance(x, list):
@@ -82,15 +82,15 @@ def _convert_deep(x, enc, convert, relaxed=True):
def unicodize_deep(x, enc=DEFAULT_ENCODING, relaxed=True):
return _convert_deep(x, enc, to_unicode, relaxed)
-
-
+
+
def stringize_deep(x, enc=DEFAULT_ENCODING, relaxed=True):
return _convert_deep(x, enc, to_str, relaxed)
-
-
+
+
@library.python.func.memoize()
-def locale_encoding():
- try:
+def locale_encoding():
+ try:
loc = locale.getdefaultlocale()[1]
if loc:
codecs.lookup(loc)
@@ -98,17 +98,17 @@ def locale_encoding():
except LookupError as e:
logger.debug('Cannot get system locale: %s', e)
return None
- except ValueError as e:
+ except ValueError as e:
logger.warn('Cannot get system locale: %s', e)
- return None
-
-
-def fs_encoding():
- return sys.getfilesystemencoding()
-
-
-def guess_default_encoding():
- enc = locale_encoding()
+ return None
+
+
+def fs_encoding():
+ return sys.getfilesystemencoding()
+
+
+def guess_default_encoding():
+ enc = locale_encoding()
return enc if enc else DEFAULT_ENCODING
diff --git a/library/python/strings/ut/test_strings.py b/library/python/strings/ut/test_strings.py
index 0ec4fb5d79..dd0c694ee1 100644
--- a/library/python/strings/ut/test_strings.py
+++ b/library/python/strings/ut/test_strings.py
@@ -1,37 +1,37 @@
-# coding=utf-8
-
-import pytest
+# coding=utf-8
+
+import pytest
import six
-
+
import library.python.strings
-
-
-class Convertible(object):
- text = u'текст'
- text_utf8 = text.encode('utf-8')
-
- def __unicode__(self):
- return self.text
-
- def __str__(self):
- return self.text_utf8
-
-
-class ConvertibleToUnicodeOnly(Convertible):
- def __str__(self):
- return self.text.encode('ascii')
-
-
-class ConvertibleToStrOnly(Convertible):
- def __unicode__(self):
- return self.text_utf8.decode('ascii')
-
-
-class NonConvertible(ConvertibleToUnicodeOnly, ConvertibleToStrOnly):
- pass
-
-
-def test_to_basestring():
+
+
+class Convertible(object):
+ text = u'текст'
+ text_utf8 = text.encode('utf-8')
+
+ def __unicode__(self):
+ return self.text
+
+ def __str__(self):
+ return self.text_utf8
+
+
+class ConvertibleToUnicodeOnly(Convertible):
+ def __str__(self):
+ return self.text.encode('ascii')
+
+
+class ConvertibleToStrOnly(Convertible):
+ def __unicode__(self):
+ return self.text_utf8.decode('ascii')
+
+
+class NonConvertible(ConvertibleToUnicodeOnly, ConvertibleToStrOnly):
+ pass
+
+
+def test_to_basestring():
assert library.python.strings.to_basestring('str') == 'str'
assert library.python.strings.to_basestring(u'юникод') == u'юникод'
if six.PY2: # __str__ should return str not bytes in Python3
@@ -39,9 +39,9 @@ def test_to_basestring():
assert library.python.strings.to_basestring(ConvertibleToUnicodeOnly()) == Convertible.text
assert library.python.strings.to_basestring(ConvertibleToStrOnly()) == Convertible.text_utf8
assert library.python.strings.to_basestring(NonConvertible())
-
-
-def test_to_unicode():
+
+
+def test_to_unicode():
assert library.python.strings.to_unicode(u'юникод') == u'юникод'
assert library.python.strings.to_unicode('str') == u'str'
assert library.python.strings.to_unicode(u'строка'.encode('utf-8')) == u'строка'
@@ -53,14 +53,14 @@ def test_to_unicode():
library.python.strings.to_unicode(ConvertibleToStrOnly())
with pytest.raises(UnicodeDecodeError):
library.python.strings.to_unicode(NonConvertible())
-
-
-def test_to_unicode_errors_replace():
+
+
+def test_to_unicode_errors_replace():
assert library.python.strings.to_unicode(u'abcабв'.encode('utf-8'), 'ascii')
assert library.python.strings.to_unicode(u'абв'.encode('utf-8'), 'ascii')
-
-
-def test_to_str():
+
+
+def test_to_str():
assert library.python.strings.to_str('str') == 'str' if six.PY2 else b'str'
assert library.python.strings.to_str(u'unicode') == 'unicode' if six.PY2 else b'unicode'
assert library.python.strings.to_str(u'юникод') == u'юникод'.encode('utf-8')
@@ -72,134 +72,134 @@ def test_to_str():
assert library.python.strings.to_str(ConvertibleToStrOnly()) == Convertible.text_utf8
with pytest.raises(UnicodeEncodeError):
library.python.strings.to_str(NonConvertible())
-
-
-def test_to_str_errors_replace():
+
+
+def test_to_str_errors_replace():
assert library.python.strings.to_str(u'abcабв', 'ascii')
assert library.python.strings.to_str(u'абв', 'ascii')
-
-
-def test_to_str_transcode():
+
+
+def test_to_str_transcode():
assert library.python.strings.to_str('str', from_enc='ascii') == 'str' if six.PY2 else b'str'
assert library.python.strings.to_str('str', from_enc='utf-8') == 'str' if six.PY2 else b'str'
-
+
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), from_enc='utf-8') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), to_enc='utf-8', from_enc='utf-8') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), to_enc='cp1251', from_enc='utf-8') == u'юникод'.encode('cp1251')
-
+
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), from_enc='cp1251') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), to_enc='cp1251', from_enc='cp1251') == u'юникод'.encode('cp1251')
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), to_enc='utf-8', from_enc='cp1251') == u'юникод'.encode('utf-8')
-
+
assert library.python.strings.to_str(u'юникод'.encode('koi8-r'), from_enc='koi8-r') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('koi8-r'), to_enc='koi8-r', from_enc='koi8-r') == u'юникод'.encode('koi8-r')
assert library.python.strings.to_str(u'юникод'.encode('koi8-r'), to_enc='cp1251', from_enc='koi8-r') == u'юникод'.encode('cp1251')
-
-
-def test_to_str_transcode_wrong():
+
+
+def test_to_str_transcode_wrong():
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), from_enc='cp1251')
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), from_enc='utf-8')
-
-
-def test_to_str_transcode_disabled():
- # No transcoding enabled, set from_enc to enable
+
+
+def test_to_str_transcode_disabled():
+ # No transcoding enabled, set from_enc to enable
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), to_enc='utf-8') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), to_enc='cp1251') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), to_enc='utf-8') == u'юникод'.encode('cp1251')
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), to_enc='cp1251') == u'юникод'.encode('cp1251')
assert library.python.strings.to_str(u'юникод'.encode('cp1251'), to_enc='koi8-r') == u'юникод'.encode('cp1251')
assert library.python.strings.to_str(u'юникод'.encode('koi8-r'), to_enc='cp1251') == u'юникод'.encode('koi8-r')
-
-
-def test_stringize_deep():
+
+
+def test_stringize_deep():
assert library.python.strings.stringize_deep({
- 'key 1': 'value 1',
- u'ключ 2': u'значение 2',
+ 'key 1': 'value 1',
+ u'ключ 2': u'значение 2',
'list': [u'ключ 2', 'key 1', (u'к', 2)]
- }) == {
+ }) == {
'key 1' if six.PY2 else b'key 1': 'value 1' if six.PY2 else b'value 1',
- u'ключ 2'.encode('utf-8'): u'значение 2'.encode('utf-8'),
+ u'ключ 2'.encode('utf-8'): u'значение 2'.encode('utf-8'),
'list' if six.PY2 else b'list': [u'ключ 2'.encode('utf-8'), 'key 1' if six.PY2 else b'key 1', (u'к'.encode('utf-8'), 2)]
- }
-
-
-def test_stringize_deep_doesnt_transcode():
+ }
+
+
+def test_stringize_deep_doesnt_transcode():
assert library.python.strings.stringize_deep({
- u'ключ 1'.encode('utf-8'): u'значение 1'.encode('utf-8'),
- u'ключ 2'.encode('cp1251'): u'значение 2'.encode('cp1251'),
- }) == {
- u'ключ 1'.encode('utf-8'): u'значение 1'.encode('utf-8'),
- u'ключ 2'.encode('cp1251'): u'значение 2'.encode('cp1251'),
- }
-
-
-def test_stringize_deep_nested():
+ u'ключ 1'.encode('utf-8'): u'значение 1'.encode('utf-8'),
+ u'ключ 2'.encode('cp1251'): u'значение 2'.encode('cp1251'),
+ }) == {
+ u'ключ 1'.encode('utf-8'): u'значение 1'.encode('utf-8'),
+ u'ключ 2'.encode('cp1251'): u'значение 2'.encode('cp1251'),
+ }
+
+
+def test_stringize_deep_nested():
assert library.python.strings.stringize_deep({
- 'key 1': 'value 1',
- u'ключ 2': {
- 'subkey 1': 'value 1',
- u'подключ 2': u'value 2',
- },
- }) == {
+ 'key 1': 'value 1',
+ u'ключ 2': {
+ 'subkey 1': 'value 1',
+ u'подключ 2': u'value 2',
+ },
+ }) == {
'key 1' if six.PY2 else b'key 1': 'value 1' if six.PY2 else b'value 1',
- u'ключ 2'.encode('utf-8'): {
+ u'ключ 2'.encode('utf-8'): {
'subkey 1' if six.PY2 else b'subkey 1': 'value 1' if six.PY2 else b'value 1',
- u'подключ 2'.encode('utf-8'): u'value 2'.encode('utf-8'),
- },
- }
-
-
-def test_stringize_deep_plain():
+ u'подключ 2'.encode('utf-8'): u'value 2'.encode('utf-8'),
+ },
+ }
+
+
+def test_stringize_deep_plain():
assert library.python.strings.stringize_deep('str') == 'str' if six.PY2 else b'str'
assert library.python.strings.stringize_deep(u'юникод') == u'юникод'.encode('utf-8')
assert library.python.strings.stringize_deep(u'юникод'.encode('utf-8')) == u'юникод'.encode('utf-8')
-
-
-def test_stringize_deep_nonstr():
- with pytest.raises(TypeError):
+
+
+def test_stringize_deep_nonstr():
+ with pytest.raises(TypeError):
library.python.strings.stringize_deep(Convertible(), relaxed=False)
x = Convertible()
assert x == library.python.strings.stringize_deep(x)
-
-
-def test_unicodize_deep():
+
+
+def test_unicodize_deep():
assert library.python.strings.unicodize_deep({
- 'key 1': 'value 1',
- u'ключ 2': u'значение 2',
- u'ключ 3'.encode('utf-8'): u'значение 3'.encode('utf-8'),
- }) == {
- u'key 1': u'value 1',
- u'ключ 2': u'значение 2',
- u'ключ 3': u'значение 3',
- }
-
-
-def test_unicodize_deep_nested():
+ 'key 1': 'value 1',
+ u'ключ 2': u'значение 2',
+ u'ключ 3'.encode('utf-8'): u'значение 3'.encode('utf-8'),
+ }) == {
+ u'key 1': u'value 1',
+ u'ключ 2': u'значение 2',
+ u'ключ 3': u'значение 3',
+ }
+
+
+def test_unicodize_deep_nested():
assert library.python.strings.unicodize_deep({
- 'key 1': 'value 1',
- u'ключ 2': {
- 'subkey 1': 'value 1',
- u'подключ 2': u'значение 2',
- u'подключ 3'.encode('utf-8'): u'значение 3'.encode('utf-8'),
- },
- }) == {
- u'key 1': u'value 1',
- u'ключ 2': {
- u'subkey 1': u'value 1',
- u'подключ 2': u'значение 2',
- u'подключ 3': u'значение 3',
- },
- }
-
-
-def test_unicodize_deep_plain():
+ 'key 1': 'value 1',
+ u'ключ 2': {
+ 'subkey 1': 'value 1',
+ u'подключ 2': u'значение 2',
+ u'подключ 3'.encode('utf-8'): u'значение 3'.encode('utf-8'),
+ },
+ }) == {
+ u'key 1': u'value 1',
+ u'ключ 2': {
+ u'subkey 1': u'value 1',
+ u'подключ 2': u'значение 2',
+ u'подключ 3': u'значение 3',
+ },
+ }
+
+
+def test_unicodize_deep_plain():
assert library.python.strings.unicodize_deep('str') == u'str'
assert library.python.strings.unicodize_deep(u'юникод') == u'юникод'
assert library.python.strings.unicodize_deep(u'юникод'.encode('utf-8')) == u'юникод'
-
-
-def test_unicodize_deep_nonstr():
- with pytest.raises(TypeError):
+
+
+def test_unicodize_deep_nonstr():
+ with pytest.raises(TypeError):
library.python.strings.unicodize_deep(Convertible(), relaxed=False)
x = Convertible()
assert x == library.python.strings.stringize_deep(x)
diff --git a/library/python/strings/ut/ya.make b/library/python/strings/ut/ya.make
index adbeb9a054..dfacb226c7 100644
--- a/library/python/strings/ut/ya.make
+++ b/library/python/strings/ut/ya.make
@@ -2,7 +2,7 @@ OWNER(g:yatool)
PY23_TEST()
-TEST_SRCS(test_strings.py)
+TEST_SRCS(test_strings.py)
PEERDIR(
library/python/strings
diff --git a/library/python/strings/ya.make b/library/python/strings/ya.make
index eee89ae7dc..7e0b033717 100644
--- a/library/python/strings/ya.make
+++ b/library/python/strings/ya.make
@@ -8,9 +8,9 @@ PY_SRCS(
strings.py
)
-PEERDIR(
- library/python/func
+PEERDIR(
+ library/python/func
contrib/python/six
-)
+)
END()
diff --git a/library/python/symbols/python/ut/ya.make b/library/python/symbols/python/ut/ya.make
index ba20bf0237..2849e01b1e 100644
--- a/library/python/symbols/python/ut/ya.make
+++ b/library/python/symbols/python/ut/ya.make
@@ -2,14 +2,14 @@ PY23_LIBRARY()
OWNER(orivej)
-TEST_SRCS(test_ctypes.py)
+TEST_SRCS(test_ctypes.py)
PEERDIR(
library/python/symbols/python
)
END()
-
+
RECURSE_FOR_TESTS(
py2
py3
diff --git a/library/python/symbols/python/ya.make b/library/python/symbols/python/ya.make
index 7762f87592..6bfd54f8bc 100644
--- a/library/python/symbols/python/ya.make
+++ b/library/python/symbols/python/ya.make
@@ -11,5 +11,5 @@ SRCS(
)
END()
-
-RECURSE_FOR_TESTS(ut)
+
+RECURSE_FOR_TESTS(ut)
diff --git a/library/python/testing/import_test/ya.make b/library/python/testing/import_test/ya.make
index 68b147a00c..fae36ffe8f 100644
--- a/library/python/testing/import_test/ya.make
+++ b/library/python/testing/import_test/ya.make
@@ -1,7 +1,7 @@
-OWNER(
+OWNER(
g:yatest
- exprmntr
-)
+ exprmntr
+)
PY23_LIBRARY()
diff --git a/library/python/testing/recipe/ya.make b/library/python/testing/recipe/ya.make
index d6fa84a873..dd323aa245 100644
--- a/library/python/testing/recipe/ya.make
+++ b/library/python/testing/recipe/ya.make
@@ -1,7 +1,7 @@
-OWNER(
- exprmntr
+OWNER(
+ exprmntr
g:yatest
-)
+)
PY23_LIBRARY()
diff --git a/library/python/testing/yatest_common/yatest/common/canonical.py b/library/python/testing/yatest_common/yatest/common/canonical.py
index 443a5106ea..b6a136d3e9 100644
--- a/library/python/testing/yatest_common/yatest/common/canonical.py
+++ b/library/python/testing/yatest_common/yatest/common/canonical.py
@@ -12,22 +12,22 @@ from . import path
yatest_logger = logging.getLogger("ya.test")
-def _copy(src, dst, universal_lines=False):
- if universal_lines:
- with open(dst, "wb") as f:
+def _copy(src, dst, universal_lines=False):
+ if universal_lines:
+ with open(dst, "wb") as f:
for line in open(src, "rbU"):
- f.write(line)
- return
- shutil.copy(src, dst)
-
-
+ f.write(line)
+ return
+ shutil.copy(src, dst)
+
+
def canonical_file(path, diff_tool=None, local=False, universal_lines=False, diff_file_name=None, diff_tool_timeout=None):
"""
Create canonical file that can be returned from a test
:param path: path to the file
:param diff_tool: custom diff tool to use for comparison with the canonical one, if None - default will be used
:param local: save file locally, otherwise move to sandbox
- :param universal_lines: normalize EOL
+ :param universal_lines: normalize EOL
:param diff_tool_timeout: timeout for running diff tool
:return: object that can be canonized
"""
@@ -36,7 +36,7 @@ def canonical_file(path, diff_tool=None, local=False, universal_lines=False, dif
tempdir = tempfile.mkdtemp(prefix="canon_tmp", dir=runtime.build_path())
safe_path = os.path.join(tempdir, os.path.basename(abs_path))
# if the created file is in output_path, we copy it, so that it will be available when the tests finishes
- _copy(path, safe_path, universal_lines=universal_lines)
+ _copy(path, safe_path, universal_lines=universal_lines)
if diff_tool:
if not isinstance(diff_tool, six.string_types):
try: # check if iterable
diff --git a/library/python/testing/yatest_common/yatest/common/network.py b/library/python/testing/yatest_common/yatest/common/network.py
index 291aa49151..37bcb1b8e0 100644
--- a/library/python/testing/yatest_common/yatest/common/network.py
+++ b/library/python/testing/yatest_common/yatest/common/network.py
@@ -1,4 +1,4 @@
-# coding=utf-8
+# coding=utf-8
import os
import errno
diff --git a/library/python/testing/yatest_common/yatest/common/path.py b/library/python/testing/yatest_common/yatest/common/path.py
index 079770605e..6fed7dda8a 100644
--- a/library/python/testing/yatest_common/yatest/common/path.py
+++ b/library/python/testing/yatest_common/yatest/common/path.py
@@ -1,4 +1,4 @@
-# coding=utf-8
+# coding=utf-8
import errno
import os
diff --git a/library/python/testing/yatest_lib/ya.make b/library/python/testing/yatest_lib/ya.make
index 7453e5b665..342bae82ba 100644
--- a/library/python/testing/yatest_lib/ya.make
+++ b/library/python/testing/yatest_lib/ya.make
@@ -3,8 +3,8 @@ OWNER(g:yatest)
PY23_LIBRARY()
PY_SRCS(
- NAMESPACE
- yatest_lib
+ NAMESPACE
+ yatest_lib
external.py
test_splitter.py
tools.py
diff --git a/library/python/windows/__init__.py b/library/python/windows/__init__.py
index 2e426f2bd8..62861b3309 100644
--- a/library/python/windows/__init__.py
+++ b/library/python/windows/__init__.py
@@ -1,290 +1,290 @@
# coding: utf-8
-import os
+import os
import stat
import sys
import shutil
import logging
-
+
from six import reraise
import library.python.func
import library.python.strings
-
+
logger = logging.getLogger(__name__)
-
-ERRORS = {
- 'SUCCESS': 0,
+
+ERRORS = {
+ 'SUCCESS': 0,
'PATH_NOT_FOUND': 3,
'ACCESS_DENIED': 5,
'SHARING_VIOLATION': 32,
- 'INSUFFICIENT_BUFFER': 122,
- 'DIR_NOT_EMPTY': 145,
-}
-
+ 'INSUFFICIENT_BUFFER': 122,
+ 'DIR_NOT_EMPTY': 145,
+}
+
RETRIABLE_FILE_ERRORS = (ERRORS['ACCESS_DENIED'], ERRORS['SHARING_VIOLATION'])
RETRIABLE_DIR_ERRORS = (ERRORS['ACCESS_DENIED'], ERRORS['DIR_NOT_EMPTY'], ERRORS['SHARING_VIOLATION'])
-
-# Check if on Windows
+
+# Check if on Windows
@library.python.func.lazy
-def on_win():
- return os.name == 'nt'
-
-
-class NotOnWindowsError(RuntimeError):
- def __init__(self, message):
- super(NotOnWindowsError, self).__init__(message)
-
-
-class DisabledOnWindowsError(RuntimeError):
- def __init__(self, message):
- super(DisabledOnWindowsError, self).__init__(message)
-
-
-class NoCTypesError(RuntimeError):
- def __init__(self, message):
- super(NoCTypesError, self).__init__(message)
-
-
-# Decorator for Windows-only functions
-def win_only(f):
- def f_wrapped(*args, **kwargs):
- if not on_win():
- raise NotOnWindowsError('Windows-only function is called, but platform is not Windows')
- return f(*args, **kwargs)
-
- return f_wrapped
-
-
-# Decorator for functions disabled on Windows
-def win_disabled(f):
- def f_wrapped(*args, **kwargs):
- if on_win():
- run_disabled()
- return f(*args, **kwargs)
-
- return f_wrapped
-
-
-def errorfix(f):
- if not on_win():
- return f
-
- def f_wrapped(*args, **kwargs):
- try:
- return f(*args, **kwargs)
+def on_win():
+ return os.name == 'nt'
+
+
+class NotOnWindowsError(RuntimeError):
+ def __init__(self, message):
+ super(NotOnWindowsError, self).__init__(message)
+
+
+class DisabledOnWindowsError(RuntimeError):
+ def __init__(self, message):
+ super(DisabledOnWindowsError, self).__init__(message)
+
+
+class NoCTypesError(RuntimeError):
+ def __init__(self, message):
+ super(NoCTypesError, self).__init__(message)
+
+
+# Decorator for Windows-only functions
+def win_only(f):
+ def f_wrapped(*args, **kwargs):
+ if not on_win():
+ raise NotOnWindowsError('Windows-only function is called, but platform is not Windows')
+ return f(*args, **kwargs)
+
+ return f_wrapped
+
+
+# Decorator for functions disabled on Windows
+def win_disabled(f):
+ def f_wrapped(*args, **kwargs):
+ if on_win():
+ run_disabled()
+ return f(*args, **kwargs)
+
+ return f_wrapped
+
+
+def errorfix(f):
+ if not on_win():
+ return f
+
+ def f_wrapped(*args, **kwargs):
+ try:
+ return f(*args, **kwargs)
except WindowsError:
tp, value, tb = sys.exc_info()
fix_error(value)
reraise(tp, value, tb)
-
- return f_wrapped
-
-
-# Decorator for diehard wrapper
-# On Windows platform retries to run function while specific WindowsError is thrown
-# On non-Windows platforms fallbacks to function itself
-def diehard(winerrors, tries=100, delay=1):
- def wrap(f):
- if not on_win():
- return f
-
- return lambda *args, **kwargs: run_diehard(f, winerrors, tries, delay, *args, **kwargs)
-
- return wrap
-
-
-if on_win():
- import msvcrt
- import time
-
+
+ return f_wrapped
+
+
+# Decorator for diehard wrapper
+# On Windows platform retries to run function while specific WindowsError is thrown
+# On non-Windows platforms fallbacks to function itself
+def diehard(winerrors, tries=100, delay=1):
+ def wrap(f):
+ if not on_win():
+ return f
+
+ return lambda *args, **kwargs: run_diehard(f, winerrors, tries, delay, *args, **kwargs)
+
+ return wrap
+
+
+if on_win():
+ import msvcrt
+ import time
+
import library.python.strings
-
- _has_ctypes = True
- try:
- import ctypes
+
+ _has_ctypes = True
+ try:
+ import ctypes
from ctypes import wintypes
- except ImportError:
- _has_ctypes = False
-
- _INVALID_HANDLE_VALUE = -1
-
- _MOVEFILE_REPLACE_EXISTING = 0x1
- _MOVEFILE_WRITE_THROUGH = 0x8
-
- _SEM_FAILCRITICALERRORS = 0x1
- _SEM_NOGPFAULTERRORBOX = 0x2
- _SEM_NOALIGNMENTFAULTEXCEPT = 0x4
- _SEM_NOOPENFILEERRORBOX = 0x8
-
- _SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1
-
- _CREATE_NO_WINDOW = 0x8000000
-
- _ATOMIC_RENAME_FILE_TRANSACTION_DEFAULT_TIMEOUT = 1000
-
+ except ImportError:
+ _has_ctypes = False
+
+ _INVALID_HANDLE_VALUE = -1
+
+ _MOVEFILE_REPLACE_EXISTING = 0x1
+ _MOVEFILE_WRITE_THROUGH = 0x8
+
+ _SEM_FAILCRITICALERRORS = 0x1
+ _SEM_NOGPFAULTERRORBOX = 0x2
+ _SEM_NOALIGNMENTFAULTEXCEPT = 0x4
+ _SEM_NOOPENFILEERRORBOX = 0x8
+
+ _SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1
+
+ _CREATE_NO_WINDOW = 0x8000000
+
+ _ATOMIC_RENAME_FILE_TRANSACTION_DEFAULT_TIMEOUT = 1000
+
_HANDLE_FLAG_INHERIT = 0x1
- @win_only
- def require_ctypes(f):
- def f_wrapped(*args, **kwargs):
- if not _has_ctypes:
- raise NoCTypesError('No ctypes found')
- return f(*args, **kwargs)
-
- return f_wrapped
-
- # Run function in diehard mode (see diehard decorator commentary)
- @win_only
- def run_diehard(f, winerrors, tries, delay, *args, **kwargs):
- if isinstance(winerrors, int):
- winerrors = (winerrors,)
+ @win_only
+ def require_ctypes(f):
+ def f_wrapped(*args, **kwargs):
+ if not _has_ctypes:
+ raise NoCTypesError('No ctypes found')
+ return f(*args, **kwargs)
+
+ return f_wrapped
+
+ # Run function in diehard mode (see diehard decorator commentary)
+ @win_only
+ def run_diehard(f, winerrors, tries, delay, *args, **kwargs):
+ if isinstance(winerrors, int):
+ winerrors = (winerrors,)
ei = None
- for t in xrange(tries):
- if t:
+ for t in xrange(tries):
+ if t:
logger.debug('Diehard [errs %s]: try #%d in %s', ','.join(str(x) for x in winerrors), t, f)
- try:
- return f(*args, **kwargs)
- except WindowsError as e:
- if e.winerror not in winerrors:
- raise
+ try:
+ return f(*args, **kwargs)
+ except WindowsError as e:
+ if e.winerror not in winerrors:
+ raise
ei = sys.exc_info()
- time.sleep(delay)
+ time.sleep(delay)
reraise(ei[0], ei[1], ei[2])
-
- # Placeholder for disabled functions
- @win_only
- def run_disabled(*args, **kwargs):
- raise DisabledOnWindowsError('Function called is disabled on Windows')
-
- class CustomWinError(WindowsError):
- def __init__(self, winerror, message='', filename=None):
- super(CustomWinError, self).__init__(winerror, message)
- self.message = message
- self.strerror = self.message if self.message else format_error(self.windows_error)
- self.filename = filename
- self.utf8 = True
-
- @win_only
- def unicode_path(path):
+
+ # Placeholder for disabled functions
+ @win_only
+ def run_disabled(*args, **kwargs):
+ raise DisabledOnWindowsError('Function called is disabled on Windows')
+
+ class CustomWinError(WindowsError):
+ def __init__(self, winerror, message='', filename=None):
+ super(CustomWinError, self).__init__(winerror, message)
+ self.message = message
+ self.strerror = self.message if self.message else format_error(self.windows_error)
+ self.filename = filename
+ self.utf8 = True
+
+ @win_only
+ def unicode_path(path):
return library.python.strings.to_unicode(path, library.python.strings.fs_encoding())
-
- @win_only
- @require_ctypes
- def format_error(error):
- if isinstance(error, WindowsError):
- error = error.winerror
- if not isinstance(error, int):
- return 'Unknown'
- return ctypes.FormatError(error)
-
- @win_only
- def fix_error(windows_error):
- if not windows_error.strerror:
- windows_error.strerror = format_error(windows_error)
- transcode_error(windows_error)
-
- @win_only
- def transcode_error(windows_error, to_enc='utf-8'):
+
+ @win_only
+ @require_ctypes
+ def format_error(error):
+ if isinstance(error, WindowsError):
+ error = error.winerror
+ if not isinstance(error, int):
+ return 'Unknown'
+ return ctypes.FormatError(error)
+
+ @win_only
+ def fix_error(windows_error):
+ if not windows_error.strerror:
+ windows_error.strerror = format_error(windows_error)
+ transcode_error(windows_error)
+
+ @win_only
+ def transcode_error(windows_error, to_enc='utf-8'):
from_enc = 'utf-8' if getattr(windows_error, 'utf8', False) else library.python.strings.guess_default_encoding()
- if from_enc != to_enc:
+ if from_enc != to_enc:
windows_error.strerror = library.python.strings.to_str(windows_error.strerror, to_enc=to_enc, from_enc=from_enc)
- setattr(windows_error, 'utf8', to_enc == 'utf-8')
-
- class Transaction(object):
- def __init__(self, timeout=None, description=''):
- self.timeout = timeout
- self.description = description
-
- @require_ctypes
- def __enter__(self):
- self._handle = ctypes.windll.ktmw32.CreateTransaction(None, 0, 0, 0, 0, self.timeout, self.description)
- if self._handle == _INVALID_HANDLE_VALUE:
- raise ctypes.WinError()
- return self._handle
-
- @require_ctypes
- def __exit__(self, t, v, tb):
- try:
- if not ctypes.windll.ktmw32.CommitTransaction(self._handle):
- raise ctypes.WinError()
- finally:
- ctypes.windll.kernel32.CloseHandle(self._handle)
-
- @win_only
- def file_handle(f):
- return msvcrt.get_osfhandle(f.fileno())
-
+ setattr(windows_error, 'utf8', to_enc == 'utf-8')
+
+ class Transaction(object):
+ def __init__(self, timeout=None, description=''):
+ self.timeout = timeout
+ self.description = description
+
+ @require_ctypes
+ def __enter__(self):
+ self._handle = ctypes.windll.ktmw32.CreateTransaction(None, 0, 0, 0, 0, self.timeout, self.description)
+ if self._handle == _INVALID_HANDLE_VALUE:
+ raise ctypes.WinError()
+ return self._handle
+
+ @require_ctypes
+ def __exit__(self, t, v, tb):
+ try:
+ if not ctypes.windll.ktmw32.CommitTransaction(self._handle):
+ raise ctypes.WinError()
+ finally:
+ ctypes.windll.kernel32.CloseHandle(self._handle)
+
+ @win_only
+ def file_handle(f):
+ return msvcrt.get_osfhandle(f.fileno())
+
# https://www.python.org/dev/peps/pep-0446/
# http://mihalop.blogspot.ru/2014/05/python-subprocess-and-file-descriptors.html
@require_ctypes
- @win_only
+ @win_only
def open_file(*args, **kwargs):
f = open(*args, **kwargs)
ctypes.windll.kernel32.SetHandleInformation(file_handle(f), _HANDLE_FLAG_INHERIT, 0)
return f
@win_only
- @require_ctypes
- def replace_file(src, dst):
- if not ctypes.windll.kernel32.MoveFileExW(unicode_path(src), unicode_path(dst), _MOVEFILE_REPLACE_EXISTING | _MOVEFILE_WRITE_THROUGH):
- raise ctypes.WinError()
-
- @win_only
- @require_ctypes
- def replace_file_across_devices(src, dst):
+ @require_ctypes
+ def replace_file(src, dst):
+ if not ctypes.windll.kernel32.MoveFileExW(unicode_path(src), unicode_path(dst), _MOVEFILE_REPLACE_EXISTING | _MOVEFILE_WRITE_THROUGH):
+ raise ctypes.WinError()
+
+ @win_only
+ @require_ctypes
+ def replace_file_across_devices(src, dst):
with Transaction(timeout=_ATOMIC_RENAME_FILE_TRANSACTION_DEFAULT_TIMEOUT, description='ya library.python.windows replace_file_across_devices') as transaction:
- if not ctypes.windll.kernel32.MoveFileTransactedW(unicode_path(src), unicode_path(dst), None, None, _MOVEFILE_REPLACE_EXISTING | _MOVEFILE_WRITE_THROUGH, transaction):
- raise ctypes.WinError()
-
- @win_only
- @require_ctypes
- def hardlink(src, lnk):
- if not ctypes.windll.kernel32.CreateHardLinkW(unicode_path(lnk), unicode_path(src), None):
- raise ctypes.WinError()
-
- # Requires SE_CREATE_SYMBOLIC_LINK_NAME privilege
- @win_only
- @win_disabled
- @require_ctypes
- def symlink_file(src, lnk):
- if not ctypes.windll.kernel32.CreateSymbolicLinkW(unicode_path(lnk), unicode_path(src), 0):
- raise ctypes.WinError()
-
- # Requires SE_CREATE_SYMBOLIC_LINK_NAME privilege
- @win_only
- @win_disabled
- @require_ctypes
- def symlink_dir(src, lnk):
- if not ctypes.windll.kernel32.CreateSymbolicLinkW(unicode_path(lnk), unicode_path(src), _SYMBOLIC_LINK_FLAG_DIRECTORY):
- raise ctypes.WinError()
-
- @win_only
- @require_ctypes
- def lock_file(f, offset, length, raises=True):
- locked = ctypes.windll.kernel32.LockFile(file_handle(f), _low_dword(offset), _high_dword(offset), _low_dword(length), _high_dword(length))
- if not raises:
- return bool(locked)
- if not locked:
- raise ctypes.WinError()
-
- @win_only
- @require_ctypes
- def unlock_file(f, offset, length, raises=True):
- unlocked = ctypes.windll.kernel32.UnlockFile(file_handle(f), _low_dword(offset), _high_dword(offset), _low_dword(length), _high_dword(length))
- if not raises:
- return bool(unlocked)
- if not unlocked:
- raise ctypes.WinError()
-
- @win_only
- @require_ctypes
- def set_error_mode(mode):
- return ctypes.windll.kernel32.SetErrorMode(mode)
-
+ if not ctypes.windll.kernel32.MoveFileTransactedW(unicode_path(src), unicode_path(dst), None, None, _MOVEFILE_REPLACE_EXISTING | _MOVEFILE_WRITE_THROUGH, transaction):
+ raise ctypes.WinError()
+
+ @win_only
+ @require_ctypes
+ def hardlink(src, lnk):
+ if not ctypes.windll.kernel32.CreateHardLinkW(unicode_path(lnk), unicode_path(src), None):
+ raise ctypes.WinError()
+
+ # Requires SE_CREATE_SYMBOLIC_LINK_NAME privilege
+ @win_only
+ @win_disabled
+ @require_ctypes
+ def symlink_file(src, lnk):
+ if not ctypes.windll.kernel32.CreateSymbolicLinkW(unicode_path(lnk), unicode_path(src), 0):
+ raise ctypes.WinError()
+
+ # Requires SE_CREATE_SYMBOLIC_LINK_NAME privilege
+ @win_only
+ @win_disabled
+ @require_ctypes
+ def symlink_dir(src, lnk):
+ if not ctypes.windll.kernel32.CreateSymbolicLinkW(unicode_path(lnk), unicode_path(src), _SYMBOLIC_LINK_FLAG_DIRECTORY):
+ raise ctypes.WinError()
+
+ @win_only
+ @require_ctypes
+ def lock_file(f, offset, length, raises=True):
+ locked = ctypes.windll.kernel32.LockFile(file_handle(f), _low_dword(offset), _high_dword(offset), _low_dword(length), _high_dword(length))
+ if not raises:
+ return bool(locked)
+ if not locked:
+ raise ctypes.WinError()
+
+ @win_only
+ @require_ctypes
+ def unlock_file(f, offset, length, raises=True):
+ unlocked = ctypes.windll.kernel32.UnlockFile(file_handle(f), _low_dword(offset), _high_dword(offset), _low_dword(length), _high_dword(length))
+ if not raises:
+ return bool(unlocked)
+ if not unlocked:
+ raise ctypes.WinError()
+
+ @win_only
+ @require_ctypes
+ def set_error_mode(mode):
+ return ctypes.windll.kernel32.SetErrorMode(mode)
+
@win_only
def rmtree(path):
def error_handler(func, handling_path, execinfo):
@@ -306,23 +306,23 @@ if on_win():
raise e
shutil.rmtree(path, onerror=error_handler)
- # Don't display the Windows GPF dialog if the invoked program dies.
- # http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
- @win_only
- def disable_error_dialogs():
+ # Don't display the Windows GPF dialog if the invoked program dies.
+ # http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
+ @win_only
+ def disable_error_dialogs():
set_error_mode(_SEM_NOGPFAULTERRORBOX | _SEM_FAILCRITICALERRORS)
-
- @win_only
- def default_process_creation_flags():
- return 0
-
- @require_ctypes
- def _low_dword(x):
- return ctypes.c_ulong(x & ((1 << 32) - 1))
-
- @require_ctypes
- def _high_dword(x):
- return ctypes.c_ulong((x >> 32) & ((1 << 32) - 1))
+
+ @win_only
+ def default_process_creation_flags():
+ return 0
+
+ @require_ctypes
+ def _low_dword(x):
+ return ctypes.c_ulong(x & ((1 << 32) - 1))
+
+ @require_ctypes
+ def _high_dword(x):
+ return ctypes.c_ulong((x >> 32) & ((1 << 32) - 1))
@win_only
@require_ctypes
@@ -351,14 +351,14 @@ if on_win():
assert isinstance(flag, bool)
if not ctypes.windll.kernel32.SetHandleInformation(file_handle(file), _low_dword(value), _low_dword(int(flag))):
raise ctypes.WinError()
-
- @win_only
- @require_ctypes
- def get_windows_directory():
- buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
- size = ctypes.windll.kernel32.GetWindowsDirectoryW(buf, ctypes.wintypes.MAX_PATH)
- if not size:
- raise ctypes.WinError()
- if size > ctypes.wintypes.MAX_PATH - 1:
- raise CustomWinError(ERRORS['INSUFFICIENT_BUFFER'])
- return ctypes.wstring_at(buf, size)
+
+ @win_only
+ @require_ctypes
+ def get_windows_directory():
+ buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
+ size = ctypes.windll.kernel32.GetWindowsDirectoryW(buf, ctypes.wintypes.MAX_PATH)
+ if not size:
+ raise ctypes.WinError()
+ if size > ctypes.wintypes.MAX_PATH - 1:
+ raise CustomWinError(ERRORS['INSUFFICIENT_BUFFER'])
+ return ctypes.wstring_at(buf, size)
diff --git a/library/python/windows/ut/test_windows.py b/library/python/windows/ut/test_windows.py
index 516dfa4bb4..bef3ec2dc5 100644
--- a/library/python/windows/ut/test_windows.py
+++ b/library/python/windows/ut/test_windows.py
@@ -1,96 +1,96 @@
-# coding=utf-8
-
-import errno
-import os
-import pytest
-
+# coding=utf-8
+
+import errno
+import os
+import pytest
+
import library.python.strings
import library.python.windows
-
-
-def gen_error_access_denied():
+
+
+def gen_error_access_denied():
if library.python.windows.on_win():
- err = WindowsError()
- err.errno = errno.EACCES
- err.strerror = ''
+ err = WindowsError()
+ err.errno = errno.EACCES
+ err.strerror = ''
err.winerror = library.python.windows.ERRORS['ACCESS_DENIED']
- else:
- err = OSError()
- err.errno = errno.EACCES
- err.strerror = os.strerror(err.errno)
- err.filename = 'unknown/file'
- raise err
-
-
-def test_errorfix_buggy():
+ else:
+ err = OSError()
+ err.errno = errno.EACCES
+ err.strerror = os.strerror(err.errno)
+ err.filename = 'unknown/file'
+ raise err
+
+
+def test_errorfix_buggy():
@library.python.windows.errorfix
- def erroneous_func():
- gen_error_access_denied()
-
- with pytest.raises(OSError) as errinfo:
- erroneous_func()
- assert errinfo.value.errno == errno.EACCES
- assert errinfo.value.filename == 'unknown/file'
- assert isinstance(errinfo.value.strerror, basestring)
- assert errinfo.value.strerror
-
-
-def test_errorfix_explicit():
+ def erroneous_func():
+ gen_error_access_denied()
+
+ with pytest.raises(OSError) as errinfo:
+ erroneous_func()
+ assert errinfo.value.errno == errno.EACCES
+ assert errinfo.value.filename == 'unknown/file'
+ assert isinstance(errinfo.value.strerror, basestring)
+ assert errinfo.value.strerror
+
+
+def test_errorfix_explicit():
@library.python.windows.errorfix
- def erroneous_func():
+ def erroneous_func():
if library.python.windows.on_win():
- err = WindowsError()
+ err = WindowsError()
err.winerror = library.python.windows.ERRORS['ACCESS_DENIED']
- else:
- err = OSError()
- err.errno = errno.EACCES
- err.strerror = 'Some error description'
- err.filename = 'unknown/file'
- raise err
-
- with pytest.raises(OSError) as errinfo:
- erroneous_func()
- assert errinfo.value.errno == errno.EACCES
- assert errinfo.value.filename == 'unknown/file'
- assert errinfo.value.strerror == 'Some error description'
-
-
-def test_errorfix_decoding_cp1251():
+ else:
+ err = OSError()
+ err.errno = errno.EACCES
+ err.strerror = 'Some error description'
+ err.filename = 'unknown/file'
+ raise err
+
+ with pytest.raises(OSError) as errinfo:
+ erroneous_func()
+ assert errinfo.value.errno == errno.EACCES
+ assert errinfo.value.filename == 'unknown/file'
+ assert errinfo.value.strerror == 'Some error description'
+
+
+def test_errorfix_decoding_cp1251():
@library.python.windows.errorfix
- def erroneous_func():
- model_msg = u'Какое-то описание ошибки'
+ def erroneous_func():
+ model_msg = u'Какое-то описание ошибки'
if library.python.windows.on_win():
- err = WindowsError()
+ err = WindowsError()
err.strerror = library.python.strings.to_str(model_msg, 'cp1251')
- else:
- err = OSError()
+ else:
+ err = OSError()
err.strerror = library.python.strings.to_str(model_msg)
- raise err
-
- with pytest.raises(OSError) as errinfo:
- erroneous_func()
- error_msg = errinfo.value.strerror
- if not isinstance(errinfo.value.strerror, unicode):
+ raise err
+
+ with pytest.raises(OSError) as errinfo:
+ erroneous_func()
+ error_msg = errinfo.value.strerror
+ if not isinstance(errinfo.value.strerror, unicode):
error_msg = library.python.strings.to_unicode(error_msg)
- assert error_msg == u'Какое-то описание ошибки'
-
-
-def test_diehard():
+ assert error_msg == u'Какое-то описание ошибки'
+
+
+def test_diehard():
@library.python.windows.diehard(library.python.windows.ERRORS['ACCESS_DENIED'], tries=5)
- def erroneous_func(errors):
- try:
- gen_error_access_denied()
- except Exception as e:
- errors.append(e)
- raise
-
- raised_errors = []
- with pytest.raises(OSError) as errinfo:
- erroneous_func(raised_errors)
- assert errinfo.value.errno == errno.EACCES
- assert any(e.errno == errno.EACCES for e in raised_errors)
- assert raised_errors and errinfo.value == raised_errors[-1]
+ def erroneous_func(errors):
+ try:
+ gen_error_access_denied()
+ except Exception as e:
+ errors.append(e)
+ raise
+
+ raised_errors = []
+ with pytest.raises(OSError) as errinfo:
+ erroneous_func(raised_errors)
+ assert errinfo.value.errno == errno.EACCES
+ assert any(e.errno == errno.EACCES for e in raised_errors)
+ assert raised_errors and errinfo.value == raised_errors[-1]
if library.python.windows.on_win():
- assert len(raised_errors) == 5
- else:
- assert len(raised_errors) == 1
+ assert len(raised_errors) == 5
+ else:
+ assert len(raised_errors) == 1
diff --git a/library/python/windows/ut/ya.make b/library/python/windows/ut/ya.make
index 992afe0259..c39f1797b8 100644
--- a/library/python/windows/ut/ya.make
+++ b/library/python/windows/ut/ya.make
@@ -2,7 +2,7 @@ OWNER(g:yatool)
PY2TEST()
-TEST_SRCS(test_windows.py)
+TEST_SRCS(test_windows.py)
PEERDIR(
library/python/windows
diff --git a/library/python/ya.make b/library/python/ya.make
index 04b9e61286..2e1eb6e0e1 100644
--- a/library/python/ya.make
+++ b/library/python/ya.make
@@ -135,8 +135,8 @@ RECURSE(
openssl
par_apply
par_apply/test
- path
- path/tests
+ path
+ path/tests
protobuf
pymain
pyscopg2
@@ -154,8 +154,8 @@ RECURSE(
reservoir_sampling
refsclient
resource
- retry
- retry/tests
+ retry
+ retry/tests
runtime
runtime/main
runtime/test
diff --git a/library/ya.make b/library/ya.make
index f003ab35af..86f833bd02 100644
--- a/library/ya.make
+++ b/library/ya.make
@@ -15,4 +15,4 @@ IF (NOT SANITIZER_TYPE)
)
ENDIF()
-NEED_CHECK()
+NEED_CHECK()
diff --git a/tools/enum_parser/enum_parser/main.cpp b/tools/enum_parser/enum_parser/main.cpp
index f695db5f55..0943c69c1d 100644
--- a/tools/enum_parser/enum_parser/main.cpp
+++ b/tools/enum_parser/enum_parser/main.cpp
@@ -26,7 +26,7 @@
void WriteHeader(const TString& headerName, IOutputStream& out, IOutputStream* headerOutPtr = nullptr) {
out << "// This file was auto-generated. Do not edit!!!\n";
- out << "#include " << headerName << "\n";
+ out << "#include " << headerName << "\n";
out << "#include <tools/enum_parser/enum_serialization_runtime/enum_runtime.h>\n\n";
out << "#include <tools/enum_parser/enum_parser/stdlib_deps.h>\n\n";
out << "#include <util/generic/typetraits.h>\n";
@@ -392,11 +392,11 @@ int main(int argc, char** argv) {
"Generate appropriate header to specified file.\n"
"Works only if output file specified."
);
- opts.AddLongOption("include-path").OptionalArgument("<header-path>").StoreResult(&includePath)
- .Help(
- "Include input header using this path in angle brackets.\n"
- "When not set, header basename is used in double quotes."
- );
+ opts.AddLongOption("include-path").OptionalArgument("<header-path>").StoreResult(&includePath)
+ .Help(
+ "Include input header using this path in angle brackets.\n"
+ "When not set, header basename is used in double quotes."
+ );
opts.AddLongOption('j', "json-output").OptionalArgument("<json-output>").StoreResult(&outputJsonFileName)
.Help(
@@ -433,12 +433,12 @@ int main(int argc, char** argv) {
}
}
- if (!includePath) {
+ if (!includePath) {
includePath = TString() + '"' + TFsPath(inputFileName).Basename() + '"';
- } else {
+ } else {
includePath = TString() + '<' + includePath + '>';
- }
-
+ }
+
TEnumParser parser(inputFileName);
WriteHeader(includePath, *out, headerOut.Get());
diff --git a/tools/ya.make b/tools/ya.make
index 5446bfa076..51a6b8b426 100644
--- a/tools/ya.make
+++ b/tools/ya.make
@@ -58,7 +58,7 @@ RECURSE(
html2text
idl
idx_relemmatizer
- inflector
+ inflector
is_holiday
jsv8
json_to_jsonlines
@@ -84,11 +84,11 @@ RECURSE(
nodeiter_test/tests
normalize_requests
nots
- oauth_token
+ oauth_token
pgmigrate
pire
print_ranking_features
- printcorpus
+ printcorpus
printdocstat
printdom
printkeys
@@ -143,7 +143,7 @@ RECURSE(
spamfilt
stdin
struct2fieldcalc
- syntaxer
+ syntaxer
tarccreate
tarcview
templater
diff --git a/util/charset/benchmark/to_lower/metrics/ya.make b/util/charset/benchmark/to_lower/metrics/ya.make
index 3bec63360e..5bb3461a8d 100644
--- a/util/charset/benchmark/to_lower/metrics/ya.make
+++ b/util/charset/benchmark/to_lower/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/charset/benchmark/to_lower)
+DEPENDS(util/charset/benchmark/to_lower)
END()
diff --git a/util/charset/benchmark/to_lower/ya.make b/util/charset/benchmark/to_lower/ya.make
index 900e6790d1..74c47e6de5 100644
--- a/util/charset/benchmark/to_lower/ya.make
+++ b/util/charset/benchmark/to_lower/ya.make
@@ -1,4 +1,4 @@
-OWNER(yazevnul)
+OWNER(yazevnul)
Y_BENCHMARK()
diff --git a/util/charset/benchmark/utf8_to_wide/metrics/ya.make b/util/charset/benchmark/utf8_to_wide/metrics/ya.make
index 941ab08442..c406e25bee 100644
--- a/util/charset/benchmark/utf8_to_wide/metrics/ya.make
+++ b/util/charset/benchmark/utf8_to_wide/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/charset/benchmark/utf8_to_wide)
+DEPENDS(util/charset/benchmark/utf8_to_wide)
END()
diff --git a/util/charset/unidata.h b/util/charset/unidata.h
index 108776c27b..400d314186 100644
--- a/util/charset/unidata.h
+++ b/util/charset/unidata.h
@@ -352,9 +352,9 @@ inline bool IsLower(wchar32 ch) {
inline bool IsUpper(wchar32 ch) {
return NUnicode::CharHasType(ch, SHIFT(Lu_UPPER));
}
-inline bool IsTitle(wchar32 ch) {
- return NUnicode::CharHasType(ch, SHIFT(Lt_TITLE));
-}
+inline bool IsTitle(wchar32 ch) {
+ return NUnicode::CharHasType(ch, SHIFT(Lt_TITLE));
+}
inline bool IsAlpha(wchar32 ch) {
return NUnicode::CharHasType(ch,
SHIFT(Lu_UPPER) | SHIFT(Ll_LOWER) | SHIFT(Lt_TITLE) | SHIFT(Lm_LETTER) | SHIFT(Lm_EXTENDER) |
diff --git a/util/charset/ya.make b/util/charset/ya.make
index 03413fd59f..26d38cb10b 100644
--- a/util/charset/ya.make
+++ b/util/charset/ya.make
@@ -22,10 +22,10 @@ JOIN_SRCS(
IF (ARCH_X86_64 AND NOT DISABLE_INSTRUCTION_SETS)
SRC_CPP_SSE41(wide_sse41.cpp)
ELSE()
- SRC(
- wide_sse41.cpp
- -DSSE41_STUB
- )
+ SRC(
+ wide_sse41.cpp
+ -DSSE41_STUB
+ )
ENDIF()
END()
diff --git a/util/draft/ut/ya.make b/util/draft/ut/ya.make
index 75c3073a39..37ab9413c5 100644
--- a/util/draft/ut/ya.make
+++ b/util/draft/ut/ya.make
@@ -5,10 +5,10 @@ SUBSCRIBER(g:util-subscribers)
SRCDIR(util/draft)
-PEERDIR(
- util/draft
-)
-
+PEERDIR(
+ util/draft
+)
+
SRCS(
date_ut.cpp
datetime_ut.cpp
diff --git a/util/folder/dirut.cpp b/util/folder/dirut.cpp
index 793a95545b..ffc9b09f96 100644
--- a/util/folder/dirut.cpp
+++ b/util/folder/dirut.cpp
@@ -563,7 +563,7 @@ int ResolvePath(const char* rel, const char* abs, char res[/*MAXPATHLEN*/], bool
*res = 0;
if (!rel || !*rel)
return EINVAL;
- if (!IsAbsolutePath(rel) && IsAbsolutePath(abs)) {
+ if (!IsAbsolutePath(rel) && IsAbsolutePath(abs)) {
len = strlcpy(t, abs, sizeof(t));
if (len >= sizeof(t) - 3)
return EINVAL;
@@ -581,13 +581,13 @@ int ResolvePath(const char* rel, const char* abs, char res[/*MAXPATHLEN*/], bool
}
if (!realpath(t, res)) {
if (!isdir && realpath(GetDirName(t).data(), res)) {
- len = strlen(res);
- if (res[len - 1] != LOCSLASH_C) {
- res[len++] = LOCSLASH_C;
- res[len] = 0;
+ len = strlen(res);
+ if (res[len - 1] != LOCSLASH_C) {
+ res[len++] = LOCSLASH_C;
+ res[len] = 0;
}
strcpy(res + len, GetBaseName(t).data());
- return 0;
+ return 0;
}
return errno ? errno : ENOENT;
}
diff --git a/util/folder/dirut.h b/util/folder/dirut.h
index f7871a110a..2537027b12 100644
--- a/util/folder/dirut.h
+++ b/util/folder/dirut.h
@@ -67,7 +67,7 @@ inline TString GetFileNameComponent(const TString& f) {
return GetFileNameComponent(f.data());
}
-/// RealPath doesn't guarantee trailing separator to be stripped or left in place for directories.
+/// RealPath doesn't guarantee trailing separator to be stripped or left in place for directories.
TString RealPath(const TString& path); // throws
TString RealLocation(const TString& path); /// throws; last file name component doesn't need to exist
diff --git a/util/folder/dirut_ut.cpp b/util/folder/dirut_ut.cpp
index cfe19f5482..45ebfc842c 100644
--- a/util/folder/dirut_ut.cpp
+++ b/util/folder/dirut_ut.cpp
@@ -4,8 +4,8 @@
#include <library/cpp/testing/unittest/registar.h>
#include <util/generic/string.h>
-#include <util/memory/tempbuf.h>
-#include <util/stream/file.h>
+#include <util/memory/tempbuf.h>
+#include <util/stream/file.h>
#include <util/system/platform.h>
Y_UNIT_TEST_SUITE(TDirutTest) {
@@ -15,18 +15,18 @@ Y_UNIT_TEST_SUITE(TDirutTest) {
Y_UNIT_TEST(TestRealLocation) {
UNIT_ASSERT(IsDir(RealLocation(".")));
-
+
TTempDir tempDir;
TString base = RealPath(tempDir());
UNIT_ASSERT(!base.empty());
-
+
if (base.back() == GetDirectorySeparator()) {
base.pop_back();
}
-
+
TString path;
TString pathNotNorm;
-
+
path = base + GetDirectorySeparatorS() + "no_such_file";
UNIT_ASSERT(NFs::Exists(GetDirName(path)));
UNIT_ASSERT(!NFs::Exists(path));
@@ -34,16 +34,16 @@ Y_UNIT_TEST_SUITE(TDirutTest) {
UNIT_ASSERT(NFs::Exists(GetDirName(path)));
UNIT_ASSERT(!NFs::Exists(path));
UNIT_ASSERT_EQUAL(GetDirName(path), base);
-
+
pathNotNorm = base + GetDirectorySeparatorS() + "some_dir" + GetDirectorySeparatorS() + ".." + GetDirectorySeparatorS() + "no_such_file";
MakeDirIfNotExist((base + GetDirectorySeparatorS() + "some_dir").data());
pathNotNorm = RealLocation(pathNotNorm);
UNIT_ASSERT(NFs::Exists(GetDirName(pathNotNorm)));
UNIT_ASSERT(!NFs::Exists(pathNotNorm));
UNIT_ASSERT_EQUAL(GetDirName(pathNotNorm), base);
-
+
UNIT_ASSERT_EQUAL(path, pathNotNorm);
-
+
path = base + GetDirectorySeparatorS() + "file";
{
TFixedBufferFileOutput file(path);
@@ -55,8 +55,8 @@ Y_UNIT_TEST_SUITE(TDirutTest) {
UNIT_ASSERT(NFs::Exists(GetDirName(path)));
UNIT_ASSERT(NFs::Exists(path));
UNIT_ASSERT_EQUAL(GetDirName(path), base);
- }
-
+ }
+
void DoTest(const char* p, const char* base, const char* canon) {
TString path(p);
UNIT_ASSERT(resolvepath(path, base));
@@ -106,24 +106,24 @@ Y_UNIT_TEST_SUITE(TDirutTest) {
path = base + GetDirectorySeparatorS() + "nofile";
ResolvePath("nofile", base.data(), tempBuf.Data(), false);
UNIT_ASSERT_EQUAL(tempBuf.Data(), path);
- }
-
+ }
+
Y_UNIT_TEST(TestGetDirName) {
UNIT_ASSERT_VALUES_EQUAL(".", GetDirName("parambambam"));
- }
-
+ }
+
Y_UNIT_TEST(TestStripFileComponent) {
static const TString tmpDir = "tmp_dir_for_tests";
static const TString tmpSubDir = tmpDir + GetDirectorySeparatorS() + "subdir";
static const TString tmpFile = tmpDir + GetDirectorySeparatorS() + "file";
-
+
// creating tmp dir and subdirs
MakeDirIfNotExist(tmpDir.data());
MakeDirIfNotExist(tmpSubDir.data());
{
TFixedBufferFileOutput file(tmpFile);
}
-
+
UNIT_ASSERT_EQUAL(StripFileComponent(tmpDir), tmpDir + GetDirectorySeparatorS());
UNIT_ASSERT_EQUAL(StripFileComponent(tmpSubDir), tmpSubDir + GetDirectorySeparatorS());
UNIT_ASSERT_EQUAL(StripFileComponent(tmpFile), tmpDir + GetDirectorySeparatorS());
diff --git a/util/folder/path.h b/util/folder/path.h
index c98501fa35..2fb4d6b4ef 100644
--- a/util/folder/path.h
+++ b/util/folder/path.h
@@ -15,10 +15,10 @@
#include <utility>
-/**
- * Class behaviour is platform-dependent.
- * It uses platform-dependent separators for path-reconstructing operations.
- */
+/**
+ * Class behaviour is platform-dependent.
+ * It uses platform-dependent separators for path-reconstructing operations.
+ */
class TFsPath {
private:
struct TSplit;
diff --git a/util/folder/path_ut.cpp b/util/folder/path_ut.cpp
index 7b718deabc..e6a3451016 100644
--- a/util/folder/path_ut.cpp
+++ b/util/folder/path_ut.cpp
@@ -87,19 +87,19 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
}
Y_UNIT_TEST(Parent) {
-#ifdef _win_
+#ifdef _win_
UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\etc/passwd").Parent(), TFsPath("\\etc"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\etc").Parent(), TFsPath("\\"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\").Parent(), TFsPath("\\"));
-
+
UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc\\passwd").Parent(), TFsPath("etc"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc").Parent(), TFsPath("."));
UNIT_ASSERT_VALUES_EQUAL(TFsPath(".\\etc").Parent(), TFsPath("."));
-
+
UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\etc/passwd").Parent(), TFsPath("C:\\etc"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\etc").Parent(), TFsPath("C:\\"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("C:\\").Parent(), TFsPath("C:\\"));
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(TFsPath("/etc/passwd").Parent(), TFsPath("/etc"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("/etc").Parent(), TFsPath("/"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("/").Parent(), TFsPath("/"));
@@ -107,7 +107,7 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc/passwd").Parent(), TFsPath("etc"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("etc").Parent(), TFsPath("."));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("./etc").Parent(), TFsPath("."));
-#endif
+#endif
#if 0
UNIT_ASSERT_VALUES_EQUAL(TFsPath("./etc/passwd").Parent(), TFsPath("./etc"));
@@ -194,37 +194,37 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
TFsPath p("/db/BASE/primus121-025-1380131338//");
UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
TFsPath testP = p / "test";
-#ifdef _win_
+#ifdef _win_
UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\test");
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "/db/BASE/primus121-025-1380131338/test");
-#endif
+#endif
}
Y_UNIT_TEST(TestSlashesAndBasenameWin) {
- TFsPath p("\\db\\BASE\\primus121-025-1380131338\\\\");
- TFsPath testP = p / "test";
-#ifdef _win_
+ TFsPath p("\\db\\BASE\\primus121-025-1380131338\\\\");
+ TFsPath testP = p / "test";
+#ifdef _win_
UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\test");
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("\\db\\BASE\\primus121-025-1380131338\\\\"));
UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "\\db\\BASE\\primus121-025-1380131338\\\\/test");
-#endif
- }
-
+#endif
+ }
+
Y_UNIT_TEST(TestSlashesAndBasenameWinDrive) {
- TFsPath p("C:\\db\\BASE\\primus121-025-1380131338\\\\");
- TFsPath testP = p / "test";
-#ifdef _win_
+ TFsPath p("C:\\db\\BASE\\primus121-025-1380131338\\\\");
+ TFsPath testP = p / "test";
+#ifdef _win_
UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("primus121-025-1380131338"));
UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "C:\\db\\BASE\\primus121-025-1380131338\\test");
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(p.Basename(), TString("C:\\db\\BASE\\primus121-025-1380131338\\\\"));
UNIT_ASSERT_VALUES_EQUAL(testP.GetPath(), "C:\\db\\BASE\\primus121-025-1380131338\\\\/test");
-#endif
- }
-
+#endif
+ }
+
Y_UNIT_TEST(TestList) {
TTestDirectory td("TestList-dir");
@@ -350,17 +350,17 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
UNIT_ASSERT_VALUES_EQUAL(TFsPath(), TFsPath().Fix());
UNIT_ASSERT_VALUES_EQUAL(TFsPath() / TFsPath(), TFsPath());
-#ifdef _win_
+#ifdef _win_
UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b"), TFsPath() / TString("a\\b"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b"), "a\\b" / TFsPath());
UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\a\\b"), TFsPath() / "\\a\\b");
UNIT_ASSERT_VALUES_EQUAL(TFsPath("\\a\\b"), "\\a\\b" / TFsPath());
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b"), TFsPath() / TString("a/b"));
UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b"), "a/b" / TFsPath());
UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b"), TFsPath() / "/a/b");
UNIT_ASSERT_VALUES_EQUAL(TFsPath("/a/b"), "/a/b" / TFsPath());
-#endif
+#endif
UNIT_ASSERT_VALUES_EQUAL(TFsPath("."), TFsPath() / ".");
UNIT_ASSERT_VALUES_EQUAL(TFsPath("."), "." / TFsPath());
@@ -380,11 +380,11 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
UNIT_ASSERT(!TFsPath().IsSubpathOf("a/b"));
UNIT_ASSERT(TFsPath().IsContainerOf("a/b"));
UNIT_ASSERT(!TFsPath().IsContainerOf("/a/b"));
-#ifdef _win_
+#ifdef _win_
UNIT_ASSERT_VALUES_EQUAL(TFsPath("a\\b").RelativeTo(TFsPath()), TFsPath("a\\b"));
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(TFsPath("a/b").RelativeTo(TFsPath()), TFsPath("a/b"));
-#endif
+#endif
UNIT_ASSERT(!TFsPath().Exists());
UNIT_ASSERT(!TFsPath().IsFile());
@@ -394,21 +394,21 @@ Y_UNIT_TEST_SUITE(TFsPathTests) {
}
Y_UNIT_TEST(TestJoinFsPaths) {
-#ifdef _win_
- UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a\\b", "c\\d"), "a\\b\\c\\d");
+#ifdef _win_
+ UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a\\b", "c\\d"), "a\\b\\c\\d");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a\\b", "..\\c"), "a\\b\\..\\c");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a\\b\\..\\c", "d"), "a\\c\\d");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a", "b", "c", "d"), "a\\b\\c\\d");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a\\b\\..\\c"), "a\\b\\..\\c");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a\\b", ""), "a\\b");
-#else
+#else
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a/b", "c/d"), "a/b/c/d");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a/b", "../c"), "a/b/../c");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a/b/../c", "d"), "a/c/d");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a", "b", "c", "d"), "a/b/c/d");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a/b/../c"), "a/b/../c");
UNIT_ASSERT_VALUES_EQUAL(JoinFsPaths("a/b", ""), "a/b");
-#endif
+#endif
}
Y_UNIT_TEST(TestStringCast) {
diff --git a/util/folder/pathsplit.cpp b/util/folder/pathsplit.cpp
index d69aaf8d94..81d439a727 100644
--- a/util/folder/pathsplit.cpp
+++ b/util/folder/pathsplit.cpp
@@ -1,7 +1,7 @@
#include "pathsplit.h"
-#include "dirut.h"
-
+#include "dirut.h"
+
#include <util/stream/output.h>
#include <util/generic/yexception.h>
@@ -24,7 +24,7 @@ void TPathSplitTraitsUnix::DoParseFirstPart(const TStringBuf part) {
}
if (IsAbsolutePath(part)) {
- IsAbsolute = true;
+ IsAbsolute = true;
}
DoParsePart(part);
diff --git a/util/folder/pathsplit.h b/util/folder/pathsplit.h
index 2b734722cd..d134338e35 100644
--- a/util/folder/pathsplit.h
+++ b/util/folder/pathsplit.h
@@ -3,7 +3,7 @@
#include <util/generic/vector.h>
#include <util/generic/strbuf.h>
#include <util/generic/string.h>
-#include <util/string/ascii.h>
+#include <util/string/ascii.h>
//do not own any data
struct TPathSplitStore: public TVector<TStringBuf> {
@@ -23,7 +23,7 @@ protected:
struct TPathSplitTraitsUnix: public TPathSplitStore {
static constexpr char MainPathSep = '/';
-
+
inline TString Reconstruct() const {
return DoReconstruct(TStringBuf("/"));
}
@@ -42,7 +42,7 @@ struct TPathSplitTraitsUnix: public TPathSplitStore {
struct TPathSplitTraitsWindows: public TPathSplitStore {
static constexpr char MainPathSep = '\\';
-
+
inline TString Reconstruct() const {
return DoReconstruct(TStringBuf("\\"));
}
diff --git a/util/folder/pathsplit_ut.cpp b/util/folder/pathsplit_ut.cpp
index d48187360b..0e97afd0d0 100644
--- a/util/folder/pathsplit_ut.cpp
+++ b/util/folder/pathsplit_ut.cpp
@@ -1,29 +1,29 @@
-// File includes itself to make multiple passes of its suites with different platform-dependent definitions
-
-#ifndef PS_INCLUDED
-// Outer part
-
+// File includes itself to make multiple passes of its suites with different platform-dependent definitions
+
+#ifndef PS_INCLUDED
+// Outer part
+
#include "pathsplit.h"
-
+
#include <library/cpp/testing/unittest/registar.h>
-
+
#define VAR(NAME) Y_CAT(NAME, __LINE__)
-
+
#define PS_CHECK(input, ...) \
const char* VAR(model)[] = {"", __VA_ARGS__}; \
UNIT_ASSERT_EQUAL(input.size(), sizeof(VAR(model)) / sizeof(const char*) - 1); \
for (size_t n = 0; n < input.size(); ++n) { \
UNIT_ASSERT_STRINGS_EQUAL(input[n], VAR(model)[n + 1]); \
}
-
+
#define PS_INCLUDED
-
+
#define PSUF(NAME) NAME
#define PSUF_LOCAL(NAME) NAME##Local
#include __FILE__
#undef PSUF
#undef PSUF_LOCAL
-
+
#define PSUF(NAME) NAME##Unix
#define PSUF_LOCAL(NAME) PSUF(NAME)
#ifdef _win_
@@ -37,7 +37,7 @@
#endif
#undef PSUF
#undef PSUF_LOCAL
-
+
#define PSUF(NAME) NAME##Windows
#define PSUF_LOCAL(NAME) PSUF(NAME)
#ifndef _win_
@@ -51,61 +51,61 @@
#endif
#undef PSUF
#undef PSUF_LOCAL
-
+
#undef PS_INCLUDED
-
-#else
-// Inner part
-
+
+#else
+// Inner part
+
#ifdef _win_
#define TRUE_ONLY_WIN true
#else
#define TRUE_ONLY_WIN false
#endif
-
+
Y_UNIT_TEST_SUITE(PSUF(PathSplit)) {
Y_UNIT_TEST(Empty) {
PSUF(TPathSplit)
ps;
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(Relative) {
PSUF(TPathSplit)
ps("some/usual/path");
- PS_CHECK(ps, "some", "usual", "path");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ PS_CHECK(ps, "some", "usual", "path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(Absolute) {
PSUF(TPathSplit)
ps("/some/usual/path");
- PS_CHECK(ps, "some", "usual", "path");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- }
-
+ PS_CHECK(ps, "some", "usual", "path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ }
+
Y_UNIT_TEST(Self) {
PSUF(TPathSplit)
ps(".");
- PS_CHECK(ps, ".");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ PS_CHECK(ps, ".");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(Parent) {
PSUF(TPathSplit)
ps("..");
- PS_CHECK(ps, "..");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ PS_CHECK(ps, "..");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(Root) {
PSUF(TPathSplit)
ps("/");
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- }
-
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ }
+
Y_UNIT_TEST(Reconstruct) {
PSUF(TPathSplit)
ps("some/usual/path/../../other/././//path");
@@ -114,369 +114,369 @@ Y_UNIT_TEST_SUITE(PSUF(PathSplit)) {
#else
UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some/other/path");
#endif
-
+
ps = PSUF(TPathSplit)("/some/usual/path/../../other/././//path");
#ifdef _win_
UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "\\some\\other\\path");
#else
UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "/some/other/path");
#endif
- }
-
+ }
+
Y_UNIT_TEST(ParseFirstPart) {
PSUF(TPathSplit)
ps;
- ps.ParseFirstPart("some/usual/path");
- PS_CHECK(ps, "some", "usual", "path");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)();
- ps.ParseFirstPart("/some/usual/path");
- PS_CHECK(ps, "some", "usual", "path");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- }
-
+ ps.ParseFirstPart("some/usual/path");
+ PS_CHECK(ps, "some", "usual", "path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)();
+ ps.ParseFirstPart("/some/usual/path");
+ PS_CHECK(ps, "some", "usual", "path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ }
+
Y_UNIT_TEST(ParsePart) {
PSUF(TPathSplit)
ps("some/usual/path");
- ps.ParsePart("sub/path");
- PS_CHECK(ps, "some", "usual", "path", "sub", "path");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)("some/usual/path");
- ps.ParsePart("/sub/path");
- PS_CHECK(ps, "some", "usual", "path", "sub", "path");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ ps.ParsePart("sub/path");
+ PS_CHECK(ps, "some", "usual", "path", "sub", "path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)("some/usual/path");
+ ps.ParsePart("/sub/path");
+ PS_CHECK(ps, "some", "usual", "path", "sub", "path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(ParsePartSelf) {
PSUF(TPathSplit)
ps("some/usual/path");
- ps.ParsePart(".");
- PS_CHECK(ps, "some", "usual", "path");
-
- ps = PSUF(TPathSplit)("some/usual/path");
- ps.ParsePart("././.");
- PS_CHECK(ps, "some", "usual", "path");
- }
-
+ ps.ParsePart(".");
+ PS_CHECK(ps, "some", "usual", "path");
+
+ ps = PSUF(TPathSplit)("some/usual/path");
+ ps.ParsePart("././.");
+ PS_CHECK(ps, "some", "usual", "path");
+ }
+
Y_UNIT_TEST(ParsePartParent) {
PSUF(TPathSplit)
ps("some/usual/path");
- ps.ParsePart("..");
- PS_CHECK(ps, "some", "usual");
-
- ps = PSUF(TPathSplit)("some/usual/path");
- ps.ParsePart("../..");
- PS_CHECK(ps, "some");
-
- ps = PSUF(TPathSplit)("some/usual/path");
- ps.ParsePart("../../..");
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)("/some/usual/path");
- ps.ParsePart("../../..");
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- }
-
+ ps.ParsePart("..");
+ PS_CHECK(ps, "some", "usual");
+
+ ps = PSUF(TPathSplit)("some/usual/path");
+ ps.ParsePart("../..");
+ PS_CHECK(ps, "some");
+
+ ps = PSUF(TPathSplit)("some/usual/path");
+ ps.ParsePart("../../..");
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)("/some/usual/path");
+ ps.ParsePart("../../..");
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ }
+
Y_UNIT_TEST(ParsePartOverflow) {
PSUF(TPathSplit)
ps("some/usual/path");
- ps.ParsePart("../../../../..");
- PS_CHECK(ps, "..", "..");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)("/some/usual/path");
- ps.ParsePart("../../../../..");
- PS_CHECK(ps, "..", "..");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- }
-
+ ps.ParsePart("../../../../..");
+ PS_CHECK(ps, "..", "..");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)("/some/usual/path");
+ ps.ParsePart("../../../../..");
+ PS_CHECK(ps, "..", "..");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ }
+
Y_UNIT_TEST(WinRelative) {
PSUF(TPathSplit)
ps("some\\usual\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path");
+ PS_CHECK(ps, "some", "usual", "path");
#else
- PS_CHECK(ps, "some\\usual\\path");
+ PS_CHECK(ps, "some\\usual\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(WinAbsolute) {
PSUF(TPathSplit)
ps("\\some\\usual\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path");
+ PS_CHECK(ps, "some", "usual", "path");
#else
- PS_CHECK(ps, "\\some\\usual\\path");
+ PS_CHECK(ps, "\\some\\usual\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, TRUE_ONLY_WIN);
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, TRUE_ONLY_WIN);
+
PSUF(TPathSplit)
psDrive("C:\\some\\usual\\path");
#ifdef _win_
- PS_CHECK(psDrive, "some", "usual", "path");
- UNIT_ASSERT_EQUAL(psDrive.Drive, "C:");
+ PS_CHECK(psDrive, "some", "usual", "path");
+ UNIT_ASSERT_EQUAL(psDrive.Drive, "C:");
#else
- PS_CHECK(psDrive, "C:\\some\\usual\\path");
+ PS_CHECK(psDrive, "C:\\some\\usual\\path");
#endif
- UNIT_ASSERT_EQUAL(psDrive.IsAbsolute, TRUE_ONLY_WIN);
-
+ UNIT_ASSERT_EQUAL(psDrive.IsAbsolute, TRUE_ONLY_WIN);
+
PSUF(TPathSplit)
psDrive2("C:/some/usual/path");
#ifdef _win_
- PS_CHECK(psDrive2, "some", "usual", "path");
- UNIT_ASSERT_EQUAL(psDrive2.Drive, "C:");
+ PS_CHECK(psDrive2, "some", "usual", "path");
+ UNIT_ASSERT_EQUAL(psDrive2.Drive, "C:");
#else
- PS_CHECK(psDrive2, "C:", "some", "usual", "path");
+ PS_CHECK(psDrive2, "C:", "some", "usual", "path");
#endif
- UNIT_ASSERT_EQUAL(psDrive2.IsAbsolute, TRUE_ONLY_WIN);
- }
-
+ UNIT_ASSERT_EQUAL(psDrive2.IsAbsolute, TRUE_ONLY_WIN);
+ }
+
Y_UNIT_TEST(WinRoot) {
PSUF(TPathSplit)
ps("\\");
#ifdef _win_
- PS_CHECK(ps);
+ PS_CHECK(ps);
#else
- PS_CHECK(ps, "\\");
+ PS_CHECK(ps, "\\");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, TRUE_ONLY_WIN);
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, TRUE_ONLY_WIN);
+
PSUF(TPathSplit)
psDrive("C:");
#ifdef _win_
- PS_CHECK(psDrive);
- UNIT_ASSERT_EQUAL(psDrive.Drive, "C:");
+ PS_CHECK(psDrive);
+ UNIT_ASSERT_EQUAL(psDrive.Drive, "C:");
#else
- PS_CHECK(psDrive, "C:");
+ PS_CHECK(psDrive, "C:");
#endif
- UNIT_ASSERT_EQUAL(psDrive.IsAbsolute, TRUE_ONLY_WIN);
- }
-
+ UNIT_ASSERT_EQUAL(psDrive.IsAbsolute, TRUE_ONLY_WIN);
+ }
+
Y_UNIT_TEST(WinReconstruct) {
PSUF(TPathSplit)
ps("some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
#ifdef _win_
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some\\other\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some\\other\\path");
#else
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
#endif
-
- ps = PSUF(TPathSplit)("\\some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
+
+ ps = PSUF(TPathSplit)("\\some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
#ifdef _win_
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "\\some\\other\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "\\some\\other\\path");
#else
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "\\some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "\\some\\usual\\path\\..\\..\\other\\.\\.\\\\\\path");
#endif
- }
-
+ }
+
Y_UNIT_TEST(WinParseFirstPart) {
PSUF(TPathSplit)
ps;
- ps.ParseFirstPart("some\\usual\\path");
+ ps.ParseFirstPart("some\\usual\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path");
+ PS_CHECK(ps, "some", "usual", "path");
#else
- PS_CHECK(ps, "some\\usual\\path");
+ PS_CHECK(ps, "some\\usual\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)();
- ps.ParseFirstPart("\\some\\usual\\path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)();
+ ps.ParseFirstPart("\\some\\usual\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path");
+ PS_CHECK(ps, "some", "usual", "path");
#else
- PS_CHECK(ps, "\\some\\usual\\path");
+ PS_CHECK(ps, "\\some\\usual\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, TRUE_ONLY_WIN);
- }
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, TRUE_ONLY_WIN);
+ }
+
Y_UNIT_TEST(WinParsePart) {
PSUF(TPathSplit)
ps("some\\usual\\path");
- ps.ParsePart("sub\\path");
+ ps.ParsePart("sub\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path", "sub", "path");
+ PS_CHECK(ps, "some", "usual", "path", "sub", "path");
#else
- PS_CHECK(ps, "some\\usual\\path", "sub\\path");
+ PS_CHECK(ps, "some\\usual\\path", "sub\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)("some\\usual\\path");
- ps.ParsePart("\\sub\\path");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)("some\\usual\\path");
+ ps.ParsePart("\\sub\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path", "sub", "path");
+ PS_CHECK(ps, "some", "usual", "path", "sub", "path");
#else
- PS_CHECK(ps, "some\\usual\\path", "\\sub\\path");
+ PS_CHECK(ps, "some\\usual\\path", "\\sub\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
#ifdef _win_
Y_UNIT_TEST(WinParsePartSelf) {
PSUF(TPathSplit)
ps("some\\usual\\path");
- ps.ParsePart(".");
- PS_CHECK(ps, "some", "usual", "path");
-
- ps = PSUF(TPathSplit)("some\\usual\\path");
- ps.ParsePart(".\\.\\.");
- PS_CHECK(ps, "some", "usual", "path");
- }
-
+ ps.ParsePart(".");
+ PS_CHECK(ps, "some", "usual", "path");
+
+ ps = PSUF(TPathSplit)("some\\usual\\path");
+ ps.ParsePart(".\\.\\.");
+ PS_CHECK(ps, "some", "usual", "path");
+ }
+
Y_UNIT_TEST(WinParsePartParent) {
PSUF(TPathSplit)
ps("some\\usual\\path");
- ps.ParsePart("..");
- PS_CHECK(ps, "some", "usual");
-
- ps = PSUF(TPathSplit)("some\\usual\\path");
- ps.ParsePart("..\\..");
- PS_CHECK(ps, "some");
-
- ps = PSUF(TPathSplit)("some\\usual\\path");
- ps.ParsePart("..\\..\\..");
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)("\\some\\usual\\path");
- ps.ParsePart("..\\..\\..");
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
-
- ps = PSUF(TPathSplit)("C:\\some\\usual\\path");
- ps.ParsePart("..\\..\\..");
- PS_CHECK(ps);
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- UNIT_ASSERT_EQUAL(ps.Drive, "C:");
- }
-
+ ps.ParsePart("..");
+ PS_CHECK(ps, "some", "usual");
+
+ ps = PSUF(TPathSplit)("some\\usual\\path");
+ ps.ParsePart("..\\..");
+ PS_CHECK(ps, "some");
+
+ ps = PSUF(TPathSplit)("some\\usual\\path");
+ ps.ParsePart("..\\..\\..");
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)("\\some\\usual\\path");
+ ps.ParsePart("..\\..\\..");
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+
+ ps = PSUF(TPathSplit)("C:\\some\\usual\\path");
+ ps.ParsePart("..\\..\\..");
+ PS_CHECK(ps);
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ UNIT_ASSERT_EQUAL(ps.Drive, "C:");
+ }
+
Y_UNIT_TEST(WinParsePartOverflow) {
PSUF(TPathSplit)
ps("some\\usual\\path");
- ps.ParsePart("..\\..\\..\\..\\..");
- PS_CHECK(ps, "..", "..");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
-
- ps = PSUF(TPathSplit)("\\some\\usual\\path");
- ps.ParsePart("..\\..\\..\\..\\..");
- PS_CHECK(ps, "..", "..");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
-
- ps = PSUF(TPathSplit)("C:\\some\\usual\\path");
- ps.ParsePart("..\\..\\..\\..\\..");
- PS_CHECK(ps, "..", "..");
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
- UNIT_ASSERT_EQUAL(ps.Drive, "C:");
- }
+ ps.ParsePart("..\\..\\..\\..\\..");
+ PS_CHECK(ps, "..", "..");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+
+ ps = PSUF(TPathSplit)("\\some\\usual\\path");
+ ps.ParsePart("..\\..\\..\\..\\..");
+ PS_CHECK(ps, "..", "..");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+
+ ps = PSUF(TPathSplit)("C:\\some\\usual\\path");
+ ps.ParsePart("..\\..\\..\\..\\..");
+ PS_CHECK(ps, "..", "..");
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, true);
+ UNIT_ASSERT_EQUAL(ps.Drive, "C:");
+ }
#endif
-
+
Y_UNIT_TEST(WinMixed) {
PSUF(TPathSplit)
ps("some\\usual/path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path");
+ PS_CHECK(ps, "some", "usual", "path");
#else
- PS_CHECK(ps, "some\\usual", "path");
+ PS_CHECK(ps, "some\\usual", "path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(WinParsePartMixed) {
PSUF(TPathSplit)
ps("some\\usual/path");
- ps.ParsePart("sub/sub\\path");
+ ps.ParsePart("sub/sub\\path");
#ifdef _win_
- PS_CHECK(ps, "some", "usual", "path", "sub", "sub", "path");
+ PS_CHECK(ps, "some", "usual", "path", "sub", "sub", "path");
#else
- PS_CHECK(ps, "some\\usual", "path", "sub", "sub\\path");
+ PS_CHECK(ps, "some\\usual", "path", "sub", "sub\\path");
#endif
- UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
- }
-
+ UNIT_ASSERT_EQUAL(ps.IsAbsolute, false);
+ }
+
Y_UNIT_TEST(BeginWithSelf) {
PSUF(TPathSplit)
ps("./some/usual/path");
- PS_CHECK(ps, "some", "usual", "path");
+ PS_CHECK(ps, "some", "usual", "path");
#ifdef _win_
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some\\usual\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some\\usual\\path");
#else
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some/usual/path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "some/usual/path");
#endif
- }
-
+ }
+
Y_UNIT_TEST(BeginWithParent) {
PSUF(TPathSplit)
ps("../some/usual/path");
- PS_CHECK(ps, "..", "some", "usual", "path");
+ PS_CHECK(ps, "..", "some", "usual", "path");
#ifdef _win_
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "..\\some\\usual\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "..\\some\\usual\\path");
#else
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "../some/usual/path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "../some/usual/path");
#endif
- }
-
+ }
+
Y_UNIT_TEST(InOut) {
PSUF(TPathSplit)
ps("path/..");
- PS_CHECK(ps);
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "");
- }
-
+ PS_CHECK(ps);
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "");
+ }
+
Y_UNIT_TEST(OutIn) {
PSUF(TPathSplit)
ps("../path");
- PS_CHECK(ps, "..", "path");
+ PS_CHECK(ps, "..", "path");
#ifdef _win_
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "..\\path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "..\\path");
#else
- UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "../path");
+ UNIT_ASSERT_STRINGS_EQUAL(ps.Reconstruct(), "../path");
#endif
- }
-}
-
+ }
+}
+
Y_UNIT_TEST_SUITE(PSUF(PathSplitTraits)) {
Y_UNIT_TEST(IsPathSep) {
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsPathSep('/'), true);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsPathSep('\\'), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsPathSep(' '), false);
- }
-
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsPathSep('/'), true);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsPathSep('\\'), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsPathSep(' '), false);
+ }
+
Y_UNIT_TEST(IsAbsolutePath) {
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath(""), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/"), true);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("some/usual/path"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/some/usual/path"), true);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("."), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath(".."), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/."), true);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/.."), true);
- }
-
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath(""), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/"), true);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("some/usual/path"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/some/usual/path"), true);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("."), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath(".."), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/."), true);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("/.."), true);
+ }
+
Y_UNIT_TEST(WinIsAbsolutePath) {
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("somepath"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\somepath"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\."), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\.."), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:somepath"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:\\"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:\\somepath"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:/"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:/somepath"), TRUE_ONLY_WIN);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:somepath"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:\\somepath"), false);
- UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:/somepath"), false);
- }
-}
-
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("somepath"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\somepath"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\."), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("\\.."), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:somepath"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:\\"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:\\somepath"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:/"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("C:/somepath"), TRUE_ONLY_WIN);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:somepath"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:\\somepath"), false);
+ UNIT_ASSERT_EQUAL(PSUF_LOCAL(TPathSplitTraits)::IsAbsolutePath("#:/somepath"), false);
+ }
+}
+
#undef TRUE_ONLY_WIN
-
-#endif
+
+#endif
diff --git a/util/generic/benchmark/fastclp2/metrics/ya.make b/util/generic/benchmark/fastclp2/metrics/ya.make
index 079d0ce5e3..b2d17ebad3 100644
--- a/util/generic/benchmark/fastclp2/metrics/ya.make
+++ b/util/generic/benchmark/fastclp2/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/generic/benchmark/fastclp2)
+DEPENDS(util/generic/benchmark/fastclp2)
END()
diff --git a/util/generic/benchmark/log2/metrics/ya.make b/util/generic/benchmark/log2/metrics/ya.make
index afef38ed11..eb987e38d2 100644
--- a/util/generic/benchmark/log2/metrics/ya.make
+++ b/util/generic/benchmark/log2/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/generic/benchmark/log2)
+DEPENDS(util/generic/benchmark/log2)
END()
diff --git a/util/generic/benchmark/rotate_bits/metrics/ya.make b/util/generic/benchmark/rotate_bits/metrics/ya.make
index 1e08b6019c..ac27d2f845 100644
--- a/util/generic/benchmark/rotate_bits/metrics/ya.make
+++ b/util/generic/benchmark/rotate_bits/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/generic/benchmark/rotate_bits)
+DEPENDS(util/generic/benchmark/rotate_bits)
END()
diff --git a/util/generic/benchmark/vector_count_ctor/metrics/ya.make b/util/generic/benchmark/vector_count_ctor/metrics/ya.make
index edbf2a463b..c48f89b564 100644
--- a/util/generic/benchmark/vector_count_ctor/metrics/ya.make
+++ b/util/generic/benchmark/vector_count_ctor/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/generic/benchmark/vector_count_ctor)
+DEPENDS(util/generic/benchmark/vector_count_ctor)
END()
diff --git a/util/generic/bitmap.h b/util/generic/bitmap.h
index 4e65dd9036..f77d182460 100644
--- a/util/generic/bitmap.h
+++ b/util/generic/bitmap.h
@@ -9,7 +9,7 @@
#include <util/system/yassert.h>
#include <util/system/defaults.h>
-#include <util/str_stl.h>
+#include <util/str_stl.h>
#include <util/ysaveload.h>
namespace NBitMapPrivate {
@@ -985,21 +985,21 @@ public:
}
Mask.Sanitize();
}
-
- inline size_t Hash() const {
- THash<TChunk> chunkHasher;
-
- size_t hash = chunkHasher(0);
- bool tailSkipped = false;
- for (size_t i = Mask.GetChunkCapacity(); i > 0; --i) {
- if (tailSkipped || Mask.Data[i - 1]) {
- hash = ::CombineHashes(hash, chunkHasher(Mask.Data[i - 1]));
- tailSkipped = true;
- }
- }
-
- return hash;
- }
+
+ inline size_t Hash() const {
+ THash<TChunk> chunkHasher;
+
+ size_t hash = chunkHasher(0);
+ bool tailSkipped = false;
+ for (size_t i = Mask.GetChunkCapacity(); i > 0; --i) {
+ if (tailSkipped || Mask.Data[i - 1]) {
+ hash = ::CombineHashes(hash, chunkHasher(Mask.Data[i - 1]));
+ tailSkipped = true;
+ }
+ }
+
+ return hash;
+ }
inline const TChunk* GetChunks() const {
return Mask.Data;
@@ -1105,10 +1105,10 @@ public:
using TDynBitMap = TBitMapOps<TDynamicBitMapTraits<ui64>>;
#define Y_FOR_EACH_BIT(var, bitmap) for (size_t var = (bitmap).FirstNonZeroBit(); var != (bitmap).Size(); var = (bitmap).NextNonZeroBit(var))
-
-template <typename TTraits>
+
+template <typename TTraits>
struct THash<TBitMapOps<TTraits>> {
- size_t operator()(const TBitMapOps<TTraits>& elem) const {
- return elem.Hash();
- }
-};
+ size_t operator()(const TBitMapOps<TTraits>& elem) const {
+ return elem.Hash();
+ }
+};
diff --git a/util/generic/bitmap_ut.cpp b/util/generic/bitmap_ut.cpp
index bf139cda08..087d34a8dc 100644
--- a/util/generic/bitmap_ut.cpp
+++ b/util/generic/bitmap_ut.cpp
@@ -474,80 +474,80 @@ Y_UNIT_TEST_SUITE(TBitMapTest) {
UNIT_ASSERT_EQUAL(bitmap4.NextNonZeroBit(127), bitmap4.Size());
UNIT_ASSERT_EQUAL(bitmap4.NextNonZeroBit(533), bitmap4.Size());
}
-
+
Y_UNIT_TEST(TestHashFixed) {
- TBitMap<32, ui8> bitmap32;
- TBitMap<32, ui8> bitmap322;
- TBitMap<64, ui8> bitmap64;
-
- bitmap32.Clear();
- bitmap322.Clear();
- UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap322.Hash());
- bitmap32.Set(0);
- UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap322.Hash());
- bitmap322.Set(0);
- UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap322.Hash());
- bitmap32.Set(8).Set(31);
- UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap322.Hash());
- bitmap322.Set(8).Set(31);
- UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap322.Hash());
-
- bitmap32.Clear();
- bitmap64.Clear();
- UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap64.Hash());
- bitmap32.Set(0);
- UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap64.Hash());
- bitmap64.Set(0);
- UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap64.Hash());
- bitmap32.Set(8).Set(31);
- UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap64.Hash());
- bitmap64.Set(8).Set(31);
- UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap64.Hash());
- bitmap64.Set(32);
- UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap64.Hash());
- }
-
+ TBitMap<32, ui8> bitmap32;
+ TBitMap<32, ui8> bitmap322;
+ TBitMap<64, ui8> bitmap64;
+
+ bitmap32.Clear();
+ bitmap322.Clear();
+ UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap322.Hash());
+ bitmap32.Set(0);
+ UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap322.Hash());
+ bitmap322.Set(0);
+ UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap322.Hash());
+ bitmap32.Set(8).Set(31);
+ UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap322.Hash());
+ bitmap322.Set(8).Set(31);
+ UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap322.Hash());
+
+ bitmap32.Clear();
+ bitmap64.Clear();
+ UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap64.Hash());
+ bitmap32.Set(0);
+ UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap64.Hash());
+ bitmap64.Set(0);
+ UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap64.Hash());
+ bitmap32.Set(8).Set(31);
+ UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap64.Hash());
+ bitmap64.Set(8).Set(31);
+ UNIT_ASSERT_EQUAL(bitmap32.Hash(), bitmap64.Hash());
+ bitmap64.Set(32);
+ UNIT_ASSERT_UNEQUAL(bitmap32.Hash(), bitmap64.Hash());
+ }
+
Y_UNIT_TEST(TestHashDynamic) {
- TDynBitMap bitmap1;
- TDynBitMap bitmap2;
-
- bitmap1.Clear();
- bitmap2.Clear();
- UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
- bitmap1.Set(0);
- UNIT_ASSERT_UNEQUAL(bitmap1.Hash(), bitmap2.Hash());
- bitmap2.Set(0);
- UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
- bitmap1.Set(8).Set(31);
- UNIT_ASSERT_UNEQUAL(bitmap1.Hash(), bitmap2.Hash());
- bitmap2.Set(8).Set(31);
- UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
- bitmap1.Set(64);
- UNIT_ASSERT_UNEQUAL(bitmap1.Hash(), bitmap2.Hash());
- bitmap2.Set(64);
- UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
- }
-
+ TDynBitMap bitmap1;
+ TDynBitMap bitmap2;
+
+ bitmap1.Clear();
+ bitmap2.Clear();
+ UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
+ bitmap1.Set(0);
+ UNIT_ASSERT_UNEQUAL(bitmap1.Hash(), bitmap2.Hash());
+ bitmap2.Set(0);
+ UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
+ bitmap1.Set(8).Set(31);
+ UNIT_ASSERT_UNEQUAL(bitmap1.Hash(), bitmap2.Hash());
+ bitmap2.Set(8).Set(31);
+ UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
+ bitmap1.Set(64);
+ UNIT_ASSERT_UNEQUAL(bitmap1.Hash(), bitmap2.Hash());
+ bitmap2.Set(64);
+ UNIT_ASSERT_EQUAL(bitmap1.Hash(), bitmap2.Hash());
+ }
+
Y_UNIT_TEST(TestHashMixed) {
static_assert((std::is_same<TDynBitMap::TChunk, ui64>::value), "expect (TSameType<TDynBitMap::TChunk, ui64>::Result)");
-
- TBitMap<sizeof(ui64) * 16, ui64> bitmapFixed;
- TDynBitMap bitmapDynamic;
-
- bitmapFixed.Clear();
- bitmapDynamic.Clear();
- UNIT_ASSERT_EQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
- bitmapFixed.Set(0);
- UNIT_ASSERT_UNEQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
- bitmapDynamic.Set(0);
- UNIT_ASSERT_EQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
- bitmapFixed.Set(8).Set(127);
- UNIT_ASSERT_UNEQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
- bitmapDynamic.Set(8).Set(127);
- UNIT_ASSERT_EQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
- bitmapDynamic.Set(128);
- UNIT_ASSERT_UNEQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
- }
+
+ TBitMap<sizeof(ui64) * 16, ui64> bitmapFixed;
+ TDynBitMap bitmapDynamic;
+
+ bitmapFixed.Clear();
+ bitmapDynamic.Clear();
+ UNIT_ASSERT_EQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
+ bitmapFixed.Set(0);
+ UNIT_ASSERT_UNEQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
+ bitmapDynamic.Set(0);
+ UNIT_ASSERT_EQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
+ bitmapFixed.Set(8).Set(127);
+ UNIT_ASSERT_UNEQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
+ bitmapDynamic.Set(8).Set(127);
+ UNIT_ASSERT_EQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
+ bitmapDynamic.Set(128);
+ UNIT_ASSERT_UNEQUAL(bitmapFixed.Hash(), bitmapDynamic.Hash());
+ }
Y_UNIT_TEST(TestSetResetRange) {
// Single chunk
diff --git a/util/generic/fuzz/vector/ya.make b/util/generic/fuzz/vector/ya.make
index 6b41dd8a0b..b8614f6411 100644
--- a/util/generic/fuzz/vector/ya.make
+++ b/util/generic/fuzz/vector/ya.make
@@ -1,9 +1,9 @@
FUZZ()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SUBSCRIBER(g:util-subscribers)
SRCS(
diff --git a/util/generic/is_in.h b/util/generic/is_in.h
index e452d9f96a..4f175ea5eb 100644
--- a/util/generic/is_in.h
+++ b/util/generic/is_in.h
@@ -3,7 +3,7 @@
#include "typetraits.h"
#include <algorithm>
-#include <initializer_list>
+#include <initializer_list>
template <class I, class T>
static inline bool IsIn(I f, I l, const T& v);
@@ -46,8 +46,8 @@ static inline bool IsIn(const C& c, const T& e) {
using namespace NIsInHelper;
return TIsInTraits<C, T, TIsAssocCont<C>::value>::IsIn(c, e);
}
-
+
template <class T, class U>
static inline bool IsIn(std::initializer_list<T> l, const U& e) {
return ::IsIn(l.begin(), l.end(), e);
-}
+}
diff --git a/util/generic/is_in_ut.cpp b/util/generic/is_in_ut.cpp
index 247f5df4dd..c668bce807 100644
--- a/util/generic/is_in_ut.cpp
+++ b/util/generic/is_in_ut.cpp
@@ -75,11 +75,11 @@ Y_UNIT_TEST_SUITE(TIsIn) {
const char* abc = "abc";
const char* def = "def";
- UNIT_ASSERT(IsIn({6, 2, 12}, 6));
- UNIT_ASSERT(IsIn({6, 2, 12}, 2));
- UNIT_ASSERT(!IsIn({6, 2, 12}, 7));
- UNIT_ASSERT(IsIn({6}, 6));
- UNIT_ASSERT(!IsIn({6}, 7));
+ UNIT_ASSERT(IsIn({6, 2, 12}, 6));
+ UNIT_ASSERT(IsIn({6, 2, 12}, 2));
+ UNIT_ASSERT(!IsIn({6, 2, 12}, 7));
+ UNIT_ASSERT(IsIn({6}, 6));
+ UNIT_ASSERT(!IsIn({6}, 7));
UNIT_ASSERT(!IsIn(std::initializer_list<int>(), 6));
UNIT_ASSERT(IsIn({TStringBuf("abc"), TStringBuf("def")}, TStringBuf("abc")));
UNIT_ASSERT(IsIn({TStringBuf("abc"), TStringBuf("def")}, TStringBuf("def")));
@@ -92,8 +92,8 @@ Y_UNIT_TEST_SUITE(TIsIn) {
const TStringBuf str = "abc////";
UNIT_ASSERT(IsIn({"abc", "def"}, TStringBuf{str.data(), 3}));
- }
-
+ }
+
Y_UNIT_TEST(ConfOfTest) {
UNIT_ASSERT(IsIn({1, 2, 3}, 1));
UNIT_ASSERT(!IsIn({1, 2, 3}, 4));
diff --git a/util/memory/benchmark/pool/metrics/ya.make b/util/memory/benchmark/pool/metrics/ya.make
index 708318f2bc..c671bc5c1c 100644
--- a/util/memory/benchmark/pool/metrics/ya.make
+++ b/util/memory/benchmark/pool/metrics/ya.make
@@ -1,4 +1,4 @@
-OWNER(g:util)
+OWNER(g:util)
SUBSCRIBER(g:util-subscribers)
PY2TEST()
@@ -11,8 +11,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/memory/benchmark/pool)
+DEPENDS(util/memory/benchmark/pool)
END()
diff --git a/util/memory/benchmark/pool/ya.make b/util/memory/benchmark/pool/ya.make
index 64ba83eec7..5f4f7d3f15 100644
--- a/util/memory/benchmark/pool/ya.make
+++ b/util/memory/benchmark/pool/ya.make
@@ -1,4 +1,4 @@
-OWNER(g:util)
+OWNER(g:util)
SUBSCRIBER(g:util-subscribers)
Y_BENCHMARK()
diff --git a/util/memory/benchmark/ya.make b/util/memory/benchmark/ya.make
index 73b42a5fcf..2259b9434e 100644
--- a/util/memory/benchmark/ya.make
+++ b/util/memory/benchmark/ya.make
@@ -1,4 +1,4 @@
-OWNER(g:util)
+OWNER(g:util)
SUBSCRIBER(g:util-subscribers)
RECURSE(
diff --git a/util/random/benchmark/prng/metrics/ya.make b/util/random/benchmark/prng/metrics/ya.make
index d89e6a6b52..1f56aac0bd 100644
--- a/util/random/benchmark/prng/metrics/ya.make
+++ b/util/random/benchmark/prng/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/random/benchmark/prng)
+DEPENDS(util/random/benchmark/prng)
END()
diff --git a/util/string/benchmark/float_to_string/metrics/ya.make b/util/string/benchmark/float_to_string/metrics/ya.make
index 9d9c71dbbc..4b8c4cc07d 100644
--- a/util/string/benchmark/float_to_string/metrics/ya.make
+++ b/util/string/benchmark/float_to_string/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/string/benchmark/float_to_string)
+DEPENDS(util/string/benchmark/float_to_string)
END()
diff --git a/util/string/benchmark/float_to_string/ya.make b/util/string/benchmark/float_to_string/ya.make
index 83bba6a0dd..8136ad34f0 100644
--- a/util/string/benchmark/float_to_string/ya.make
+++ b/util/string/benchmark/float_to_string/ya.make
@@ -1,9 +1,9 @@
-OWNER(yazevnul)
+OWNER(yazevnul)
Y_BENCHMARK()
-# to minimize allocations overhead
-ALLOCATOR(B)
+# to minimize allocations overhead
+ALLOCATOR(B)
SRCS(
main.cpp
diff --git a/util/string/benchmark/join/metrics/ya.make b/util/string/benchmark/join/metrics/ya.make
index 51aaacab3b..08ff3a149f 100644
--- a/util/string/benchmark/join/metrics/ya.make
+++ b/util/string/benchmark/join/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/string/benchmark/join)
+DEPENDS(util/string/benchmark/join)
END()
diff --git a/util/string/benchmark/subst_global/metrics/ya.make b/util/string/benchmark/subst_global/metrics/ya.make
index 7f9d9e5e76..d8c30ad460 100644
--- a/util/string/benchmark/subst_global/metrics/ya.make
+++ b/util/string/benchmark/subst_global/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/string/benchmark/subst_global)
+DEPENDS(util/string/benchmark/subst_global)
END()
diff --git a/util/string/benchmark/subst_global/ya.make b/util/string/benchmark/subst_global/ya.make
index 83bba6a0dd..8136ad34f0 100644
--- a/util/string/benchmark/subst_global/ya.make
+++ b/util/string/benchmark/subst_global/ya.make
@@ -1,9 +1,9 @@
-OWNER(yazevnul)
+OWNER(yazevnul)
Y_BENCHMARK()
-# to minimize allocations overhead
-ALLOCATOR(B)
+# to minimize allocations overhead
+ALLOCATOR(B)
SRCS(
main.cpp
diff --git a/util/string/fuzzing/collapse/ya.make b/util/string/fuzzing/collapse/ya.make
index 6b41dd8a0b..b8614f6411 100644
--- a/util/string/fuzzing/collapse/ya.make
+++ b/util/string/fuzzing/collapse/ya.make
@@ -1,9 +1,9 @@
FUZZ()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SUBSCRIBER(g:util-subscribers)
SRCS(
diff --git a/util/string/fuzzing/strtod/ya.make b/util/string/fuzzing/strtod/ya.make
index 6b41dd8a0b..b8614f6411 100644
--- a/util/string/fuzzing/strtod/ya.make
+++ b/util/string/fuzzing/strtod/ya.make
@@ -1,9 +1,9 @@
FUZZ()
-OWNER(
- pg
- g:util
-)
+OWNER(
+ pg
+ g:util
+)
SUBSCRIBER(g:util-subscribers)
SRCS(
diff --git a/util/system/benchmark/cpu_id/metrics/ya.make b/util/system/benchmark/cpu_id/metrics/ya.make
index 9e36d9c13b..8c55def99b 100644
--- a/util/system/benchmark/cpu_id/metrics/ya.make
+++ b/util/system/benchmark/cpu_id/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/system/benchmark/cpu_id)
+DEPENDS(util/system/benchmark/cpu_id)
END()
diff --git a/util/system/benchmark/create_destroy_thread/metrics/ya.make b/util/system/benchmark/create_destroy_thread/metrics/ya.make
index c5d63db55e..d526487e1a 100644
--- a/util/system/benchmark/create_destroy_thread/metrics/ya.make
+++ b/util/system/benchmark/create_destroy_thread/metrics/ya.make
@@ -14,8 +14,8 @@ TAG(
ya:fat
)
-TEST_SRCS(main.py)
+TEST_SRCS(main.py)
-DEPENDS(util/system/benchmark/create_destroy_thread)
+DEPENDS(util/system/benchmark/create_destroy_thread)
END()
diff --git a/util/system/benchmark/create_destroy_thread/ya.make b/util/system/benchmark/create_destroy_thread/ya.make
index 27d120b678..03eb0ec8e0 100644
--- a/util/system/benchmark/create_destroy_thread/ya.make
+++ b/util/system/benchmark/create_destroy_thread/ya.make
@@ -1,4 +1,4 @@
-OWNER(yazevnul)
+OWNER(yazevnul)
Y_BENCHMARK()
diff --git a/util/system/getpid.cpp b/util/system/getpid.cpp
index e93123a0cd..b9615f0dfa 100644
--- a/util/system/getpid.cpp
+++ b/util/system/getpid.cpp
@@ -14,7 +14,7 @@
#include <unistd.h>
#endif
-TProcessId GetPID() {
+TProcessId GetPID() {
#ifdef _win_
return GetCurrentProcessId();
#else
diff --git a/util/system/getpid.h b/util/system/getpid.h
index 8f86d6712d..60e243266f 100644
--- a/util/system/getpid.h
+++ b/util/system/getpid.h
@@ -1,12 +1,12 @@
#pragma once
-#include "platform.h"
-#include "types.h"
+#include "platform.h"
+#include "types.h"
-#if defined(_win_)
-using TProcessId = ui32; // DWORD
-#else
-using TProcessId = pid_t;
-#endif
-
-TProcessId GetPID();
+#if defined(_win_)
+using TProcessId = ui32; // DWORD
+#else
+using TProcessId = pid_t;
+#endif
+
+TProcessId GetPID();
diff --git a/util/system/getpid_ut.cpp b/util/system/getpid_ut.cpp
index a3ee6247d1..e7122a2971 100644
--- a/util/system/getpid_ut.cpp
+++ b/util/system/getpid_ut.cpp
@@ -14,6 +14,6 @@ public:
UNIT_TEST_SUITE_REGISTRATION(TGetPidTest);
void TGetPidTest::Test() {
- const TProcessId pid = GetPID();
+ const TProcessId pid = GetPID();
UNIT_ASSERT(pid != 0);
}
diff --git a/util/system/shellcommand.cpp b/util/system/shellcommand.cpp
index 7c29580e21..b1989b5c8c 100644
--- a/util/system/shellcommand.cpp
+++ b/util/system/shellcommand.cpp
@@ -15,7 +15,7 @@
#include <util/stream/str.h>
#include <util/string/cast.h>
#include <util/system/info.h>
-
+
#include <errno.h>
#if defined(_unix_)
@@ -87,8 +87,8 @@ namespace {
}
}
#elif defined(_win_)
- constexpr static size_t MAX_COMMAND_LINE = 32 * 1024;
-
+ constexpr static size_t MAX_COMMAND_LINE = 32 * 1024;
+
std::wstring GetWString(const char* astring) {
if (!astring)
return std::wstring();
@@ -400,7 +400,7 @@ public:
kill(-Pid, SIGTERM); // between a failed kill(-Pid) and a successful kill(Pid) a grandchild could have been spawned
}
#else
- TerminateProcess(Pid, 1 /* exit code */);
+ TerminateProcess(Pid, 1 /* exit code */);
#endif
if (!ok) {
ythrow TSystemError() << "cannot terminate " << Pid;
@@ -562,10 +562,10 @@ void TShellCommand::TImpl::StartProcess(TShellCommand::TImpl::TPipes& pipes) {
// winapi can modify command text, copy it
Y_ENSURE_EX(cmd.size() < MAX_COMMAND_LINE, yexception() << "Command is too long (length=" << cmd.size() << ")");
- TTempArray<wchar_t> cmdcopy(MAX_COMMAND_LINE);
+ TTempArray<wchar_t> cmdcopy(MAX_COMMAND_LINE);
Copy(cmd.data(), cmd.data() + cmd.size(), cmdcopy.Data());
*(cmdcopy.Data() + cmd.size()) = 0;
-
+
const wchar_t* cwd = NULL;
std::wstring cwdBuff;
if (WorkDir.size()) {
@@ -591,7 +591,7 @@ void TShellCommand::TImpl::StartProcess(TShellCommand::TImpl::TPipes& pipes) {
if (User.Name.empty() || GetUsername() == User.Name) {
res = CreateProcessW(
nullptr, // image name
- cmdcopy.Data(),
+ cmdcopy.Data(),
nullptr, // process security attributes
nullptr, // thread security attributes
TRUE, // inherit handles - needed for IO, CloseAllFdsOnExec not respected
@@ -607,7 +607,7 @@ void TShellCommand::TImpl::StartProcess(TShellCommand::TImpl::TPipes& pipes) {
GetWString(User.Password.data()).c_str(),
0, // logon flags
NULL, // image name
- cmdcopy.Data(),
+ cmdcopy.Data(),
0, // obscure creation flags
lpEnvironment, // environment
cwd, // current directory
@@ -619,11 +619,11 @@ void TShellCommand::TImpl::StartProcess(TShellCommand::TImpl::TPipes& pipes) {
AtomicSet(ExecutionStatus, SHELL_ERROR);
/// @todo: write to error stream if set
TStringOutput out(CollectedError);
- out << "Process was not created: " << LastSystemErrorText() << " command text was: '" << GetAString(cmdcopy.Data()) << "'";
+ out << "Process was not created: " << LastSystemErrorText() << " command text was: '" << GetAString(cmdcopy.Data()) << "'";
}
- Pid = process_info.hProcess;
+ Pid = process_info.hProcess;
CloseHandle(process_info.hThread);
- DBG(Cerr << "created process id " << Pid << " in dir: " << cwd << ", cmd: " << cmdcopy.Data() << Endl);
+ DBG(Cerr << "created process id " << Pid << " in dir: " << cwd << ", cmd: " << cmdcopy.Data() << Endl);
}
#endif
@@ -1073,7 +1073,7 @@ void TShellCommand::TImpl::Communicate(TProcessInfo* pi) {
#else
if (waitPidResult == WAIT_OBJECT_0) {
DWORD exitCode = STILL_ACTIVE;
- if (!GetExitCodeProcess(pi->Parent->Pid, &exitCode)) {
+ if (!GetExitCodeProcess(pi->Parent->Pid, &exitCode)) {
ythrow yexception() << "GetExitCodeProcess: " << LastSystemErrorText();
}
if (exitCode == 0)
diff --git a/util/system/shellcommand_ut.cpp b/util/system/shellcommand_ut.cpp
index 9791617740..9d849279d2 100644
--- a/util/system/shellcommand_ut.cpp
+++ b/util/system/shellcommand_ut.cpp
@@ -1,5 +1,5 @@
#include "shellcommand.h"
-
+
#include "compat.h"
#include "defaults.h"
#include "fs.h"
@@ -266,7 +266,7 @@ Y_UNIT_TEST_SUITE(TShellCommandTest) {
void DoWrite(const void* buf, size_t len) override {
Y_UNUSED(buf);
Y_UNUSED(len);
- }
+ }
void DoFinish() override {
++NumCloses;
}
@@ -278,7 +278,7 @@ Y_UNIT_TEST_SUITE(TShellCommandTest) {
auto options = TShellCommandOptions().SetCloseStreams(true).SetOutputStream(&stream).SetErrorStream(&stream);
TShellCommand("echo hello", options).Run().Wait();
- UNIT_ASSERT_VALUES_EQUAL(stream.NumCloses, 2);
+ UNIT_ASSERT_VALUES_EQUAL(stream.NumCloses, 2);
}
Y_UNIT_TEST(TestInterruptSimple) {
TShellCommandOptions options;
diff --git a/util/system/ut/ya.make b/util/system/ut/ya.make
index 8dc3f6b7e1..127e7c261e 100644
--- a/util/system/ut/ya.make
+++ b/util/system/ut/ya.make
@@ -4,11 +4,11 @@ OWNER(g:util)
SUBSCRIBER(g:util-subscribers)
FORK_TESTS()
-
+
FORK_SUBTESTS()
-
+
SPLIT_FACTOR(40)
-
+
TIMEOUT(300)
SIZE(MEDIUM)
diff --git a/util/tests/cython/ya.make b/util/tests/cython/ya.make
index 58496b5e21..b928c19026 100644
--- a/util/tests/cython/ya.make
+++ b/util/tests/cython/ya.make
@@ -8,8 +8,8 @@ SRCDIR(util)
NO_WSHADOW()
PY_SRCS(
- NAMESPACE
- util
+ NAMESPACE
+ util
folder/path_ut.pyx
generic/array_ref_ut.pyx
generic/deque_ut.pyx
diff --git a/util/tests/sym_versions/ya.make b/util/tests/sym_versions/ya.make
index dbad2f60fd..3957c60fc9 100644
--- a/util/tests/sym_versions/ya.make
+++ b/util/tests/sym_versions/ya.make
@@ -1,13 +1,13 @@
PY2TEST()
-OWNER(
- pg
- g:util
+OWNER(
+ pg
+ g:util
)
SUBSCRIBER(g:util-subscribers)
-TEST_SRCS(test_glibc.py)
-
+TEST_SRCS(test_glibc.py)
+
PEERDIR(
library/python/resource
)
@@ -17,26 +17,26 @@ RESOURCE(
)
DEPENDS(
- # start binaries
- util/generic/ut
- util/charset/ut
- util/datetime/ut
- util/digest/ut
- util/draft/ut
- util/folder/ut
- util/memory/ut
- util/network/ut
- util/random/ut
- util/stream/ut
- util/string/ut
- util/system/ut
- util/thread/ut
- # end binaries
- contrib/python/pyelftools/readelf
+ # start binaries
+ util/generic/ut
+ util/charset/ut
+ util/datetime/ut
+ util/digest/ut
+ util/draft/ut
+ util/folder/ut
+ util/memory/ut
+ util/network/ut
+ util/random/ut
+ util/stream/ut
+ util/string/ut
+ util/system/ut
+ util/thread/ut
+ # end binaries
+ contrib/python/pyelftools/readelf
)
FORK_SUBTESTS()
-
+
SPLIT_FACTOR(10)
END()
diff --git a/util/tests/ya.make b/util/tests/ya.make
index c5bb4aeb7e..e1e85c2931 100644
--- a/util/tests/ya.make
+++ b/util/tests/ya.make
@@ -7,7 +7,7 @@ RECURSE(
)
IF (OS_LINUX)
- RECURSE(
- sym_versions
- )
+ RECURSE(
+ sym_versions
+ )
ENDIF()
diff --git a/util/ya.make b/util/ya.make
index edb7ce4faf..6ebe7e40cf 100644
--- a/util/ya.make
+++ b/util/ya.make
@@ -3,16 +3,16 @@ LIBRARY(yutil)
OWNER(g:util)
SUBSCRIBER(g:util-subscribers)
-NEED_CHECK()
-
+NEED_CHECK()
+
NO_UTIL()
-# stream
-# string
+# stream
+# string
PEERDIR(
util/charset
- contrib/libs/zlib
- contrib/libs/double-conversion
+ contrib/libs/zlib
+ contrib/libs/double-conversion
)
PEERDIR(
@@ -31,8 +31,8 @@ JOIN_SRCS(
SRCS(
datetime/parser.rl6
- digest/city.cpp
- random/random.cpp
+ digest/city.cpp
+ random/random.cpp
string/cast.cpp
)
diff --git a/ya.bat b/ya.bat
index e4d1231f5e..dc6eba5aed 100755
--- a/ya.bat
+++ b/ya.bat
@@ -1,86 +1,86 @@
-@echo off
-rem Ya Simple Windows launcher
-setlocal
-call :dbg Ya Simple Windows Launcher (Debug)
-call :find_ya
-if ERRORLEVEL 1 exit /b 1
-call :dbg Ya: %YA_BAT_REAL%
-call :fix_env
-call :find_python
-if ERRORLEVEL 1 exit /b 1
+@echo off
+rem Ya Simple Windows launcher
+setlocal
+call :dbg Ya Simple Windows Launcher (Debug)
+call :find_ya
+if ERRORLEVEL 1 exit /b 1
+call :dbg Ya: %YA_BAT_REAL%
+call :fix_env
+call :find_python
+if ERRORLEVEL 1 exit /b 1
call :dbg Python: "%YA_BAT_PYTHON%"
call "%YA_BAT_PYTHON%" "%YA_BAT_REAL%" %*
-exit /b %ERRORLEVEL%
-
-:find_ya
-call :dbg Searching for ya near ya.bat...
-set YA_BAT_REAL=%~dp0ya
+exit /b %ERRORLEVEL%
+
+:find_ya
+call :dbg Searching for ya near ya.bat...
+set YA_BAT_REAL=%~dp0ya
if exist "%YA_BAT_REAL%" exit /b 0
-call :err Ya not found
-exit /b 1
-
-:fix_env
-call :dbg Fixing environment...
-for /f "delims=: tokens=2" %%F in ('chcp') do (
- if "%%F" == " 65001" (
- call :dbg -- Forcing I/O encoding for python: utf-8
- set PYTHONIOENCODING=utf-8
- )
-)
-exit /b 0
-
-:find_python
-call :dbg Searching for python in PATH...
+call :err Ya not found
+exit /b 1
+
+:fix_env
+call :dbg Fixing environment...
+for /f "delims=: tokens=2" %%F in ('chcp') do (
+ if "%%F" == " 65001" (
+ call :dbg -- Forcing I/O encoding for python: utf-8
+ set PYTHONIOENCODING=utf-8
+ )
+)
+exit /b 0
+
+:find_python
+call :dbg Searching for python in PATH...
for /f "delims=" %%F in ('where python 2^>nul') do (
call :test_python %%~sF
- if not ERRORLEVEL 1 (
- set YA_BAT_PYTHON=%%F
- exit /b 0
- )
-)
-call :dbg Searching for python in ftypes...
-for /f delims^=^=^"^ tokens^=2 %%F in ('ftype Python.File 2^>nul') do (
- call :test_python %%F
- if not ERRORLEVEL 1 (
- set YA_BAT_PYTHON=%%F
- exit /b 0
- )
-)
-call :dbg Searching for python manually...
-for %%F in (
- C:\Python27\python.exe
- C:\Python26\python.exe
-) do (
- call :test_python %%F
- if not ERRORLEVEL 1 (
- set YA_BAT_PYTHON=%%F
- exit /b 0
- )
-)
-call :err Python not found
-exit /b 1
-
-:test_python
-call :dbg -- Checking python: %1
-if not exist %1 (
- call :dbg ---- Not found
- exit /b 1
-)
-for /f %%P in ('%1 -c "import os, sys; sys.stdout.write(os.name + '\n')" 2^>nul') do set YA_BAT_PYTHON_PLATFORM=%%P
-if not defined YA_BAT_PYTHON_PLATFORM (
- call :dbg ---- Not runnable
- exit /b 2
-)
-if not "%YA_BAT_PYTHON_PLATFORM%"=="nt" (
- call :dbg ---- Non-windows: %YA_BAT_PYTHON_PLATFORM%
- exit /b 3
-)
-exit /b 0
-
-:dbg
-if defined YA_BAT_DEBUG echo [ya.bat] %* 1>&2
-exit /b 0
-
-:err
-echo [ya.bat] Error: %* 1>&2
-exit /b 0
+ if not ERRORLEVEL 1 (
+ set YA_BAT_PYTHON=%%F
+ exit /b 0
+ )
+)
+call :dbg Searching for python in ftypes...
+for /f delims^=^=^"^ tokens^=2 %%F in ('ftype Python.File 2^>nul') do (
+ call :test_python %%F
+ if not ERRORLEVEL 1 (
+ set YA_BAT_PYTHON=%%F
+ exit /b 0
+ )
+)
+call :dbg Searching for python manually...
+for %%F in (
+ C:\Python27\python.exe
+ C:\Python26\python.exe
+) do (
+ call :test_python %%F
+ if not ERRORLEVEL 1 (
+ set YA_BAT_PYTHON=%%F
+ exit /b 0
+ )
+)
+call :err Python not found
+exit /b 1
+
+:test_python
+call :dbg -- Checking python: %1
+if not exist %1 (
+ call :dbg ---- Not found
+ exit /b 1
+)
+for /f %%P in ('%1 -c "import os, sys; sys.stdout.write(os.name + '\n')" 2^>nul') do set YA_BAT_PYTHON_PLATFORM=%%P
+if not defined YA_BAT_PYTHON_PLATFORM (
+ call :dbg ---- Not runnable
+ exit /b 2
+)
+if not "%YA_BAT_PYTHON_PLATFORM%"=="nt" (
+ call :dbg ---- Non-windows: %YA_BAT_PYTHON_PLATFORM%
+ exit /b 3
+)
+exit /b 0
+
+:dbg
+if defined YA_BAT_DEBUG echo [ya.bat] %* 1>&2
+exit /b 0
+
+:err
+echo [ya.bat] Error: %* 1>&2
+exit /b 0
diff --git a/ydb/core/blobstorage/vdisk/handoff/handoff_delegate.h b/ydb/core/blobstorage/vdisk/handoff/handoff_delegate.h
index a5150aa426..eaedc8bb04 100644
--- a/ydb/core/blobstorage/vdisk/handoff/handoff_delegate.h
+++ b/ydb/core/blobstorage/vdisk/handoff/handoff_delegate.h
@@ -12,7 +12,7 @@ namespace NKikimr {
template <class TKey, class TMemRec>
class THandoffMap;
- template <class TKey, class TMemRec>
+ template <class TKey, class TMemRec>
class TLevelIndexSnapshot;
////////////////////////////////////////////////////////////////////////////
diff --git a/ydb/library/yql/public/udf/udfs_exports.exports b/ydb/library/yql/public/udf/udfs_exports.exports
index bb38935e3f..c3af1d6045 100644
--- a/ydb/library/yql/public/udf/udfs_exports.exports
+++ b/ydb/library/yql/public/udf/udfs_exports.exports
@@ -1,4 +1,4 @@
-C Register
-C AbiVersion
+C Register
+C AbiVersion
C SetBackTraceCallback
C BindSymbols